Update .bashrc
[dotfiles/.git] / .config / coc / extensions / node_modules / coc-prettier / node_modules / prettier-eslint / node_modules / typescript / lib / typingsInstaller.js
1 /*! *****************************************************************************
2 Copyright (c) Microsoft Corporation. All rights reserved.
3 Licensed under the Apache License, Version 2.0 (the "License"); you may not use
4 this file except in compliance with the License. You may obtain a copy of the
5 License at http://www.apache.org/licenses/LICENSE-2.0
6
7 THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
8 KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
9 WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
10 MERCHANTABLITY OR NON-INFRINGEMENT.
11
12 See the Apache Version 2.0 License for specific language governing permissions
13 and limitations under the License.
14 ***************************************************************************** */
15
16
17 "use strict";
18 var __spreadArrays = (this && this.__spreadArrays) || function () {
19     for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;
20     for (var r = Array(s), k = 0, i = 0; i < il; i++)
21         for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)
22             r[k] = a[j];
23     return r;
24 };
25 var __assign = (this && this.__assign) || function () {
26     __assign = Object.assign || function(t) {
27         for (var s, i = 1, n = arguments.length; i < n; i++) {
28             s = arguments[i];
29             for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
30                 t[p] = s[p];
31         }
32         return t;
33     };
34     return __assign.apply(this, arguments);
35 };
36 var __generator = (this && this.__generator) || function (thisArg, body) {
37     var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
38     return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
39     function verb(n) { return function (v) { return step([n, v]); }; }
40     function step(op) {
41         if (f) throw new TypeError("Generator is already executing.");
42         while (_) try {
43             if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
44             if (y = 0, t) op = [op[0] & 2, t.value];
45             switch (op[0]) {
46                 case 0: case 1: t = op; break;
47                 case 4: _.label++; return { value: op[1], done: false };
48                 case 5: _.label++; y = op[1]; op = [0]; continue;
49                 case 7: op = _.ops.pop(); _.trys.pop(); continue;
50                 default:
51                     if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
52                     if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
53                     if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
54                     if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
55                     if (t[2]) _.ops.pop();
56                     _.trys.pop(); continue;
57             }
58             op = body.call(thisArg, _);
59         } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
60         if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
61     }
62 };
63 var __makeTemplateObject = (this && this.__makeTemplateObject) || function (cooked, raw) {
64     if (Object.defineProperty) { Object.defineProperty(cooked, "raw", { value: raw }); } else { cooked.raw = raw; }
65     return cooked;
66 };
67 var __extends = (this && this.__extends) || (function () {
68     var extendStatics = function (d, b) {
69         extendStatics = Object.setPrototypeOf ||
70             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
71             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
72         return extendStatics(d, b);
73     };
74     return function (d, b) {
75         extendStatics(d, b);
76         function __() { this.constructor = d; }
77         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
78     };
79 })();
80 var ts;
81 (function (ts) {
82     // WARNING: The script `configurePrerelease.ts` uses a regexp to parse out these values.
83     // If changing the text in this section, be sure to test `configurePrerelease` too.
84     ts.versionMajorMinor = "3.9";
85     /** The version of the TypeScript compiler release */
86     ts.version = "3.9.10";
87     /**
88      * Returns the native Map implementation if it is available and compatible (i.e. supports iteration).
89      */
90     /* @internal */
91     function tryGetNativeMap() {
92         // eslint-disable-next-line no-in-operator
93         return typeof Map !== "undefined" && "entries" in Map.prototype ? Map : undefined;
94     }
95     ts.tryGetNativeMap = tryGetNativeMap;
96     /* @internal */
97     ts.Map = tryGetNativeMap() || (function () {
98         // NOTE: createMapShim will be defined for typescriptServices.js but not for tsc.js, so we must test for it.
99         if (typeof ts.createMapShim === "function") {
100             return ts.createMapShim();
101         }
102         throw new Error("TypeScript requires an environment that provides a compatible native Map implementation.");
103     })();
104     /* @internal */
105     var Comparison;
106     (function (Comparison) {
107         Comparison[Comparison["LessThan"] = -1] = "LessThan";
108         Comparison[Comparison["EqualTo"] = 0] = "EqualTo";
109         Comparison[Comparison["GreaterThan"] = 1] = "GreaterThan";
110     })(Comparison = ts.Comparison || (ts.Comparison = {}));
111 })(ts || (ts = {}));
112 /* @internal */
113 var ts;
114 (function (ts) {
115     ts.emptyArray = [];
116     /** Create a new map. */
117     function createMap() {
118         return new ts.Map();
119     }
120     ts.createMap = createMap;
121     /** Create a new map from an array of entries. */
122     function createMapFromEntries(entries) {
123         var map = createMap();
124         for (var _i = 0, entries_1 = entries; _i < entries_1.length; _i++) {
125             var _a = entries_1[_i], key = _a[0], value = _a[1];
126             map.set(key, value);
127         }
128         return map;
129     }
130     ts.createMapFromEntries = createMapFromEntries;
131     /** Create a new map from a template object is provided, the map will copy entries from it. */
132     function createMapFromTemplate(template) {
133         var map = new ts.Map();
134         // Copies keys/values from template. Note that for..in will not throw if
135         // template is undefined, and instead will just exit the loop.
136         for (var key in template) {
137             if (hasOwnProperty.call(template, key)) {
138                 map.set(key, template[key]);
139             }
140         }
141         return map;
142     }
143     ts.createMapFromTemplate = createMapFromTemplate;
144     function length(array) {
145         return array ? array.length : 0;
146     }
147     ts.length = length;
148     /**
149      * Iterates through 'array' by index and performs the callback on each element of array until the callback
150      * returns a truthy value, then returns that value.
151      * If no such value is found, the callback is applied to each element of array and undefined is returned.
152      */
153     function forEach(array, callback) {
154         if (array) {
155             for (var i = 0; i < array.length; i++) {
156                 var result = callback(array[i], i);
157                 if (result) {
158                     return result;
159                 }
160             }
161         }
162         return undefined;
163     }
164     ts.forEach = forEach;
165     /**
166      * Like `forEach`, but iterates in reverse order.
167      */
168     function forEachRight(array, callback) {
169         if (array) {
170             for (var i = array.length - 1; i >= 0; i--) {
171                 var result = callback(array[i], i);
172                 if (result) {
173                     return result;
174                 }
175             }
176         }
177         return undefined;
178     }
179     ts.forEachRight = forEachRight;
180     /** Like `forEach`, but suitable for use with numbers and strings (which may be falsy). */
181     function firstDefined(array, callback) {
182         if (array === undefined) {
183             return undefined;
184         }
185         for (var i = 0; i < array.length; i++) {
186             var result = callback(array[i], i);
187             if (result !== undefined) {
188                 return result;
189             }
190         }
191         return undefined;
192     }
193     ts.firstDefined = firstDefined;
194     function firstDefinedIterator(iter, callback) {
195         while (true) {
196             var iterResult = iter.next();
197             if (iterResult.done) {
198                 return undefined;
199             }
200             var result = callback(iterResult.value);
201             if (result !== undefined) {
202                 return result;
203             }
204         }
205     }
206     ts.firstDefinedIterator = firstDefinedIterator;
207     function zipWith(arrayA, arrayB, callback) {
208         var result = [];
209         ts.Debug.assertEqual(arrayA.length, arrayB.length);
210         for (var i = 0; i < arrayA.length; i++) {
211             result.push(callback(arrayA[i], arrayB[i], i));
212         }
213         return result;
214     }
215     ts.zipWith = zipWith;
216     function zipToIterator(arrayA, arrayB) {
217         ts.Debug.assertEqual(arrayA.length, arrayB.length);
218         var i = 0;
219         return {
220             next: function () {
221                 if (i === arrayA.length) {
222                     return { value: undefined, done: true };
223                 }
224                 i++;
225                 return { value: [arrayA[i - 1], arrayB[i - 1]], done: false };
226             }
227         };
228     }
229     ts.zipToIterator = zipToIterator;
230     function zipToMap(keys, values) {
231         ts.Debug.assert(keys.length === values.length);
232         var map = createMap();
233         for (var i = 0; i < keys.length; ++i) {
234             map.set(keys[i], values[i]);
235         }
236         return map;
237     }
238     ts.zipToMap = zipToMap;
239     /**
240      * Iterates through `array` by index and performs the callback on each element of array until the callback
241      * returns a falsey value, then returns false.
242      * If no such value is found, the callback is applied to each element of array and `true` is returned.
243      */
244     function every(array, callback) {
245         if (array) {
246             for (var i = 0; i < array.length; i++) {
247                 if (!callback(array[i], i)) {
248                     return false;
249                 }
250             }
251         }
252         return true;
253     }
254     ts.every = every;
255     function find(array, predicate) {
256         for (var i = 0; i < array.length; i++) {
257             var value = array[i];
258             if (predicate(value, i)) {
259                 return value;
260             }
261         }
262         return undefined;
263     }
264     ts.find = find;
265     function findLast(array, predicate) {
266         for (var i = array.length - 1; i >= 0; i--) {
267             var value = array[i];
268             if (predicate(value, i)) {
269                 return value;
270             }
271         }
272         return undefined;
273     }
274     ts.findLast = findLast;
275     /** Works like Array.prototype.findIndex, returning `-1` if no element satisfying the predicate is found. */
276     function findIndex(array, predicate, startIndex) {
277         for (var i = startIndex || 0; i < array.length; i++) {
278             if (predicate(array[i], i)) {
279                 return i;
280             }
281         }
282         return -1;
283     }
284     ts.findIndex = findIndex;
285     function findLastIndex(array, predicate, startIndex) {
286         for (var i = startIndex === undefined ? array.length - 1 : startIndex; i >= 0; i--) {
287             if (predicate(array[i], i)) {
288                 return i;
289             }
290         }
291         return -1;
292     }
293     ts.findLastIndex = findLastIndex;
294     /**
295      * Returns the first truthy result of `callback`, or else fails.
296      * This is like `forEach`, but never returns undefined.
297      */
298     function findMap(array, callback) {
299         for (var i = 0; i < array.length; i++) {
300             var result = callback(array[i], i);
301             if (result) {
302                 return result;
303             }
304         }
305         return ts.Debug.fail();
306     }
307     ts.findMap = findMap;
308     function contains(array, value, equalityComparer) {
309         if (equalityComparer === void 0) { equalityComparer = equateValues; }
310         if (array) {
311             for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
312                 var v = array_1[_i];
313                 if (equalityComparer(v, value)) {
314                     return true;
315                 }
316             }
317         }
318         return false;
319     }
320     ts.contains = contains;
321     function arraysEqual(a, b, equalityComparer) {
322         if (equalityComparer === void 0) { equalityComparer = equateValues; }
323         return a.length === b.length && a.every(function (x, i) { return equalityComparer(x, b[i]); });
324     }
325     ts.arraysEqual = arraysEqual;
326     function indexOfAnyCharCode(text, charCodes, start) {
327         for (var i = start || 0; i < text.length; i++) {
328             if (contains(charCodes, text.charCodeAt(i))) {
329                 return i;
330             }
331         }
332         return -1;
333     }
334     ts.indexOfAnyCharCode = indexOfAnyCharCode;
335     function countWhere(array, predicate) {
336         var count = 0;
337         if (array) {
338             for (var i = 0; i < array.length; i++) {
339                 var v = array[i];
340                 if (predicate(v, i)) {
341                     count++;
342                 }
343             }
344         }
345         return count;
346     }
347     ts.countWhere = countWhere;
348     function filter(array, f) {
349         if (array) {
350             var len = array.length;
351             var i = 0;
352             while (i < len && f(array[i]))
353                 i++;
354             if (i < len) {
355                 var result = array.slice(0, i);
356                 i++;
357                 while (i < len) {
358                     var item = array[i];
359                     if (f(item)) {
360                         result.push(item);
361                     }
362                     i++;
363                 }
364                 return result;
365             }
366         }
367         return array;
368     }
369     ts.filter = filter;
370     function filterMutate(array, f) {
371         var outIndex = 0;
372         for (var i = 0; i < array.length; i++) {
373             if (f(array[i], i, array)) {
374                 array[outIndex] = array[i];
375                 outIndex++;
376             }
377         }
378         array.length = outIndex;
379     }
380     ts.filterMutate = filterMutate;
381     function clear(array) {
382         array.length = 0;
383     }
384     ts.clear = clear;
385     function map(array, f) {
386         var result;
387         if (array) {
388             result = [];
389             for (var i = 0; i < array.length; i++) {
390                 result.push(f(array[i], i));
391             }
392         }
393         return result;
394     }
395     ts.map = map;
396     function mapIterator(iter, mapFn) {
397         return {
398             next: function () {
399                 var iterRes = iter.next();
400                 return iterRes.done ? iterRes : { value: mapFn(iterRes.value), done: false };
401             }
402         };
403     }
404     ts.mapIterator = mapIterator;
405     function sameMap(array, f) {
406         if (array) {
407             for (var i = 0; i < array.length; i++) {
408                 var item = array[i];
409                 var mapped = f(item, i);
410                 if (item !== mapped) {
411                     var result = array.slice(0, i);
412                     result.push(mapped);
413                     for (i++; i < array.length; i++) {
414                         result.push(f(array[i], i));
415                     }
416                     return result;
417                 }
418             }
419         }
420         return array;
421     }
422     ts.sameMap = sameMap;
423     /**
424      * Flattens an array containing a mix of array or non-array elements.
425      *
426      * @param array The array to flatten.
427      */
428     function flatten(array) {
429         var result = [];
430         for (var _i = 0, array_2 = array; _i < array_2.length; _i++) {
431             var v = array_2[_i];
432             if (v) {
433                 if (isArray(v)) {
434                     addRange(result, v);
435                 }
436                 else {
437                     result.push(v);
438                 }
439             }
440         }
441         return result;
442     }
443     ts.flatten = flatten;
444     /**
445      * Maps an array. If the mapped value is an array, it is spread into the result.
446      *
447      * @param array The array to map.
448      * @param mapfn The callback used to map the result into one or more values.
449      */
450     function flatMap(array, mapfn) {
451         var result;
452         if (array) {
453             for (var i = 0; i < array.length; i++) {
454                 var v = mapfn(array[i], i);
455                 if (v) {
456                     if (isArray(v)) {
457                         result = addRange(result, v);
458                     }
459                     else {
460                         result = append(result, v);
461                     }
462                 }
463             }
464         }
465         return result || ts.emptyArray;
466     }
467     ts.flatMap = flatMap;
468     function flatMapToMutable(array, mapfn) {
469         var result = [];
470         if (array) {
471             for (var i = 0; i < array.length; i++) {
472                 var v = mapfn(array[i], i);
473                 if (v) {
474                     if (isArray(v)) {
475                         addRange(result, v);
476                     }
477                     else {
478                         result.push(v);
479                     }
480                 }
481             }
482         }
483         return result;
484     }
485     ts.flatMapToMutable = flatMapToMutable;
486     function flatMapIterator(iter, mapfn) {
487         var first = iter.next();
488         if (first.done) {
489             return ts.emptyIterator;
490         }
491         var currentIter = getIterator(first.value);
492         return {
493             next: function () {
494                 while (true) {
495                     var currentRes = currentIter.next();
496                     if (!currentRes.done) {
497                         return currentRes;
498                     }
499                     var iterRes = iter.next();
500                     if (iterRes.done) {
501                         return iterRes;
502                     }
503                     currentIter = getIterator(iterRes.value);
504                 }
505             },
506         };
507         function getIterator(x) {
508             var res = mapfn(x);
509             return res === undefined ? ts.emptyIterator : isArray(res) ? arrayIterator(res) : res;
510         }
511     }
512     ts.flatMapIterator = flatMapIterator;
513     function sameFlatMap(array, mapfn) {
514         var result;
515         if (array) {
516             for (var i = 0; i < array.length; i++) {
517                 var item = array[i];
518                 var mapped = mapfn(item, i);
519                 if (result || item !== mapped || isArray(mapped)) {
520                     if (!result) {
521                         result = array.slice(0, i);
522                     }
523                     if (isArray(mapped)) {
524                         addRange(result, mapped);
525                     }
526                     else {
527                         result.push(mapped);
528                     }
529                 }
530             }
531         }
532         return result || array;
533     }
534     ts.sameFlatMap = sameFlatMap;
535     function mapAllOrFail(array, mapFn) {
536         var result = [];
537         for (var i = 0; i < array.length; i++) {
538             var mapped = mapFn(array[i], i);
539             if (mapped === undefined) {
540                 return undefined;
541             }
542             result.push(mapped);
543         }
544         return result;
545     }
546     ts.mapAllOrFail = mapAllOrFail;
547     function mapDefined(array, mapFn) {
548         var result = [];
549         if (array) {
550             for (var i = 0; i < array.length; i++) {
551                 var mapped = mapFn(array[i], i);
552                 if (mapped !== undefined) {
553                     result.push(mapped);
554                 }
555             }
556         }
557         return result;
558     }
559     ts.mapDefined = mapDefined;
560     function mapDefinedIterator(iter, mapFn) {
561         return {
562             next: function () {
563                 while (true) {
564                     var res = iter.next();
565                     if (res.done) {
566                         return res;
567                     }
568                     var value = mapFn(res.value);
569                     if (value !== undefined) {
570                         return { value: value, done: false };
571                     }
572                 }
573             }
574         };
575     }
576     ts.mapDefinedIterator = mapDefinedIterator;
577     function mapDefinedMap(map, mapValue, mapKey) {
578         if (mapKey === void 0) { mapKey = identity; }
579         var result = createMap();
580         map.forEach(function (value, key) {
581             var mapped = mapValue(value, key);
582             if (mapped !== undefined) {
583                 result.set(mapKey(key), mapped);
584             }
585         });
586         return result;
587     }
588     ts.mapDefinedMap = mapDefinedMap;
589     ts.emptyIterator = { next: function () { return ({ value: undefined, done: true }); } };
590     function singleIterator(value) {
591         var done = false;
592         return {
593             next: function () {
594                 var wasDone = done;
595                 done = true;
596                 return wasDone ? { value: undefined, done: true } : { value: value, done: false };
597             }
598         };
599     }
600     ts.singleIterator = singleIterator;
601     function spanMap(array, keyfn, mapfn) {
602         var result;
603         if (array) {
604             result = [];
605             var len = array.length;
606             var previousKey = void 0;
607             var key = void 0;
608             var start = 0;
609             var pos = 0;
610             while (start < len) {
611                 while (pos < len) {
612                     var value = array[pos];
613                     key = keyfn(value, pos);
614                     if (pos === 0) {
615                         previousKey = key;
616                     }
617                     else if (key !== previousKey) {
618                         break;
619                     }
620                     pos++;
621                 }
622                 if (start < pos) {
623                     var v = mapfn(array.slice(start, pos), previousKey, start, pos);
624                     if (v) {
625                         result.push(v);
626                     }
627                     start = pos;
628                 }
629                 previousKey = key;
630                 pos++;
631             }
632         }
633         return result;
634     }
635     ts.spanMap = spanMap;
636     function mapEntries(map, f) {
637         if (!map) {
638             return undefined;
639         }
640         var result = createMap();
641         map.forEach(function (value, key) {
642             var _a = f(key, value), newKey = _a[0], newValue = _a[1];
643             result.set(newKey, newValue);
644         });
645         return result;
646     }
647     ts.mapEntries = mapEntries;
648     function some(array, predicate) {
649         if (array) {
650             if (predicate) {
651                 for (var _i = 0, array_3 = array; _i < array_3.length; _i++) {
652                     var v = array_3[_i];
653                     if (predicate(v)) {
654                         return true;
655                     }
656                 }
657             }
658             else {
659                 return array.length > 0;
660             }
661         }
662         return false;
663     }
664     ts.some = some;
665     /** Calls the callback with (start, afterEnd) index pairs for each range where 'pred' is true. */
666     function getRangesWhere(arr, pred, cb) {
667         var start;
668         for (var i = 0; i < arr.length; i++) {
669             if (pred(arr[i])) {
670                 start = start === undefined ? i : start;
671             }
672             else {
673                 if (start !== undefined) {
674                     cb(start, i);
675                     start = undefined;
676                 }
677             }
678         }
679         if (start !== undefined)
680             cb(start, arr.length);
681     }
682     ts.getRangesWhere = getRangesWhere;
683     function concatenate(array1, array2) {
684         if (!some(array2))
685             return array1;
686         if (!some(array1))
687             return array2;
688         return __spreadArrays(array1, array2);
689     }
690     ts.concatenate = concatenate;
691     function selectIndex(_, i) {
692         return i;
693     }
694     function indicesOf(array) {
695         return array.map(selectIndex);
696     }
697     ts.indicesOf = indicesOf;
698     function deduplicateRelational(array, equalityComparer, comparer) {
699         // Perform a stable sort of the array. This ensures the first entry in a list of
700         // duplicates remains the first entry in the result.
701         var indices = indicesOf(array);
702         stableSortIndices(array, indices, comparer);
703         var last = array[indices[0]];
704         var deduplicated = [indices[0]];
705         for (var i = 1; i < indices.length; i++) {
706             var index = indices[i];
707             var item = array[index];
708             if (!equalityComparer(last, item)) {
709                 deduplicated.push(index);
710                 last = item;
711             }
712         }
713         // restore original order
714         deduplicated.sort();
715         return deduplicated.map(function (i) { return array[i]; });
716     }
717     function deduplicateEquality(array, equalityComparer) {
718         var result = [];
719         for (var _i = 0, array_4 = array; _i < array_4.length; _i++) {
720             var item = array_4[_i];
721             pushIfUnique(result, item, equalityComparer);
722         }
723         return result;
724     }
725     /**
726      * Deduplicates an unsorted array.
727      * @param equalityComparer An `EqualityComparer` used to determine if two values are duplicates.
728      * @param comparer An optional `Comparer` used to sort entries before comparison, though the
729      * result will remain in the original order in `array`.
730      */
731     function deduplicate(array, equalityComparer, comparer) {
732         return array.length === 0 ? [] :
733             array.length === 1 ? array.slice() :
734                 comparer ? deduplicateRelational(array, equalityComparer, comparer) :
735                     deduplicateEquality(array, equalityComparer);
736     }
737     ts.deduplicate = deduplicate;
738     /**
739      * Deduplicates an array that has already been sorted.
740      */
741     function deduplicateSorted(array, comparer) {
742         if (array.length === 0)
743             return ts.emptyArray;
744         var last = array[0];
745         var deduplicated = [last];
746         for (var i = 1; i < array.length; i++) {
747             var next = array[i];
748             switch (comparer(next, last)) {
749                 // equality comparison
750                 case true:
751                 // relational comparison
752                 // falls through
753                 case 0 /* EqualTo */:
754                     continue;
755                 case -1 /* LessThan */:
756                     // If `array` is sorted, `next` should **never** be less than `last`.
757                     return ts.Debug.fail("Array is unsorted.");
758             }
759             deduplicated.push(last = next);
760         }
761         return deduplicated;
762     }
763     function insertSorted(array, insert, compare) {
764         if (array.length === 0) {
765             array.push(insert);
766             return;
767         }
768         var insertIndex = binarySearch(array, insert, identity, compare);
769         if (insertIndex < 0) {
770             array.splice(~insertIndex, 0, insert);
771         }
772     }
773     ts.insertSorted = insertSorted;
774     function sortAndDeduplicate(array, comparer, equalityComparer) {
775         return deduplicateSorted(sort(array, comparer), equalityComparer || comparer || compareStringsCaseSensitive);
776     }
777     ts.sortAndDeduplicate = sortAndDeduplicate;
778     function arrayIsEqualTo(array1, array2, equalityComparer) {
779         if (equalityComparer === void 0) { equalityComparer = equateValues; }
780         if (!array1 || !array2) {
781             return array1 === array2;
782         }
783         if (array1.length !== array2.length) {
784             return false;
785         }
786         for (var i = 0; i < array1.length; i++) {
787             if (!equalityComparer(array1[i], array2[i], i)) {
788                 return false;
789             }
790         }
791         return true;
792     }
793     ts.arrayIsEqualTo = arrayIsEqualTo;
794     function compact(array) {
795         var result;
796         if (array) {
797             for (var i = 0; i < array.length; i++) {
798                 var v = array[i];
799                 if (result || !v) {
800                     if (!result) {
801                         result = array.slice(0, i);
802                     }
803                     if (v) {
804                         result.push(v);
805                     }
806                 }
807             }
808         }
809         return result || array;
810     }
811     ts.compact = compact;
812     /**
813      * Gets the relative complement of `arrayA` with respect to `arrayB`, returning the elements that
814      * are not present in `arrayA` but are present in `arrayB`. Assumes both arrays are sorted
815      * based on the provided comparer.
816      */
817     function relativeComplement(arrayA, arrayB, comparer) {
818         if (!arrayB || !arrayA || arrayB.length === 0 || arrayA.length === 0)
819             return arrayB;
820         var result = [];
821         loopB: for (var offsetA = 0, offsetB = 0; offsetB < arrayB.length; offsetB++) {
822             if (offsetB > 0) {
823                 // Ensure `arrayB` is properly sorted.
824                 ts.Debug.assertGreaterThanOrEqual(comparer(arrayB[offsetB], arrayB[offsetB - 1]), 0 /* EqualTo */);
825             }
826             loopA: for (var startA = offsetA; offsetA < arrayA.length; offsetA++) {
827                 if (offsetA > startA) {
828                     // Ensure `arrayA` is properly sorted. We only need to perform this check if
829                     // `offsetA` has changed since we entered the loop.
830                     ts.Debug.assertGreaterThanOrEqual(comparer(arrayA[offsetA], arrayA[offsetA - 1]), 0 /* EqualTo */);
831                 }
832                 switch (comparer(arrayB[offsetB], arrayA[offsetA])) {
833                     case -1 /* LessThan */:
834                         // If B is less than A, B does not exist in arrayA. Add B to the result and
835                         // move to the next element in arrayB without changing the current position
836                         // in arrayA.
837                         result.push(arrayB[offsetB]);
838                         continue loopB;
839                     case 0 /* EqualTo */:
840                         // If B is equal to A, B exists in arrayA. Move to the next element in
841                         // arrayB without adding B to the result or changing the current position
842                         // in arrayA.
843                         continue loopB;
844                     case 1 /* GreaterThan */:
845                         // If B is greater than A, we need to keep looking for B in arrayA. Move to
846                         // the next element in arrayA and recheck.
847                         continue loopA;
848                 }
849             }
850         }
851         return result;
852     }
853     ts.relativeComplement = relativeComplement;
854     function sum(array, prop) {
855         var result = 0;
856         for (var _i = 0, array_5 = array; _i < array_5.length; _i++) {
857             var v = array_5[_i];
858             result += v[prop];
859         }
860         return result;
861     }
862     ts.sum = sum;
863     function append(to, value) {
864         if (value === undefined)
865             return to;
866         if (to === undefined)
867             return [value];
868         to.push(value);
869         return to;
870     }
871     ts.append = append;
872     function combine(xs, ys) {
873         if (xs === undefined)
874             return ys;
875         if (ys === undefined)
876             return xs;
877         if (isArray(xs))
878             return isArray(ys) ? concatenate(xs, ys) : append(xs, ys);
879         if (isArray(ys))
880             return append(ys, xs);
881         return [xs, ys];
882     }
883     ts.combine = combine;
884     /**
885      * Gets the actual offset into an array for a relative offset. Negative offsets indicate a
886      * position offset from the end of the array.
887      */
888     function toOffset(array, offset) {
889         return offset < 0 ? array.length + offset : offset;
890     }
891     function addRange(to, from, start, end) {
892         if (from === undefined || from.length === 0)
893             return to;
894         if (to === undefined)
895             return from.slice(start, end);
896         start = start === undefined ? 0 : toOffset(from, start);
897         end = end === undefined ? from.length : toOffset(from, end);
898         for (var i = start; i < end && i < from.length; i++) {
899             if (from[i] !== undefined) {
900                 to.push(from[i]);
901             }
902         }
903         return to;
904     }
905     ts.addRange = addRange;
906     /**
907      * @return Whether the value was added.
908      */
909     function pushIfUnique(array, toAdd, equalityComparer) {
910         if (contains(array, toAdd, equalityComparer)) {
911             return false;
912         }
913         else {
914             array.push(toAdd);
915             return true;
916         }
917     }
918     ts.pushIfUnique = pushIfUnique;
919     /**
920      * Unlike `pushIfUnique`, this can take `undefined` as an input, and returns a new array.
921      */
922     function appendIfUnique(array, toAdd, equalityComparer) {
923         if (array) {
924             pushIfUnique(array, toAdd, equalityComparer);
925             return array;
926         }
927         else {
928             return [toAdd];
929         }
930     }
931     ts.appendIfUnique = appendIfUnique;
932     function stableSortIndices(array, indices, comparer) {
933         // sort indices by value then position
934         indices.sort(function (x, y) { return comparer(array[x], array[y]) || compareValues(x, y); });
935     }
936     /**
937      * Returns a new sorted array.
938      */
939     function sort(array, comparer) {
940         return (array.length === 0 ? array : array.slice().sort(comparer));
941     }
942     ts.sort = sort;
943     function arrayIterator(array) {
944         var i = 0;
945         return { next: function () {
946                 if (i === array.length) {
947                     return { value: undefined, done: true };
948                 }
949                 else {
950                     i++;
951                     return { value: array[i - 1], done: false };
952                 }
953             } };
954     }
955     ts.arrayIterator = arrayIterator;
956     function arrayReverseIterator(array) {
957         var i = array.length;
958         return {
959             next: function () {
960                 if (i === 0) {
961                     return { value: undefined, done: true };
962                 }
963                 else {
964                     i--;
965                     return { value: array[i], done: false };
966                 }
967             }
968         };
969     }
970     ts.arrayReverseIterator = arrayReverseIterator;
971     /**
972      * Stable sort of an array. Elements equal to each other maintain their relative position in the array.
973      */
974     function stableSort(array, comparer) {
975         var indices = indicesOf(array);
976         stableSortIndices(array, indices, comparer);
977         return indices.map(function (i) { return array[i]; });
978     }
979     ts.stableSort = stableSort;
980     function rangeEquals(array1, array2, pos, end) {
981         while (pos < end) {
982             if (array1[pos] !== array2[pos]) {
983                 return false;
984             }
985             pos++;
986         }
987         return true;
988     }
989     ts.rangeEquals = rangeEquals;
990     /**
991      * Returns the element at a specific offset in an array if non-empty, `undefined` otherwise.
992      * A negative offset indicates the element should be retrieved from the end of the array.
993      */
994     function elementAt(array, offset) {
995         if (array) {
996             offset = toOffset(array, offset);
997             if (offset < array.length) {
998                 return array[offset];
999             }
1000         }
1001         return undefined;
1002     }
1003     ts.elementAt = elementAt;
1004     /**
1005      * Returns the first element of an array if non-empty, `undefined` otherwise.
1006      */
1007     function firstOrUndefined(array) {
1008         return array.length === 0 ? undefined : array[0];
1009     }
1010     ts.firstOrUndefined = firstOrUndefined;
1011     function first(array) {
1012         ts.Debug.assert(array.length !== 0);
1013         return array[0];
1014     }
1015     ts.first = first;
1016     /**
1017      * Returns the last element of an array if non-empty, `undefined` otherwise.
1018      */
1019     function lastOrUndefined(array) {
1020         return array.length === 0 ? undefined : array[array.length - 1];
1021     }
1022     ts.lastOrUndefined = lastOrUndefined;
1023     function last(array) {
1024         ts.Debug.assert(array.length !== 0);
1025         return array[array.length - 1];
1026     }
1027     ts.last = last;
1028     /**
1029      * Returns the only element of an array if it contains only one element, `undefined` otherwise.
1030      */
1031     function singleOrUndefined(array) {
1032         return array && array.length === 1
1033             ? array[0]
1034             : undefined;
1035     }
1036     ts.singleOrUndefined = singleOrUndefined;
1037     function singleOrMany(array) {
1038         return array && array.length === 1
1039             ? array[0]
1040             : array;
1041     }
1042     ts.singleOrMany = singleOrMany;
1043     function replaceElement(array, index, value) {
1044         var result = array.slice(0);
1045         result[index] = value;
1046         return result;
1047     }
1048     ts.replaceElement = replaceElement;
1049     /**
1050      * Performs a binary search, finding the index at which `value` occurs in `array`.
1051      * If no such index is found, returns the 2's-complement of first index at which
1052      * `array[index]` exceeds `value`.
1053      * @param array A sorted array whose first element must be no larger than number
1054      * @param value The value to be searched for in the array.
1055      * @param keySelector A callback used to select the search key from `value` and each element of
1056      * `array`.
1057      * @param keyComparer A callback used to compare two keys in a sorted array.
1058      * @param offset An offset into `array` at which to start the search.
1059      */
1060     function binarySearch(array, value, keySelector, keyComparer, offset) {
1061         return binarySearchKey(array, keySelector(value), keySelector, keyComparer, offset);
1062     }
1063     ts.binarySearch = binarySearch;
1064     /**
1065      * Performs a binary search, finding the index at which an object with `key` occurs in `array`.
1066      * If no such index is found, returns the 2's-complement of first index at which
1067      * `array[index]` exceeds `key`.
1068      * @param array A sorted array whose first element must be no larger than number
1069      * @param key The key to be searched for in the array.
1070      * @param keySelector A callback used to select the search key from each element of `array`.
1071      * @param keyComparer A callback used to compare two keys in a sorted array.
1072      * @param offset An offset into `array` at which to start the search.
1073      */
1074     function binarySearchKey(array, key, keySelector, keyComparer, offset) {
1075         if (!some(array)) {
1076             return -1;
1077         }
1078         var low = offset || 0;
1079         var high = array.length - 1;
1080         while (low <= high) {
1081             var middle = low + ((high - low) >> 1);
1082             var midKey = keySelector(array[middle]);
1083             switch (keyComparer(midKey, key)) {
1084                 case -1 /* LessThan */:
1085                     low = middle + 1;
1086                     break;
1087                 case 0 /* EqualTo */:
1088                     return middle;
1089                 case 1 /* GreaterThan */:
1090                     high = middle - 1;
1091                     break;
1092             }
1093         }
1094         return ~low;
1095     }
1096     ts.binarySearchKey = binarySearchKey;
1097     function reduceLeft(array, f, initial, start, count) {
1098         if (array && array.length > 0) {
1099             var size = array.length;
1100             if (size > 0) {
1101                 var pos = start === undefined || start < 0 ? 0 : start;
1102                 var end = count === undefined || pos + count > size - 1 ? size - 1 : pos + count;
1103                 var result = void 0;
1104                 if (arguments.length <= 2) {
1105                     result = array[pos];
1106                     pos++;
1107                 }
1108                 else {
1109                     result = initial;
1110                 }
1111                 while (pos <= end) {
1112                     result = f(result, array[pos], pos);
1113                     pos++;
1114                 }
1115                 return result;
1116             }
1117         }
1118         return initial;
1119     }
1120     ts.reduceLeft = reduceLeft;
1121     var hasOwnProperty = Object.prototype.hasOwnProperty;
1122     /**
1123      * Indicates whether a map-like contains an own property with the specified key.
1124      *
1125      * @param map A map-like.
1126      * @param key A property key.
1127      */
1128     function hasProperty(map, key) {
1129         return hasOwnProperty.call(map, key);
1130     }
1131     ts.hasProperty = hasProperty;
1132     /**
1133      * Gets the value of an owned property in a map-like.
1134      *
1135      * @param map A map-like.
1136      * @param key A property key.
1137      */
1138     function getProperty(map, key) {
1139         return hasOwnProperty.call(map, key) ? map[key] : undefined;
1140     }
1141     ts.getProperty = getProperty;
1142     /**
1143      * Gets the owned, enumerable property keys of a map-like.
1144      */
1145     function getOwnKeys(map) {
1146         var keys = [];
1147         for (var key in map) {
1148             if (hasOwnProperty.call(map, key)) {
1149                 keys.push(key);
1150             }
1151         }
1152         return keys;
1153     }
1154     ts.getOwnKeys = getOwnKeys;
1155     function getAllKeys(obj) {
1156         var result = [];
1157         do {
1158             var names = Object.getOwnPropertyNames(obj);
1159             for (var _i = 0, names_1 = names; _i < names_1.length; _i++) {
1160                 var name = names_1[_i];
1161                 pushIfUnique(result, name);
1162             }
1163         } while (obj = Object.getPrototypeOf(obj));
1164         return result;
1165     }
1166     ts.getAllKeys = getAllKeys;
1167     function getOwnValues(sparseArray) {
1168         var values = [];
1169         for (var key in sparseArray) {
1170             if (hasOwnProperty.call(sparseArray, key)) {
1171                 values.push(sparseArray[key]);
1172             }
1173         }
1174         return values;
1175     }
1176     ts.getOwnValues = getOwnValues;
1177     function arrayFrom(iterator, map) {
1178         var result = [];
1179         for (var iterResult = iterator.next(); !iterResult.done; iterResult = iterator.next()) {
1180             result.push(map ? map(iterResult.value) : iterResult.value);
1181         }
1182         return result;
1183     }
1184     ts.arrayFrom = arrayFrom;
1185     function assign(t) {
1186         var args = [];
1187         for (var _i = 1; _i < arguments.length; _i++) {
1188             args[_i - 1] = arguments[_i];
1189         }
1190         for (var _a = 0, args_1 = args; _a < args_1.length; _a++) {
1191             var arg = args_1[_a];
1192             if (arg === undefined)
1193                 continue;
1194             for (var p in arg) {
1195                 if (hasProperty(arg, p)) {
1196                     t[p] = arg[p];
1197                 }
1198             }
1199         }
1200         return t;
1201     }
1202     ts.assign = assign;
1203     /**
1204      * Performs a shallow equality comparison of the contents of two map-likes.
1205      *
1206      * @param left A map-like whose properties should be compared.
1207      * @param right A map-like whose properties should be compared.
1208      */
1209     function equalOwnProperties(left, right, equalityComparer) {
1210         if (equalityComparer === void 0) { equalityComparer = equateValues; }
1211         if (left === right)
1212             return true;
1213         if (!left || !right)
1214             return false;
1215         for (var key in left) {
1216             if (hasOwnProperty.call(left, key)) {
1217                 if (!hasOwnProperty.call(right, key))
1218                     return false;
1219                 if (!equalityComparer(left[key], right[key]))
1220                     return false;
1221             }
1222         }
1223         for (var key in right) {
1224             if (hasOwnProperty.call(right, key)) {
1225                 if (!hasOwnProperty.call(left, key))
1226                     return false;
1227             }
1228         }
1229         return true;
1230     }
1231     ts.equalOwnProperties = equalOwnProperties;
1232     function arrayToMap(array, makeKey, makeValue) {
1233         if (makeValue === void 0) { makeValue = identity; }
1234         var result = createMap();
1235         for (var _i = 0, array_6 = array; _i < array_6.length; _i++) {
1236             var value = array_6[_i];
1237             var key = makeKey(value);
1238             if (key !== undefined)
1239                 result.set(key, makeValue(value));
1240         }
1241         return result;
1242     }
1243     ts.arrayToMap = arrayToMap;
1244     function arrayToNumericMap(array, makeKey, makeValue) {
1245         if (makeValue === void 0) { makeValue = identity; }
1246         var result = [];
1247         for (var _i = 0, array_7 = array; _i < array_7.length; _i++) {
1248             var value = array_7[_i];
1249             result[makeKey(value)] = makeValue(value);
1250         }
1251         return result;
1252     }
1253     ts.arrayToNumericMap = arrayToNumericMap;
1254     function arrayToMultiMap(values, makeKey, makeValue) {
1255         if (makeValue === void 0) { makeValue = identity; }
1256         var result = createMultiMap();
1257         for (var _i = 0, values_1 = values; _i < values_1.length; _i++) {
1258             var value = values_1[_i];
1259             result.add(makeKey(value), makeValue(value));
1260         }
1261         return result;
1262     }
1263     ts.arrayToMultiMap = arrayToMultiMap;
1264     function group(values, getGroupId, resultSelector) {
1265         if (resultSelector === void 0) { resultSelector = identity; }
1266         return arrayFrom(arrayToMultiMap(values, getGroupId).values(), resultSelector);
1267     }
1268     ts.group = group;
1269     function clone(object) {
1270         var result = {};
1271         for (var id in object) {
1272             if (hasOwnProperty.call(object, id)) {
1273                 result[id] = object[id];
1274             }
1275         }
1276         return result;
1277     }
1278     ts.clone = clone;
1279     /**
1280      * Creates a new object by adding the own properties of `second`, then the own properties of `first`.
1281      *
1282      * NOTE: This means that if a property exists in both `first` and `second`, the property in `first` will be chosen.
1283      */
1284     function extend(first, second) {
1285         var result = {};
1286         for (var id in second) {
1287             if (hasOwnProperty.call(second, id)) {
1288                 result[id] = second[id];
1289             }
1290         }
1291         for (var id in first) {
1292             if (hasOwnProperty.call(first, id)) {
1293                 result[id] = first[id];
1294             }
1295         }
1296         return result;
1297     }
1298     ts.extend = extend;
1299     function copyProperties(first, second) {
1300         for (var id in second) {
1301             if (hasOwnProperty.call(second, id)) {
1302                 first[id] = second[id];
1303             }
1304         }
1305     }
1306     ts.copyProperties = copyProperties;
1307     function maybeBind(obj, fn) {
1308         return fn ? fn.bind(obj) : undefined;
1309     }
1310     ts.maybeBind = maybeBind;
1311     function mapMap(map, f) {
1312         var result = createMap();
1313         map.forEach(function (t, key) { return result.set.apply(result, (f(t, key))); });
1314         return result;
1315     }
1316     ts.mapMap = mapMap;
1317     function createMultiMap() {
1318         var map = createMap();
1319         map.add = multiMapAdd;
1320         map.remove = multiMapRemove;
1321         return map;
1322     }
1323     ts.createMultiMap = createMultiMap;
1324     function multiMapAdd(key, value) {
1325         var values = this.get(key);
1326         if (values) {
1327             values.push(value);
1328         }
1329         else {
1330             this.set(key, values = [value]);
1331         }
1332         return values;
1333     }
1334     function multiMapRemove(key, value) {
1335         var values = this.get(key);
1336         if (values) {
1337             unorderedRemoveItem(values, value);
1338             if (!values.length) {
1339                 this.delete(key);
1340             }
1341         }
1342     }
1343     function createUnderscoreEscapedMultiMap() {
1344         return createMultiMap();
1345     }
1346     ts.createUnderscoreEscapedMultiMap = createUnderscoreEscapedMultiMap;
1347     /**
1348      * Tests whether a value is an array.
1349      */
1350     function isArray(value) {
1351         return Array.isArray ? Array.isArray(value) : value instanceof Array;
1352     }
1353     ts.isArray = isArray;
1354     function toArray(value) {
1355         return isArray(value) ? value : [value];
1356     }
1357     ts.toArray = toArray;
1358     /**
1359      * Tests whether a value is string
1360      */
1361     function isString(text) {
1362         return typeof text === "string";
1363     }
1364     ts.isString = isString;
1365     function isNumber(x) {
1366         return typeof x === "number";
1367     }
1368     ts.isNumber = isNumber;
1369     function tryCast(value, test) {
1370         return value !== undefined && test(value) ? value : undefined;
1371     }
1372     ts.tryCast = tryCast;
1373     function cast(value, test) {
1374         if (value !== undefined && test(value))
1375             return value;
1376         return ts.Debug.fail("Invalid cast. The supplied value " + value + " did not pass the test '" + ts.Debug.getFunctionName(test) + "'.");
1377     }
1378     ts.cast = cast;
1379     /** Does nothing. */
1380     function noop(_) { }
1381     ts.noop = noop;
1382     /** Do nothing and return false */
1383     function returnFalse() { return false; }
1384     ts.returnFalse = returnFalse;
1385     /** Do nothing and return true */
1386     function returnTrue() { return true; }
1387     ts.returnTrue = returnTrue;
1388     /** Do nothing and return undefined */
1389     function returnUndefined() { return undefined; }
1390     ts.returnUndefined = returnUndefined;
1391     /** Returns its argument. */
1392     function identity(x) { return x; }
1393     ts.identity = identity;
1394     /** Returns lower case string */
1395     function toLowerCase(x) { return x.toLowerCase(); }
1396     ts.toLowerCase = toLowerCase;
1397     // We convert the file names to lower case as key for file name on case insensitive file system
1398     // While doing so we need to handle special characters (eg \u0130) to ensure that we dont convert
1399     // it to lower case, fileName with its lowercase form can exist along side it.
1400     // Handle special characters and make those case sensitive instead
1401     //
1402     // |-#--|-Unicode--|-Char code-|-Desc-------------------------------------------------------------------|
1403     // | 1. | i        | 105       | Ascii i                                                                |
1404     // | 2. | I        | 73        | Ascii I                                                                |
1405     // |-------- Special characters ------------------------------------------------------------------------|
1406     // | 3. | \u0130   | 304       | Uppper case I with dot above                                           |
1407     // | 4. | i,\u0307 | 105,775   | i, followed by 775: Lower case of (3rd item)                           |
1408     // | 5. | I,\u0307 | 73,775    | I, followed by 775: Upper case of (4th item), lower case is (4th item) |
1409     // | 6. | \u0131   | 305       | Lower case i without dot, upper case is I (2nd item)                   |
1410     // | 7. | \u00DF   | 223       | Lower case sharp s                                                     |
1411     //
1412     // Because item 3 is special where in its lowercase character has its own
1413     // upper case form we cant convert its case.
1414     // Rest special characters are either already in lower case format or
1415     // they have corresponding upper case character so they dont need special handling
1416     //
1417     // But to avoid having to do string building for most common cases, also ignore
1418     // a-z, 0-9, \u0131, \u00DF, \, /, ., : and space
1419     var fileNameLowerCaseRegExp = /[^\u0130\u0131\u00DFa-z0-9\\/:\-_\. ]+/g;
1420     /**
1421      * Case insensitive file systems have descripencies in how they handle some characters (eg. turkish Upper case I with dot on top - \u0130)
1422      * This function is used in places where we want to make file name as a key on these systems
1423      * 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
1424      * 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
1425      * Technically we would want this function to be platform sepcific as well but
1426      * 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
1427      * We could use upper case and we would still need to deal with the descripencies but
1428      * 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
1429      * 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
1430      */
1431     function toFileNameLowerCase(x) {
1432         return fileNameLowerCaseRegExp.test(x) ?
1433             x.replace(fileNameLowerCaseRegExp, toLowerCase) :
1434             x;
1435     }
1436     ts.toFileNameLowerCase = toFileNameLowerCase;
1437     /** Throws an error because a function is not implemented. */
1438     function notImplemented() {
1439         throw new Error("Not implemented");
1440     }
1441     ts.notImplemented = notImplemented;
1442     function memoize(callback) {
1443         var value;
1444         return function () {
1445             if (callback) {
1446                 value = callback();
1447                 callback = undefined;
1448             }
1449             return value;
1450         };
1451     }
1452     ts.memoize = memoize;
1453     function compose(a, b, c, d, e) {
1454         if (!!e) {
1455             var args_2 = [];
1456             for (var i = 0; i < arguments.length; i++) {
1457                 args_2[i] = arguments[i];
1458             }
1459             return function (t) { return reduceLeft(args_2, function (u, f) { return f(u); }, t); };
1460         }
1461         else if (d) {
1462             return function (t) { return d(c(b(a(t)))); };
1463         }
1464         else if (c) {
1465             return function (t) { return c(b(a(t))); };
1466         }
1467         else if (b) {
1468             return function (t) { return b(a(t)); };
1469         }
1470         else if (a) {
1471             return function (t) { return a(t); };
1472         }
1473         else {
1474             return function (t) { return t; };
1475         }
1476     }
1477     ts.compose = compose;
1478     var AssertionLevel;
1479     (function (AssertionLevel) {
1480         AssertionLevel[AssertionLevel["None"] = 0] = "None";
1481         AssertionLevel[AssertionLevel["Normal"] = 1] = "Normal";
1482         AssertionLevel[AssertionLevel["Aggressive"] = 2] = "Aggressive";
1483         AssertionLevel[AssertionLevel["VeryAggressive"] = 3] = "VeryAggressive";
1484     })(AssertionLevel = ts.AssertionLevel || (ts.AssertionLevel = {}));
1485     function equateValues(a, b) {
1486         return a === b;
1487     }
1488     ts.equateValues = equateValues;
1489     /**
1490      * Compare the equality of two strings using a case-sensitive ordinal comparison.
1491      *
1492      * Case-sensitive comparisons compare both strings one code-point at a time using the integer
1493      * value of each code-point after applying `toUpperCase` to each string. We always map both
1494      * strings to their upper-case form as some unicode characters do not properly round-trip to
1495      * lowercase (such as `ẞ` (German sharp capital s)).
1496      */
1497     function equateStringsCaseInsensitive(a, b) {
1498         return a === b
1499             || a !== undefined
1500                 && b !== undefined
1501                 && a.toUpperCase() === b.toUpperCase();
1502     }
1503     ts.equateStringsCaseInsensitive = equateStringsCaseInsensitive;
1504     /**
1505      * Compare the equality of two strings using a case-sensitive ordinal comparison.
1506      *
1507      * Case-sensitive comparisons compare both strings one code-point at a time using the
1508      * integer value of each code-point.
1509      */
1510     function equateStringsCaseSensitive(a, b) {
1511         return equateValues(a, b);
1512     }
1513     ts.equateStringsCaseSensitive = equateStringsCaseSensitive;
1514     function compareComparableValues(a, b) {
1515         return a === b ? 0 /* EqualTo */ :
1516             a === undefined ? -1 /* LessThan */ :
1517                 b === undefined ? 1 /* GreaterThan */ :
1518                     a < b ? -1 /* LessThan */ :
1519                         1 /* GreaterThan */;
1520     }
1521     /**
1522      * Compare two numeric values for their order relative to each other.
1523      * To compare strings, use any of the `compareStrings` functions.
1524      */
1525     function compareValues(a, b) {
1526         return compareComparableValues(a, b);
1527     }
1528     ts.compareValues = compareValues;
1529     /**
1530      * Compare two TextSpans, first by `start`, then by `length`.
1531      */
1532     function compareTextSpans(a, b) {
1533         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);
1534     }
1535     ts.compareTextSpans = compareTextSpans;
1536     function min(a, b, compare) {
1537         return compare(a, b) === -1 /* LessThan */ ? a : b;
1538     }
1539     ts.min = min;
1540     /**
1541      * Compare two strings using a case-insensitive ordinal comparison.
1542      *
1543      * Ordinal comparisons are based on the difference between the unicode code points of both
1544      * strings. Characters with multiple unicode representations are considered unequal. Ordinal
1545      * comparisons provide predictable ordering, but place "a" after "B".
1546      *
1547      * Case-insensitive comparisons compare both strings one code-point at a time using the integer
1548      * value of each code-point after applying `toUpperCase` to each string. We always map both
1549      * strings to their upper-case form as some unicode characters do not properly round-trip to
1550      * lowercase (such as `ẞ` (German sharp capital s)).
1551      */
1552     function compareStringsCaseInsensitive(a, b) {
1553         if (a === b)
1554             return 0 /* EqualTo */;
1555         if (a === undefined)
1556             return -1 /* LessThan */;
1557         if (b === undefined)
1558             return 1 /* GreaterThan */;
1559         a = a.toUpperCase();
1560         b = b.toUpperCase();
1561         return a < b ? -1 /* LessThan */ : a > b ? 1 /* GreaterThan */ : 0 /* EqualTo */;
1562     }
1563     ts.compareStringsCaseInsensitive = compareStringsCaseInsensitive;
1564     /**
1565      * Compare two strings using a case-sensitive ordinal comparison.
1566      *
1567      * Ordinal comparisons are based on the difference between the unicode code points of both
1568      * strings. Characters with multiple unicode representations are considered unequal. Ordinal
1569      * comparisons provide predictable ordering, but place "a" after "B".
1570      *
1571      * Case-sensitive comparisons compare both strings one code-point at a time using the integer
1572      * value of each code-point.
1573      */
1574     function compareStringsCaseSensitive(a, b) {
1575         return compareComparableValues(a, b);
1576     }
1577     ts.compareStringsCaseSensitive = compareStringsCaseSensitive;
1578     function getStringComparer(ignoreCase) {
1579         return ignoreCase ? compareStringsCaseInsensitive : compareStringsCaseSensitive;
1580     }
1581     ts.getStringComparer = getStringComparer;
1582     /**
1583      * Creates a string comparer for use with string collation in the UI.
1584      */
1585     var createUIStringComparer = (function () {
1586         var defaultComparer;
1587         var enUSComparer;
1588         var stringComparerFactory = getStringComparerFactory();
1589         return createStringComparer;
1590         function compareWithCallback(a, b, comparer) {
1591             if (a === b)
1592                 return 0 /* EqualTo */;
1593             if (a === undefined)
1594                 return -1 /* LessThan */;
1595             if (b === undefined)
1596                 return 1 /* GreaterThan */;
1597             var value = comparer(a, b);
1598             return value < 0 ? -1 /* LessThan */ : value > 0 ? 1 /* GreaterThan */ : 0 /* EqualTo */;
1599         }
1600         function createIntlCollatorStringComparer(locale) {
1601             // Intl.Collator.prototype.compare is bound to the collator. See NOTE in
1602             // http://www.ecma-international.org/ecma-402/2.0/#sec-Intl.Collator.prototype.compare
1603             var comparer = new Intl.Collator(locale, { usage: "sort", sensitivity: "variant" }).compare;
1604             return function (a, b) { return compareWithCallback(a, b, comparer); };
1605         }
1606         function createLocaleCompareStringComparer(locale) {
1607             // if the locale is not the default locale (`undefined`), use the fallback comparer.
1608             if (locale !== undefined)
1609                 return createFallbackStringComparer();
1610             return function (a, b) { return compareWithCallback(a, b, compareStrings); };
1611             function compareStrings(a, b) {
1612                 return a.localeCompare(b);
1613             }
1614         }
1615         function createFallbackStringComparer() {
1616             // An ordinal comparison puts "A" after "b", but for the UI we want "A" before "b".
1617             // We first sort case insensitively.  So "Aaa" will come before "baa".
1618             // Then we sort case sensitively, so "aaa" will come before "Aaa".
1619             //
1620             // For case insensitive comparisons we always map both strings to their
1621             // upper-case form as some unicode characters do not properly round-trip to
1622             // lowercase (such as `ẞ` (German sharp capital s)).
1623             return function (a, b) { return compareWithCallback(a, b, compareDictionaryOrder); };
1624             function compareDictionaryOrder(a, b) {
1625                 return compareStrings(a.toUpperCase(), b.toUpperCase()) || compareStrings(a, b);
1626             }
1627             function compareStrings(a, b) {
1628                 return a < b ? -1 /* LessThan */ : a > b ? 1 /* GreaterThan */ : 0 /* EqualTo */;
1629             }
1630         }
1631         function getStringComparerFactory() {
1632             // If the host supports Intl, we use it for comparisons using the default locale.
1633             if (typeof Intl === "object" && typeof Intl.Collator === "function") {
1634                 return createIntlCollatorStringComparer;
1635             }
1636             // If the host does not support Intl, we fall back to localeCompare.
1637             // localeCompare in Node v0.10 is just an ordinal comparison, so don't use it.
1638             if (typeof String.prototype.localeCompare === "function" &&
1639                 typeof String.prototype.toLocaleUpperCase === "function" &&
1640                 "a".localeCompare("B") < 0) {
1641                 return createLocaleCompareStringComparer;
1642             }
1643             // Otherwise, fall back to ordinal comparison:
1644             return createFallbackStringComparer;
1645         }
1646         function createStringComparer(locale) {
1647             // Hold onto common string comparers. This avoids constantly reallocating comparers during
1648             // tests.
1649             if (locale === undefined) {
1650                 return defaultComparer || (defaultComparer = stringComparerFactory(locale));
1651             }
1652             else if (locale === "en-US") {
1653                 return enUSComparer || (enUSComparer = stringComparerFactory(locale));
1654             }
1655             else {
1656                 return stringComparerFactory(locale);
1657             }
1658         }
1659     })();
1660     var uiComparerCaseSensitive;
1661     var uiLocale;
1662     function getUILocale() {
1663         return uiLocale;
1664     }
1665     ts.getUILocale = getUILocale;
1666     function setUILocale(value) {
1667         if (uiLocale !== value) {
1668             uiLocale = value;
1669             uiComparerCaseSensitive = undefined;
1670         }
1671     }
1672     ts.setUILocale = setUILocale;
1673     /**
1674      * Compare two strings in a using the case-sensitive sort behavior of the UI locale.
1675      *
1676      * Ordering is not predictable between different host locales, but is best for displaying
1677      * ordered data for UI presentation. Characters with multiple unicode representations may
1678      * be considered equal.
1679      *
1680      * Case-sensitive comparisons compare strings that differ in base characters, or
1681      * accents/diacritic marks, or case as unequal.
1682      */
1683     function compareStringsCaseSensitiveUI(a, b) {
1684         var comparer = uiComparerCaseSensitive || (uiComparerCaseSensitive = createUIStringComparer(uiLocale));
1685         return comparer(a, b);
1686     }
1687     ts.compareStringsCaseSensitiveUI = compareStringsCaseSensitiveUI;
1688     function compareProperties(a, b, key, comparer) {
1689         return a === b ? 0 /* EqualTo */ :
1690             a === undefined ? -1 /* LessThan */ :
1691                 b === undefined ? 1 /* GreaterThan */ :
1692                     comparer(a[key], b[key]);
1693     }
1694     ts.compareProperties = compareProperties;
1695     /** True is greater than false. */
1696     function compareBooleans(a, b) {
1697         return compareValues(a ? 1 : 0, b ? 1 : 0);
1698     }
1699     ts.compareBooleans = compareBooleans;
1700     /**
1701      * 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.
1702      * Names less than length 3 only check for case-insensitive equality, not Levenshtein distance.
1703      *
1704      * If there is a candidate that's the same except for case, return that.
1705      * If there is a candidate that's within one edit of the name, return that.
1706      * Otherwise, return the candidate with the smallest Levenshtein distance,
1707      *    except for candidates:
1708      *      * With no name
1709      *      * Whose length differs from the target name by more than 0.34 of the length of the name.
1710      *      * Whose levenshtein distance is more than 0.4 of the length of the name
1711      *        (0.4 allows 1 substitution/transposition for every 5 characters,
1712      *         and 1 insertion/deletion at 3 characters)
1713      */
1714     function getSpellingSuggestion(name, candidates, getName) {
1715         var maximumLengthDifference = Math.min(2, Math.floor(name.length * 0.34));
1716         var bestDistance = Math.floor(name.length * 0.4) + 1; // If the best result isn't better than this, don't bother.
1717         var bestCandidate;
1718         var justCheckExactMatches = false;
1719         var nameLowerCase = name.toLowerCase();
1720         for (var _i = 0, candidates_1 = candidates; _i < candidates_1.length; _i++) {
1721             var candidate = candidates_1[_i];
1722             var candidateName = getName(candidate);
1723             if (candidateName !== undefined && Math.abs(candidateName.length - nameLowerCase.length) <= maximumLengthDifference) {
1724                 var candidateNameLowerCase = candidateName.toLowerCase();
1725                 if (candidateNameLowerCase === nameLowerCase) {
1726                     if (candidateName === name) {
1727                         continue;
1728                     }
1729                     return candidate;
1730                 }
1731                 if (justCheckExactMatches) {
1732                     continue;
1733                 }
1734                 if (candidateName.length < 3) {
1735                     // Don't bother, user would have noticed a 2-character name having an extra character
1736                     continue;
1737                 }
1738                 // Only care about a result better than the best so far.
1739                 var distance = levenshteinWithMax(nameLowerCase, candidateNameLowerCase, bestDistance - 1);
1740                 if (distance === undefined) {
1741                     continue;
1742                 }
1743                 if (distance < 3) {
1744                     justCheckExactMatches = true;
1745                     bestCandidate = candidate;
1746                 }
1747                 else {
1748                     ts.Debug.assert(distance < bestDistance); // Else `levenshteinWithMax` should return undefined
1749                     bestDistance = distance;
1750                     bestCandidate = candidate;
1751                 }
1752             }
1753         }
1754         return bestCandidate;
1755     }
1756     ts.getSpellingSuggestion = getSpellingSuggestion;
1757     function levenshteinWithMax(s1, s2, max) {
1758         var previous = new Array(s2.length + 1);
1759         var current = new Array(s2.length + 1);
1760         /** Represents any value > max. We don't care about the particular value. */
1761         var big = max + 1;
1762         for (var i = 0; i <= s2.length; i++) {
1763             previous[i] = i;
1764         }
1765         for (var i = 1; i <= s1.length; i++) {
1766             var c1 = s1.charCodeAt(i - 1);
1767             var minJ = i > max ? i - max : 1;
1768             var maxJ = s2.length > max + i ? max + i : s2.length;
1769             current[0] = i;
1770             /** Smallest value of the matrix in the ith column. */
1771             var colMin = i;
1772             for (var j = 1; j < minJ; j++) {
1773                 current[j] = big;
1774             }
1775             for (var j = minJ; j <= maxJ; j++) {
1776                 var dist = c1 === s2.charCodeAt(j - 1)
1777                     ? previous[j - 1]
1778                     : Math.min(/*delete*/ previous[j] + 1, /*insert*/ current[j - 1] + 1, /*substitute*/ previous[j - 1] + 2);
1779                 current[j] = dist;
1780                 colMin = Math.min(colMin, dist);
1781             }
1782             for (var j = maxJ + 1; j <= s2.length; j++) {
1783                 current[j] = big;
1784             }
1785             if (colMin > max) {
1786                 // Give up -- everything in this column is > max and it can't get better in future columns.
1787                 return undefined;
1788             }
1789             var temp = previous;
1790             previous = current;
1791             current = temp;
1792         }
1793         var res = previous[s2.length];
1794         return res > max ? undefined : res;
1795     }
1796     function endsWith(str, suffix) {
1797         var expectedPos = str.length - suffix.length;
1798         return expectedPos >= 0 && str.indexOf(suffix, expectedPos) === expectedPos;
1799     }
1800     ts.endsWith = endsWith;
1801     function removeSuffix(str, suffix) {
1802         return endsWith(str, suffix) ? str.slice(0, str.length - suffix.length) : str;
1803     }
1804     ts.removeSuffix = removeSuffix;
1805     function tryRemoveSuffix(str, suffix) {
1806         return endsWith(str, suffix) ? str.slice(0, str.length - suffix.length) : undefined;
1807     }
1808     ts.tryRemoveSuffix = tryRemoveSuffix;
1809     function stringContains(str, substring) {
1810         return str.indexOf(substring) !== -1;
1811     }
1812     ts.stringContains = stringContains;
1813     /**
1814      * Takes a string like "jquery-min.4.2.3" and returns "jquery"
1815      */
1816     function removeMinAndVersionNumbers(fileName) {
1817         // Match a "." or "-" followed by a version number or 'min' at the end of the name
1818         var trailingMinOrVersion = /[.-]((min)|(\d+(\.\d+)*))$/;
1819         // The "min" or version may both be present, in either order, so try applying the above twice.
1820         return fileName.replace(trailingMinOrVersion, "").replace(trailingMinOrVersion, "");
1821     }
1822     ts.removeMinAndVersionNumbers = removeMinAndVersionNumbers;
1823     /** Remove an item from an array, moving everything to its right one space left. */
1824     function orderedRemoveItem(array, item) {
1825         for (var i = 0; i < array.length; i++) {
1826             if (array[i] === item) {
1827                 orderedRemoveItemAt(array, i);
1828                 return true;
1829             }
1830         }
1831         return false;
1832     }
1833     ts.orderedRemoveItem = orderedRemoveItem;
1834     /** Remove an item by index from an array, moving everything to its right one space left. */
1835     function orderedRemoveItemAt(array, index) {
1836         // This seems to be faster than either `array.splice(i, 1)` or `array.copyWithin(i, i+ 1)`.
1837         for (var i = index; i < array.length - 1; i++) {
1838             array[i] = array[i + 1];
1839         }
1840         array.pop();
1841     }
1842     ts.orderedRemoveItemAt = orderedRemoveItemAt;
1843     function unorderedRemoveItemAt(array, index) {
1844         // Fill in the "hole" left at `index`.
1845         array[index] = array[array.length - 1];
1846         array.pop();
1847     }
1848     ts.unorderedRemoveItemAt = unorderedRemoveItemAt;
1849     /** Remove the *first* occurrence of `item` from the array. */
1850     function unorderedRemoveItem(array, item) {
1851         return unorderedRemoveFirstItemWhere(array, function (element) { return element === item; });
1852     }
1853     ts.unorderedRemoveItem = unorderedRemoveItem;
1854     /** Remove the *first* element satisfying `predicate`. */
1855     function unorderedRemoveFirstItemWhere(array, predicate) {
1856         for (var i = 0; i < array.length; i++) {
1857             if (predicate(array[i])) {
1858                 unorderedRemoveItemAt(array, i);
1859                 return true;
1860             }
1861         }
1862         return false;
1863     }
1864     function createGetCanonicalFileName(useCaseSensitiveFileNames) {
1865         return useCaseSensitiveFileNames ? identity : toFileNameLowerCase;
1866     }
1867     ts.createGetCanonicalFileName = createGetCanonicalFileName;
1868     function patternText(_a) {
1869         var prefix = _a.prefix, suffix = _a.suffix;
1870         return prefix + "*" + suffix;
1871     }
1872     ts.patternText = patternText;
1873     /**
1874      * Given that candidate matches pattern, returns the text matching the '*'.
1875      * E.g.: matchedText(tryParsePattern("foo*baz"), "foobarbaz") === "bar"
1876      */
1877     function matchedText(pattern, candidate) {
1878         ts.Debug.assert(isPatternMatch(pattern, candidate));
1879         return candidate.substring(pattern.prefix.length, candidate.length - pattern.suffix.length);
1880     }
1881     ts.matchedText = matchedText;
1882     /** Return the object corresponding to the best pattern to match `candidate`. */
1883     function findBestPatternMatch(values, getPattern, candidate) {
1884         var matchedValue;
1885         // use length of prefix as betterness criteria
1886         var longestMatchPrefixLength = -1;
1887         for (var _i = 0, values_2 = values; _i < values_2.length; _i++) {
1888             var v = values_2[_i];
1889             var pattern = getPattern(v);
1890             if (isPatternMatch(pattern, candidate) && pattern.prefix.length > longestMatchPrefixLength) {
1891                 longestMatchPrefixLength = pattern.prefix.length;
1892                 matchedValue = v;
1893             }
1894         }
1895         return matchedValue;
1896     }
1897     ts.findBestPatternMatch = findBestPatternMatch;
1898     function startsWith(str, prefix) {
1899         return str.lastIndexOf(prefix, 0) === 0;
1900     }
1901     ts.startsWith = startsWith;
1902     function removePrefix(str, prefix) {
1903         return startsWith(str, prefix) ? str.substr(prefix.length) : str;
1904     }
1905     ts.removePrefix = removePrefix;
1906     function tryRemovePrefix(str, prefix, getCanonicalFileName) {
1907         if (getCanonicalFileName === void 0) { getCanonicalFileName = identity; }
1908         return startsWith(getCanonicalFileName(str), getCanonicalFileName(prefix)) ? str.substring(prefix.length) : undefined;
1909     }
1910     ts.tryRemovePrefix = tryRemovePrefix;
1911     function isPatternMatch(_a, candidate) {
1912         var prefix = _a.prefix, suffix = _a.suffix;
1913         return candidate.length >= prefix.length + suffix.length &&
1914             startsWith(candidate, prefix) &&
1915             endsWith(candidate, suffix);
1916     }
1917     function and(f, g) {
1918         return function (arg) { return f(arg) && g(arg); };
1919     }
1920     ts.and = and;
1921     function or() {
1922         var fs = [];
1923         for (var _i = 0; _i < arguments.length; _i++) {
1924             fs[_i] = arguments[_i];
1925         }
1926         return function () {
1927             var args = [];
1928             for (var _i = 0; _i < arguments.length; _i++) {
1929                 args[_i] = arguments[_i];
1930             }
1931             for (var _a = 0, fs_1 = fs; _a < fs_1.length; _a++) {
1932                 var f = fs_1[_a];
1933                 if (f.apply(void 0, args)) {
1934                     return true;
1935                 }
1936             }
1937             return false;
1938         };
1939     }
1940     ts.or = or;
1941     function not(fn) {
1942         return function () {
1943             var args = [];
1944             for (var _i = 0; _i < arguments.length; _i++) {
1945                 args[_i] = arguments[_i];
1946             }
1947             return !fn.apply(void 0, args);
1948         };
1949     }
1950     ts.not = not;
1951     function assertType(_) { }
1952     ts.assertType = assertType;
1953     function singleElementArray(t) {
1954         return t === undefined ? undefined : [t];
1955     }
1956     ts.singleElementArray = singleElementArray;
1957     function enumerateInsertsAndDeletes(newItems, oldItems, comparer, inserted, deleted, unchanged) {
1958         unchanged = unchanged || noop;
1959         var newIndex = 0;
1960         var oldIndex = 0;
1961         var newLen = newItems.length;
1962         var oldLen = oldItems.length;
1963         while (newIndex < newLen && oldIndex < oldLen) {
1964             var newItem = newItems[newIndex];
1965             var oldItem = oldItems[oldIndex];
1966             var compareResult = comparer(newItem, oldItem);
1967             if (compareResult === -1 /* LessThan */) {
1968                 inserted(newItem);
1969                 newIndex++;
1970             }
1971             else if (compareResult === 1 /* GreaterThan */) {
1972                 deleted(oldItem);
1973                 oldIndex++;
1974             }
1975             else {
1976                 unchanged(oldItem, newItem);
1977                 newIndex++;
1978                 oldIndex++;
1979             }
1980         }
1981         while (newIndex < newLen) {
1982             inserted(newItems[newIndex++]);
1983         }
1984         while (oldIndex < oldLen) {
1985             deleted(oldItems[oldIndex++]);
1986         }
1987     }
1988     ts.enumerateInsertsAndDeletes = enumerateInsertsAndDeletes;
1989     function fill(length, cb) {
1990         var result = Array(length);
1991         for (var i = 0; i < length; i++) {
1992             result[i] = cb(i);
1993         }
1994         return result;
1995     }
1996     ts.fill = fill;
1997     function cartesianProduct(arrays) {
1998         var result = [];
1999         cartesianProductWorker(arrays, result, /*outer*/ undefined, 0);
2000         return result;
2001     }
2002     ts.cartesianProduct = cartesianProduct;
2003     function cartesianProductWorker(arrays, result, outer, index) {
2004         for (var _i = 0, _a = arrays[index]; _i < _a.length; _i++) {
2005             var element = _a[_i];
2006             var inner = void 0;
2007             if (outer) {
2008                 inner = outer.slice();
2009                 inner.push(element);
2010             }
2011             else {
2012                 inner = [element];
2013             }
2014             if (index === arrays.length - 1) {
2015                 result.push(inner);
2016             }
2017             else {
2018                 cartesianProductWorker(arrays, result, inner, index + 1);
2019             }
2020         }
2021     }
2022     function padLeft(s, length) {
2023         while (s.length < length) {
2024             s = " " + s;
2025         }
2026         return s;
2027     }
2028     ts.padLeft = padLeft;
2029     function padRight(s, length) {
2030         while (s.length < length) {
2031             s = s + " ";
2032         }
2033         return s;
2034     }
2035     ts.padRight = padRight;
2036 })(ts || (ts = {}));
2037 /* @internal */
2038 var ts;
2039 (function (ts) {
2040     var Debug;
2041     (function (Debug) {
2042         var currentAssertionLevel = 0 /* None */;
2043         // eslint-disable-next-line prefer-const
2044         Debug.isDebugging = false;
2045         var assertionCache = {};
2046         function getAssertionLevel() {
2047             return currentAssertionLevel;
2048         }
2049         Debug.getAssertionLevel = getAssertionLevel;
2050         function setAssertionLevel(level) {
2051             var prevAssertionLevel = currentAssertionLevel;
2052             currentAssertionLevel = level;
2053             if (level > prevAssertionLevel) {
2054                 // restore assertion functions for the current assertion level (see `shouldAssertFunction`).
2055                 for (var _i = 0, _a = ts.getOwnKeys(assertionCache); _i < _a.length; _i++) {
2056                     var key = _a[_i];
2057                     var cachedFunc = assertionCache[key];
2058                     if (cachedFunc !== undefined && Debug[key] !== cachedFunc.assertion && level >= cachedFunc.level) {
2059                         Debug[key] = cachedFunc;
2060                         assertionCache[key] = undefined;
2061                     }
2062                 }
2063             }
2064         }
2065         Debug.setAssertionLevel = setAssertionLevel;
2066         function shouldAssert(level) {
2067             return currentAssertionLevel >= level;
2068         }
2069         Debug.shouldAssert = shouldAssert;
2070         /**
2071          * Tests whether an assertion function should be executed. If it shouldn't, it is cached and replaced with `ts.noop`.
2072          * Replaced assertion functions are restored when `Debug.setAssertionLevel` is set to a high enough level.
2073          * @param level The minimum assertion level required.
2074          * @param name The name of the current assertion function.
2075          */
2076         function shouldAssertFunction(level, name) {
2077             if (!shouldAssert(level)) {
2078                 assertionCache[name] = { level: level, assertion: Debug[name] };
2079                 Debug[name] = ts.noop;
2080                 return false;
2081             }
2082             return true;
2083         }
2084         function fail(message, stackCrawlMark) {
2085             debugger;
2086             var e = new Error(message ? "Debug Failure. " + message : "Debug Failure.");
2087             if (Error.captureStackTrace) {
2088                 Error.captureStackTrace(e, stackCrawlMark || fail);
2089             }
2090             throw e;
2091         }
2092         Debug.fail = fail;
2093         function failBadSyntaxKind(node, message, stackCrawlMark) {
2094             return fail((message || "Unexpected node.") + "\r\nNode " + formatSyntaxKind(node.kind) + " was unexpected.", stackCrawlMark || failBadSyntaxKind);
2095         }
2096         Debug.failBadSyntaxKind = failBadSyntaxKind;
2097         function assert(expression, message, verboseDebugInfo, stackCrawlMark) {
2098             if (!expression) {
2099                 message = message ? "False expression: " + message : "False expression.";
2100                 if (verboseDebugInfo) {
2101                     message += "\r\nVerbose Debug Information: " + (typeof verboseDebugInfo === "string" ? verboseDebugInfo : verboseDebugInfo());
2102                 }
2103                 fail(message, stackCrawlMark || assert);
2104             }
2105         }
2106         Debug.assert = assert;
2107         function assertEqual(a, b, msg, msg2, stackCrawlMark) {
2108             if (a !== b) {
2109                 var message = msg ? msg2 ? msg + " " + msg2 : msg : "";
2110                 fail("Expected " + a + " === " + b + ". " + message, stackCrawlMark || assertEqual);
2111             }
2112         }
2113         Debug.assertEqual = assertEqual;
2114         function assertLessThan(a, b, msg, stackCrawlMark) {
2115             if (a >= b) {
2116                 fail("Expected " + a + " < " + b + ". " + (msg || ""), stackCrawlMark || assertLessThan);
2117             }
2118         }
2119         Debug.assertLessThan = assertLessThan;
2120         function assertLessThanOrEqual(a, b, stackCrawlMark) {
2121             if (a > b) {
2122                 fail("Expected " + a + " <= " + b, stackCrawlMark || assertLessThanOrEqual);
2123             }
2124         }
2125         Debug.assertLessThanOrEqual = assertLessThanOrEqual;
2126         function assertGreaterThanOrEqual(a, b, stackCrawlMark) {
2127             if (a < b) {
2128                 fail("Expected " + a + " >= " + b, stackCrawlMark || assertGreaterThanOrEqual);
2129             }
2130         }
2131         Debug.assertGreaterThanOrEqual = assertGreaterThanOrEqual;
2132         function assertIsDefined(value, message, stackCrawlMark) {
2133             // eslint-disable-next-line no-null/no-null
2134             if (value === undefined || value === null) {
2135                 fail(message, stackCrawlMark || assertIsDefined);
2136             }
2137         }
2138         Debug.assertIsDefined = assertIsDefined;
2139         function checkDefined(value, message, stackCrawlMark) {
2140             assertIsDefined(value, message, stackCrawlMark || checkDefined);
2141             return value;
2142         }
2143         Debug.checkDefined = checkDefined;
2144         /**
2145          * @deprecated Use `checkDefined` to check whether a value is defined inline. Use `assertIsDefined` to check whether
2146          * a value is defined at the statement level.
2147          */
2148         Debug.assertDefined = checkDefined;
2149         function assertEachIsDefined(value, message, stackCrawlMark) {
2150             for (var _i = 0, value_1 = value; _i < value_1.length; _i++) {
2151                 var v = value_1[_i];
2152                 assertIsDefined(v, message, stackCrawlMark || assertEachIsDefined);
2153             }
2154         }
2155         Debug.assertEachIsDefined = assertEachIsDefined;
2156         function checkEachDefined(value, message, stackCrawlMark) {
2157             assertEachIsDefined(value, message, stackCrawlMark || checkEachDefined);
2158             return value;
2159         }
2160         Debug.checkEachDefined = checkEachDefined;
2161         /**
2162          * @deprecated Use `checkEachDefined` to check whether the elements of an array are defined inline. Use `assertEachIsDefined` to check whether
2163          * the elements of an array are defined at the statement level.
2164          */
2165         Debug.assertEachDefined = checkEachDefined;
2166         function assertNever(member, message, stackCrawlMark) {
2167             if (message === void 0) { message = "Illegal value:"; }
2168             var detail = typeof member === "object" && ts.hasProperty(member, "kind") && ts.hasProperty(member, "pos") && formatSyntaxKind ? "SyntaxKind: " + formatSyntaxKind(member.kind) : JSON.stringify(member);
2169             return fail(message + " " + detail, stackCrawlMark || assertNever);
2170         }
2171         Debug.assertNever = assertNever;
2172         function assertEachNode(nodes, test, message, stackCrawlMark) {
2173             if (shouldAssertFunction(1 /* Normal */, "assertEachNode")) {
2174                 assert(test === undefined || ts.every(nodes, test), message || "Unexpected node.", function () { return "Node array did not pass test '" + getFunctionName(test) + "'."; }, stackCrawlMark || assertEachNode);
2175             }
2176         }
2177         Debug.assertEachNode = assertEachNode;
2178         function assertNode(node, test, message, stackCrawlMark) {
2179             if (shouldAssertFunction(1 /* Normal */, "assertNode")) {
2180                 assert(node !== undefined && (test === undefined || test(node)), message || "Unexpected node.", function () { return "Node " + formatSyntaxKind(node.kind) + " did not pass test '" + getFunctionName(test) + "'."; }, stackCrawlMark || assertNode);
2181             }
2182         }
2183         Debug.assertNode = assertNode;
2184         function assertNotNode(node, test, message, stackCrawlMark) {
2185             if (shouldAssertFunction(1 /* Normal */, "assertNotNode")) {
2186                 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);
2187             }
2188         }
2189         Debug.assertNotNode = assertNotNode;
2190         function assertOptionalNode(node, test, message, stackCrawlMark) {
2191             if (shouldAssertFunction(1 /* Normal */, "assertOptionalNode")) {
2192                 assert(test === undefined || node === undefined || test(node), message || "Unexpected node.", function () { return "Node " + formatSyntaxKind(node.kind) + " did not pass test '" + getFunctionName(test) + "'."; }, stackCrawlMark || assertOptionalNode);
2193             }
2194         }
2195         Debug.assertOptionalNode = assertOptionalNode;
2196         function assertOptionalToken(node, kind, message, stackCrawlMark) {
2197             if (shouldAssertFunction(1 /* Normal */, "assertOptionalToken")) {
2198                 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);
2199             }
2200         }
2201         Debug.assertOptionalToken = assertOptionalToken;
2202         function assertMissingNode(node, message, stackCrawlMark) {
2203             if (shouldAssertFunction(1 /* Normal */, "assertMissingNode")) {
2204                 assert(node === undefined, message || "Unexpected node.", function () { return "Node " + formatSyntaxKind(node.kind) + " was unexpected'."; }, stackCrawlMark || assertMissingNode);
2205             }
2206         }
2207         Debug.assertMissingNode = assertMissingNode;
2208         function getFunctionName(func) {
2209             if (typeof func !== "function") {
2210                 return "";
2211             }
2212             else if (func.hasOwnProperty("name")) {
2213                 return func.name;
2214             }
2215             else {
2216                 var text = Function.prototype.toString.call(func);
2217                 var match = /^function\s+([\w\$]+)\s*\(/.exec(text);
2218                 return match ? match[1] : "";
2219             }
2220         }
2221         Debug.getFunctionName = getFunctionName;
2222         function formatSymbol(symbol) {
2223             return "{ name: " + ts.unescapeLeadingUnderscores(symbol.escapedName) + "; flags: " + formatSymbolFlags(symbol.flags) + "; declarations: " + ts.map(symbol.declarations, function (node) { return formatSyntaxKind(node.kind); }) + " }";
2224         }
2225         Debug.formatSymbol = formatSymbol;
2226         /**
2227          * Formats an enum value as a string for debugging and debug assertions.
2228          */
2229         function formatEnum(value, enumObject, isFlags) {
2230             if (value === void 0) { value = 0; }
2231             var members = getEnumMembers(enumObject);
2232             if (value === 0) {
2233                 return members.length > 0 && members[0][0] === 0 ? members[0][1] : "0";
2234             }
2235             if (isFlags) {
2236                 var result = "";
2237                 var remainingFlags = value;
2238                 for (var _i = 0, members_1 = members; _i < members_1.length; _i++) {
2239                     var _a = members_1[_i], enumValue = _a[0], enumName = _a[1];
2240                     if (enumValue > value) {
2241                         break;
2242                     }
2243                     if (enumValue !== 0 && enumValue & value) {
2244                         result = "" + result + (result ? "|" : "") + enumName;
2245                         remainingFlags &= ~enumValue;
2246                     }
2247                 }
2248                 if (remainingFlags === 0) {
2249                     return result;
2250                 }
2251             }
2252             else {
2253                 for (var _b = 0, members_2 = members; _b < members_2.length; _b++) {
2254                     var _c = members_2[_b], enumValue = _c[0], enumName = _c[1];
2255                     if (enumValue === value) {
2256                         return enumName;
2257                     }
2258                 }
2259             }
2260             return value.toString();
2261         }
2262         Debug.formatEnum = formatEnum;
2263         function getEnumMembers(enumObject) {
2264             var result = [];
2265             for (var name in enumObject) {
2266                 var value = enumObject[name];
2267                 if (typeof value === "number") {
2268                     result.push([value, name]);
2269                 }
2270             }
2271             return ts.stableSort(result, function (x, y) { return ts.compareValues(x[0], y[0]); });
2272         }
2273         function formatSyntaxKind(kind) {
2274             return formatEnum(kind, ts.SyntaxKind, /*isFlags*/ false);
2275         }
2276         Debug.formatSyntaxKind = formatSyntaxKind;
2277         function formatNodeFlags(flags) {
2278             return formatEnum(flags, ts.NodeFlags, /*isFlags*/ true);
2279         }
2280         Debug.formatNodeFlags = formatNodeFlags;
2281         function formatModifierFlags(flags) {
2282             return formatEnum(flags, ts.ModifierFlags, /*isFlags*/ true);
2283         }
2284         Debug.formatModifierFlags = formatModifierFlags;
2285         function formatTransformFlags(flags) {
2286             return formatEnum(flags, ts.TransformFlags, /*isFlags*/ true);
2287         }
2288         Debug.formatTransformFlags = formatTransformFlags;
2289         function formatEmitFlags(flags) {
2290             return formatEnum(flags, ts.EmitFlags, /*isFlags*/ true);
2291         }
2292         Debug.formatEmitFlags = formatEmitFlags;
2293         function formatSymbolFlags(flags) {
2294             return formatEnum(flags, ts.SymbolFlags, /*isFlags*/ true);
2295         }
2296         Debug.formatSymbolFlags = formatSymbolFlags;
2297         function formatTypeFlags(flags) {
2298             return formatEnum(flags, ts.TypeFlags, /*isFlags*/ true);
2299         }
2300         Debug.formatTypeFlags = formatTypeFlags;
2301         function formatObjectFlags(flags) {
2302             return formatEnum(flags, ts.ObjectFlags, /*isFlags*/ true);
2303         }
2304         Debug.formatObjectFlags = formatObjectFlags;
2305         var isDebugInfoEnabled = false;
2306         var extendedDebugModule;
2307         function extendedDebug() {
2308             enableDebugInfo();
2309             if (!extendedDebugModule) {
2310                 throw new Error("Debugging helpers could not be loaded.");
2311             }
2312             return extendedDebugModule;
2313         }
2314         function printControlFlowGraph(flowNode) {
2315             return console.log(formatControlFlowGraph(flowNode));
2316         }
2317         Debug.printControlFlowGraph = printControlFlowGraph;
2318         function formatControlFlowGraph(flowNode) {
2319             return extendedDebug().formatControlFlowGraph(flowNode);
2320         }
2321         Debug.formatControlFlowGraph = formatControlFlowGraph;
2322         function attachFlowNodeDebugInfo(flowNode) {
2323             if (isDebugInfoEnabled) {
2324                 if (!("__debugFlowFlags" in flowNode)) { // eslint-disable-line no-in-operator
2325                     Object.defineProperties(flowNode, {
2326                         __debugFlowFlags: { get: function () { return formatEnum(this.flags, ts.FlowFlags, /*isFlags*/ true); } },
2327                         __debugToString: { value: function () { return formatControlFlowGraph(this); } }
2328                     });
2329                 }
2330             }
2331         }
2332         Debug.attachFlowNodeDebugInfo = attachFlowNodeDebugInfo;
2333         /**
2334          * Injects debug information into frequently used types.
2335          */
2336         function enableDebugInfo() {
2337             if (isDebugInfoEnabled)
2338                 return;
2339             // Add additional properties in debug mode to assist with debugging.
2340             Object.defineProperties(ts.objectAllocator.getSymbolConstructor().prototype, {
2341                 __debugFlags: { get: function () { return formatSymbolFlags(this.flags); } }
2342             });
2343             Object.defineProperties(ts.objectAllocator.getTypeConstructor().prototype, {
2344                 __debugFlags: { get: function () { return formatTypeFlags(this.flags); } },
2345                 __debugObjectFlags: { get: function () { return this.flags & 524288 /* Object */ ? formatObjectFlags(this.objectFlags) : ""; } },
2346                 __debugTypeToString: { value: function () { return this.checker.typeToString(this); } },
2347             });
2348             var nodeConstructors = [
2349                 ts.objectAllocator.getNodeConstructor(),
2350                 ts.objectAllocator.getIdentifierConstructor(),
2351                 ts.objectAllocator.getTokenConstructor(),
2352                 ts.objectAllocator.getSourceFileConstructor()
2353             ];
2354             for (var _i = 0, nodeConstructors_1 = nodeConstructors; _i < nodeConstructors_1.length; _i++) {
2355                 var ctor = nodeConstructors_1[_i];
2356                 if (!ctor.prototype.hasOwnProperty("__debugKind")) {
2357                     Object.defineProperties(ctor.prototype, {
2358                         __debugKind: { get: function () { return formatSyntaxKind(this.kind); } },
2359                         __debugNodeFlags: { get: function () { return formatNodeFlags(this.flags); } },
2360                         __debugModifierFlags: { get: function () { return formatModifierFlags(ts.getModifierFlagsNoCache(this)); } },
2361                         __debugTransformFlags: { get: function () { return formatTransformFlags(this.transformFlags); } },
2362                         __debugIsParseTreeNode: { get: function () { return ts.isParseTreeNode(this); } },
2363                         __debugEmitFlags: { get: function () { return formatEmitFlags(ts.getEmitFlags(this)); } },
2364                         __debugGetText: {
2365                             value: function (includeTrivia) {
2366                                 if (ts.nodeIsSynthesized(this))
2367                                     return "";
2368                                 var parseNode = ts.getParseTreeNode(this);
2369                                 var sourceFile = parseNode && ts.getSourceFileOfNode(parseNode);
2370                                 return sourceFile ? ts.getSourceTextOfNodeFromSourceFile(sourceFile, parseNode, includeTrivia) : "";
2371                             }
2372                         }
2373                     });
2374                 }
2375             }
2376             // attempt to load extended debugging information
2377             try {
2378                 if (ts.sys && ts.sys.require) {
2379                     var basePath = ts.getDirectoryPath(ts.resolvePath(ts.sys.getExecutingFilePath()));
2380                     var result = ts.sys.require(basePath, "./compiler-debug");
2381                     if (!result.error) {
2382                         result.module.init(ts);
2383                         extendedDebugModule = result.module;
2384                     }
2385                 }
2386             }
2387             catch (_a) {
2388                 // do nothing
2389             }
2390             isDebugInfoEnabled = true;
2391         }
2392         Debug.enableDebugInfo = enableDebugInfo;
2393     })(Debug = ts.Debug || (ts.Debug = {}));
2394 })(ts || (ts = {}));
2395 /*@internal*/
2396 var ts;
2397 (function (ts) {
2398     /** Gets a timestamp with (at least) ms resolution */
2399     ts.timestamp = typeof performance !== "undefined" && performance.now ? function () { return performance.now(); } : Date.now ? Date.now : function () { return +(new Date()); };
2400 })(ts || (ts = {}));
2401 /*@internal*/
2402 /** Performance measurements for the compiler. */
2403 var ts;
2404 (function (ts) {
2405     var performance;
2406     (function (performance) {
2407         // NOTE: cannot use ts.noop as core.ts loads after this
2408         var profilerEvent = typeof onProfilerEvent === "function" && onProfilerEvent.profiler === true ? onProfilerEvent : function () { };
2409         var enabled = false;
2410         var profilerStart = 0;
2411         var counts;
2412         var marks;
2413         var measures;
2414         function createTimerIf(condition, measureName, startMarkName, endMarkName) {
2415             return condition ? createTimer(measureName, startMarkName, endMarkName) : performance.nullTimer;
2416         }
2417         performance.createTimerIf = createTimerIf;
2418         function createTimer(measureName, startMarkName, endMarkName) {
2419             var enterCount = 0;
2420             return {
2421                 enter: enter,
2422                 exit: exit
2423             };
2424             function enter() {
2425                 if (++enterCount === 1) {
2426                     mark(startMarkName);
2427                 }
2428             }
2429             function exit() {
2430                 if (--enterCount === 0) {
2431                     mark(endMarkName);
2432                     measure(measureName, startMarkName, endMarkName);
2433                 }
2434                 else if (enterCount < 0) {
2435                     ts.Debug.fail("enter/exit count does not match.");
2436                 }
2437             }
2438         }
2439         performance.createTimer = createTimer;
2440         performance.nullTimer = { enter: ts.noop, exit: ts.noop };
2441         /**
2442          * Marks a performance event.
2443          *
2444          * @param markName The name of the mark.
2445          */
2446         function mark(markName) {
2447             if (enabled) {
2448                 marks.set(markName, ts.timestamp());
2449                 counts.set(markName, (counts.get(markName) || 0) + 1);
2450                 profilerEvent(markName);
2451             }
2452         }
2453         performance.mark = mark;
2454         /**
2455          * Adds a performance measurement with the specified name.
2456          *
2457          * @param measureName The name of the performance measurement.
2458          * @param startMarkName The name of the starting mark. If not supplied, the point at which the
2459          *      profiler was enabled is used.
2460          * @param endMarkName The name of the ending mark. If not supplied, the current timestamp is
2461          *      used.
2462          */
2463         function measure(measureName, startMarkName, endMarkName) {
2464             if (enabled) {
2465                 var end = endMarkName && marks.get(endMarkName) || ts.timestamp();
2466                 var start = startMarkName && marks.get(startMarkName) || profilerStart;
2467                 measures.set(measureName, (measures.get(measureName) || 0) + (end - start));
2468             }
2469         }
2470         performance.measure = measure;
2471         /**
2472          * Gets the number of times a marker was encountered.
2473          *
2474          * @param markName The name of the mark.
2475          */
2476         function getCount(markName) {
2477             return counts && counts.get(markName) || 0;
2478         }
2479         performance.getCount = getCount;
2480         /**
2481          * Gets the total duration of all measurements with the supplied name.
2482          *
2483          * @param measureName The name of the measure whose durations should be accumulated.
2484          */
2485         function getDuration(measureName) {
2486             return measures && measures.get(measureName) || 0;
2487         }
2488         performance.getDuration = getDuration;
2489         /**
2490          * Iterate over each measure, performing some action
2491          *
2492          * @param cb The action to perform for each measure
2493          */
2494         function forEachMeasure(cb) {
2495             measures.forEach(function (measure, key) {
2496                 cb(key, measure);
2497             });
2498         }
2499         performance.forEachMeasure = forEachMeasure;
2500         /** Enables (and resets) performance measurements for the compiler. */
2501         function enable() {
2502             counts = ts.createMap();
2503             marks = ts.createMap();
2504             measures = ts.createMap();
2505             enabled = true;
2506             profilerStart = ts.timestamp();
2507         }
2508         performance.enable = enable;
2509         /** Disables performance measurements for the compiler. */
2510         function disable() {
2511             enabled = false;
2512         }
2513         performance.disable = disable;
2514     })(performance = ts.performance || (ts.performance = {}));
2515 })(ts || (ts = {}));
2516 /* @internal */
2517 var ts;
2518 (function (ts) {
2519     var _a;
2520     var nullLogger = {
2521         logEvent: ts.noop,
2522         logErrEvent: ts.noop,
2523         logPerfEvent: ts.noop,
2524         logInfoEvent: ts.noop,
2525         logStartCommand: ts.noop,
2526         logStopCommand: ts.noop,
2527         logStartUpdateProgram: ts.noop,
2528         logStopUpdateProgram: ts.noop,
2529         logStartUpdateGraph: ts.noop,
2530         logStopUpdateGraph: ts.noop,
2531         logStartResolveModule: ts.noop,
2532         logStopResolveModule: ts.noop,
2533         logStartParseSourceFile: ts.noop,
2534         logStopParseSourceFile: ts.noop,
2535         logStartReadFile: ts.noop,
2536         logStopReadFile: ts.noop,
2537         logStartBindFile: ts.noop,
2538         logStopBindFile: ts.noop,
2539         logStartScheduledOperation: ts.noop,
2540         logStopScheduledOperation: ts.noop,
2541     };
2542     // Load optional module to enable Event Tracing for Windows
2543     // See https://github.com/microsoft/typescript-etw for more information
2544     var etwModule;
2545     try {
2546         var etwModulePath = (_a = process.env.TS_ETW_MODULE_PATH) !== null && _a !== void 0 ? _a : "./node_modules/@microsoft/typescript-etw";
2547         // require() will throw an exception if the module is not found
2548         // It may also return undefined if not installed properly
2549         etwModule = require(etwModulePath);
2550     }
2551     catch (e) {
2552         etwModule = undefined;
2553     }
2554     /** Performance logger that will generate ETW events if possible - check for `logEvent` member, as `etwModule` will be `{}` when browserified */
2555     ts.perfLogger = etwModule && etwModule.logEvent ? etwModule : nullLogger;
2556 })(ts || (ts = {}));
2557 /* @internal */
2558 var ts;
2559 (function (ts) {
2560     // https://semver.org/#spec-item-2
2561     // > A normal version number MUST take the form X.Y.Z where X, Y, and Z are non-negative
2562     // > integers, and MUST NOT contain leading zeroes. X is the major version, Y is the minor
2563     // > version, and Z is the patch version. Each element MUST increase numerically.
2564     //
2565     // NOTE: We differ here in that we allow X and X.Y, with missing parts having the default
2566     // value of `0`.
2567     var versionRegExp = /^(0|[1-9]\d*)(?:\.(0|[1-9]\d*)(?:\.(0|[1-9]\d*)(?:\-([a-z0-9-.]+))?(?:\+([a-z0-9-.]+))?)?)?$/i;
2568     // https://semver.org/#spec-item-9
2569     // > A pre-release version MAY be denoted by appending a hyphen and a series of dot separated
2570     // > identifiers immediately following the patch version. Identifiers MUST comprise only ASCII
2571     // > alphanumerics and hyphen [0-9A-Za-z-]. Identifiers MUST NOT be empty. Numeric identifiers
2572     // > MUST NOT include leading zeroes.
2573     var prereleaseRegExp = /^(?:0|[1-9]\d*|[a-z-][a-z0-9-]*)(?:\.(?:0|[1-9]\d*|[a-z-][a-z0-9-]*))*$/i;
2574     // https://semver.org/#spec-item-10
2575     // > Build metadata MAY be denoted by appending a plus sign and a series of dot separated
2576     // > identifiers immediately following the patch or pre-release version. Identifiers MUST
2577     // > comprise only ASCII alphanumerics and hyphen [0-9A-Za-z-]. Identifiers MUST NOT be empty.
2578     var buildRegExp = /^[a-z0-9-]+(?:\.[a-z0-9-]+)*$/i;
2579     // https://semver.org/#spec-item-9
2580     // > Numeric identifiers MUST NOT include leading zeroes.
2581     var numericIdentifierRegExp = /^(0|[1-9]\d*)$/;
2582     /**
2583      * Describes a precise semantic version number, https://semver.org
2584      */
2585     var Version = /** @class */ (function () {
2586         function Version(major, minor, patch, prerelease, build) {
2587             if (minor === void 0) { minor = 0; }
2588             if (patch === void 0) { patch = 0; }
2589             if (prerelease === void 0) { prerelease = ""; }
2590             if (build === void 0) { build = ""; }
2591             if (typeof major === "string") {
2592                 var result = ts.Debug.checkDefined(tryParseComponents(major), "Invalid version");
2593                 (major = result.major, minor = result.minor, patch = result.patch, prerelease = result.prerelease, build = result.build);
2594             }
2595             ts.Debug.assert(major >= 0, "Invalid argument: major");
2596             ts.Debug.assert(minor >= 0, "Invalid argument: minor");
2597             ts.Debug.assert(patch >= 0, "Invalid argument: patch");
2598             ts.Debug.assert(!prerelease || prereleaseRegExp.test(prerelease), "Invalid argument: prerelease");
2599             ts.Debug.assert(!build || buildRegExp.test(build), "Invalid argument: build");
2600             this.major = major;
2601             this.minor = minor;
2602             this.patch = patch;
2603             this.prerelease = prerelease ? prerelease.split(".") : ts.emptyArray;
2604             this.build = build ? build.split(".") : ts.emptyArray;
2605         }
2606         Version.tryParse = function (text) {
2607             var result = tryParseComponents(text);
2608             if (!result)
2609                 return undefined;
2610             var major = result.major, minor = result.minor, patch = result.patch, prerelease = result.prerelease, build = result.build;
2611             return new Version(major, minor, patch, prerelease, build);
2612         };
2613         Version.prototype.compareTo = function (other) {
2614             // https://semver.org/#spec-item-11
2615             // > Precedence is determined by the first difference when comparing each of these
2616             // > identifiers from left to right as follows: Major, minor, and patch versions are
2617             // > always compared numerically.
2618             //
2619             // https://semver.org/#spec-item-11
2620             // > Precedence for two pre-release versions with the same major, minor, and patch version
2621             // > MUST be determined by comparing each dot separated identifier from left to right until
2622             // > a difference is found [...]
2623             //
2624             // https://semver.org/#spec-item-11
2625             // > Build metadata does not figure into precedence
2626             if (this === other)
2627                 return 0 /* EqualTo */;
2628             if (other === undefined)
2629                 return 1 /* GreaterThan */;
2630             return ts.compareValues(this.major, other.major)
2631                 || ts.compareValues(this.minor, other.minor)
2632                 || ts.compareValues(this.patch, other.patch)
2633                 || comparePrerelaseIdentifiers(this.prerelease, other.prerelease);
2634         };
2635         Version.prototype.increment = function (field) {
2636             switch (field) {
2637                 case "major": return new Version(this.major + 1, 0, 0);
2638                 case "minor": return new Version(this.major, this.minor + 1, 0);
2639                 case "patch": return new Version(this.major, this.minor, this.patch + 1);
2640                 default: return ts.Debug.assertNever(field);
2641             }
2642         };
2643         Version.prototype.toString = function () {
2644             var result = this.major + "." + this.minor + "." + this.patch;
2645             if (ts.some(this.prerelease))
2646                 result += "-" + this.prerelease.join(".");
2647             if (ts.some(this.build))
2648                 result += "+" + this.build.join(".");
2649             return result;
2650         };
2651         Version.zero = new Version(0, 0, 0);
2652         return Version;
2653     }());
2654     ts.Version = Version;
2655     function tryParseComponents(text) {
2656         var match = versionRegExp.exec(text);
2657         if (!match)
2658             return undefined;
2659         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;
2660         if (prerelease && !prereleaseRegExp.test(prerelease))
2661             return undefined;
2662         if (build && !buildRegExp.test(build))
2663             return undefined;
2664         return {
2665             major: parseInt(major, 10),
2666             minor: parseInt(minor, 10),
2667             patch: parseInt(patch, 10),
2668             prerelease: prerelease,
2669             build: build
2670         };
2671     }
2672     function comparePrerelaseIdentifiers(left, right) {
2673         // https://semver.org/#spec-item-11
2674         // > When major, minor, and patch are equal, a pre-release version has lower precedence
2675         // > than a normal version.
2676         if (left === right)
2677             return 0 /* EqualTo */;
2678         if (left.length === 0)
2679             return right.length === 0 ? 0 /* EqualTo */ : 1 /* GreaterThan */;
2680         if (right.length === 0)
2681             return -1 /* LessThan */;
2682         // https://semver.org/#spec-item-11
2683         // > Precedence for two pre-release versions with the same major, minor, and patch version
2684         // > MUST be determined by comparing each dot separated identifier from left to right until
2685         // > a difference is found [...]
2686         var length = Math.min(left.length, right.length);
2687         for (var i = 0; i < length; i++) {
2688             var leftIdentifier = left[i];
2689             var rightIdentifier = right[i];
2690             if (leftIdentifier === rightIdentifier)
2691                 continue;
2692             var leftIsNumeric = numericIdentifierRegExp.test(leftIdentifier);
2693             var rightIsNumeric = numericIdentifierRegExp.test(rightIdentifier);
2694             if (leftIsNumeric || rightIsNumeric) {
2695                 // https://semver.org/#spec-item-11
2696                 // > Numeric identifiers always have lower precedence than non-numeric identifiers.
2697                 if (leftIsNumeric !== rightIsNumeric)
2698                     return leftIsNumeric ? -1 /* LessThan */ : 1 /* GreaterThan */;
2699                 // https://semver.org/#spec-item-11
2700                 // > identifiers consisting of only digits are compared numerically
2701                 var result = ts.compareValues(+leftIdentifier, +rightIdentifier);
2702                 if (result)
2703                     return result;
2704             }
2705             else {
2706                 // https://semver.org/#spec-item-11
2707                 // > identifiers with letters or hyphens are compared lexically in ASCII sort order.
2708                 var result = ts.compareStringsCaseSensitive(leftIdentifier, rightIdentifier);
2709                 if (result)
2710                     return result;
2711             }
2712         }
2713         // https://semver.org/#spec-item-11
2714         // > A larger set of pre-release fields has a higher precedence than a smaller set, if all
2715         // > of the preceding identifiers are equal.
2716         return ts.compareValues(left.length, right.length);
2717     }
2718     /**
2719      * Describes a semantic version range, per https://github.com/npm/node-semver#ranges
2720      */
2721     var VersionRange = /** @class */ (function () {
2722         function VersionRange(spec) {
2723             this._alternatives = spec ? ts.Debug.checkDefined(parseRange(spec), "Invalid range spec.") : ts.emptyArray;
2724         }
2725         VersionRange.tryParse = function (text) {
2726             var sets = parseRange(text);
2727             if (sets) {
2728                 var range = new VersionRange("");
2729                 range._alternatives = sets;
2730                 return range;
2731             }
2732             return undefined;
2733         };
2734         VersionRange.prototype.test = function (version) {
2735             if (typeof version === "string")
2736                 version = new Version(version);
2737             return testDisjunction(version, this._alternatives);
2738         };
2739         VersionRange.prototype.toString = function () {
2740             return formatDisjunction(this._alternatives);
2741         };
2742         return VersionRange;
2743     }());
2744     ts.VersionRange = VersionRange;
2745     // https://github.com/npm/node-semver#range-grammar
2746     //
2747     // range-set    ::= range ( logical-or range ) *
2748     // range        ::= hyphen | simple ( ' ' simple ) * | ''
2749     // logical-or   ::= ( ' ' ) * '||' ( ' ' ) *
2750     var logicalOrRegExp = /\s*\|\|\s*/g;
2751     var whitespaceRegExp = /\s+/g;
2752     // https://github.com/npm/node-semver#range-grammar
2753     //
2754     // partial      ::= xr ( '.' xr ( '.' xr qualifier ? )? )?
2755     // xr           ::= 'x' | 'X' | '*' | nr
2756     // nr           ::= '0' | ['1'-'9'] ( ['0'-'9'] ) *
2757     // qualifier    ::= ( '-' pre )? ( '+' build )?
2758     // pre          ::= parts
2759     // build        ::= parts
2760     // parts        ::= part ( '.' part ) *
2761     // part         ::= nr | [-0-9A-Za-z]+
2762     var partialRegExp = /^([xX*0]|[1-9]\d*)(?:\.([xX*0]|[1-9]\d*)(?:\.([xX*0]|[1-9]\d*)(?:-([a-z0-9-.]+))?(?:\+([a-z0-9-.]+))?)?)?$/i;
2763     // https://github.com/npm/node-semver#range-grammar
2764     //
2765     // hyphen       ::= partial ' - ' partial
2766     var hyphenRegExp = /^\s*([a-z0-9-+.*]+)\s+-\s+([a-z0-9-+.*]+)\s*$/i;
2767     // https://github.com/npm/node-semver#range-grammar
2768     //
2769     // simple       ::= primitive | partial | tilde | caret
2770     // primitive    ::= ( '<' | '>' | '>=' | '<=' | '=' ) partial
2771     // tilde        ::= '~' partial
2772     // caret        ::= '^' partial
2773     var rangeRegExp = /^\s*(~|\^|<|<=|>|>=|=)?\s*([a-z0-9-+.*]+)$/i;
2774     function parseRange(text) {
2775         var alternatives = [];
2776         for (var _i = 0, _a = text.trim().split(logicalOrRegExp); _i < _a.length; _i++) {
2777             var range = _a[_i];
2778             if (!range)
2779                 continue;
2780             var comparators = [];
2781             var match = hyphenRegExp.exec(range);
2782             if (match) {
2783                 if (!parseHyphen(match[1], match[2], comparators))
2784                     return undefined;
2785             }
2786             else {
2787                 for (var _b = 0, _c = range.split(whitespaceRegExp); _b < _c.length; _b++) {
2788                     var simple = _c[_b];
2789                     var match_1 = rangeRegExp.exec(simple);
2790                     if (!match_1 || !parseComparator(match_1[1], match_1[2], comparators))
2791                         return undefined;
2792                 }
2793             }
2794             alternatives.push(comparators);
2795         }
2796         return alternatives;
2797     }
2798     function parsePartial(text) {
2799         var match = partialRegExp.exec(text);
2800         if (!match)
2801             return undefined;
2802         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];
2803         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);
2804         return { version: version, major: major, minor: minor, patch: patch };
2805     }
2806     function parseHyphen(left, right, comparators) {
2807         var leftResult = parsePartial(left);
2808         if (!leftResult)
2809             return false;
2810         var rightResult = parsePartial(right);
2811         if (!rightResult)
2812             return false;
2813         if (!isWildcard(leftResult.major)) {
2814             comparators.push(createComparator(">=", leftResult.version));
2815         }
2816         if (!isWildcard(rightResult.major)) {
2817             comparators.push(isWildcard(rightResult.minor) ? createComparator("<", rightResult.version.increment("major")) :
2818                 isWildcard(rightResult.patch) ? createComparator("<", rightResult.version.increment("minor")) :
2819                     createComparator("<=", rightResult.version));
2820         }
2821         return true;
2822     }
2823     function parseComparator(operator, text, comparators) {
2824         var result = parsePartial(text);
2825         if (!result)
2826             return false;
2827         var version = result.version, major = result.major, minor = result.minor, patch = result.patch;
2828         if (!isWildcard(major)) {
2829             switch (operator) {
2830                 case "~":
2831                     comparators.push(createComparator(">=", version));
2832                     comparators.push(createComparator("<", version.increment(isWildcard(minor) ? "major" :
2833                         "minor")));
2834                     break;
2835                 case "^":
2836                     comparators.push(createComparator(">=", version));
2837                     comparators.push(createComparator("<", version.increment(version.major > 0 || isWildcard(minor) ? "major" :
2838                         version.minor > 0 || isWildcard(patch) ? "minor" :
2839                             "patch")));
2840                     break;
2841                 case "<":
2842                 case ">=":
2843                     comparators.push(createComparator(operator, version));
2844                     break;
2845                 case "<=":
2846                 case ">":
2847                     comparators.push(isWildcard(minor) ? createComparator(operator === "<=" ? "<" : ">=", version.increment("major")) :
2848                         isWildcard(patch) ? createComparator(operator === "<=" ? "<" : ">=", version.increment("minor")) :
2849                             createComparator(operator, version));
2850                     break;
2851                 case "=":
2852                 case undefined:
2853                     if (isWildcard(minor) || isWildcard(patch)) {
2854                         comparators.push(createComparator(">=", version));
2855                         comparators.push(createComparator("<", version.increment(isWildcard(minor) ? "major" : "minor")));
2856                     }
2857                     else {
2858                         comparators.push(createComparator("=", version));
2859                     }
2860                     break;
2861                 default:
2862                     // unrecognized
2863                     return false;
2864             }
2865         }
2866         else if (operator === "<" || operator === ">") {
2867             comparators.push(createComparator("<", Version.zero));
2868         }
2869         return true;
2870     }
2871     function isWildcard(part) {
2872         return part === "*" || part === "x" || part === "X";
2873     }
2874     function createComparator(operator, operand) {
2875         return { operator: operator, operand: operand };
2876     }
2877     function testDisjunction(version, alternatives) {
2878         // an empty disjunction is treated as "*" (all versions)
2879         if (alternatives.length === 0)
2880             return true;
2881         for (var _i = 0, alternatives_1 = alternatives; _i < alternatives_1.length; _i++) {
2882             var alternative = alternatives_1[_i];
2883             if (testAlternative(version, alternative))
2884                 return true;
2885         }
2886         return false;
2887     }
2888     function testAlternative(version, comparators) {
2889         for (var _i = 0, comparators_1 = comparators; _i < comparators_1.length; _i++) {
2890             var comparator = comparators_1[_i];
2891             if (!testComparator(version, comparator.operator, comparator.operand))
2892                 return false;
2893         }
2894         return true;
2895     }
2896     function testComparator(version, operator, operand) {
2897         var cmp = version.compareTo(operand);
2898         switch (operator) {
2899             case "<": return cmp < 0;
2900             case "<=": return cmp <= 0;
2901             case ">": return cmp > 0;
2902             case ">=": return cmp >= 0;
2903             case "=": return cmp === 0;
2904             default: return ts.Debug.assertNever(operator);
2905         }
2906     }
2907     function formatDisjunction(alternatives) {
2908         return ts.map(alternatives, formatAlternative).join(" || ") || "*";
2909     }
2910     function formatAlternative(comparators) {
2911         return ts.map(comparators, formatComparator).join(" ");
2912     }
2913     function formatComparator(comparator) {
2914         return "" + comparator.operator + comparator.operand;
2915     }
2916 })(ts || (ts = {}));
2917 var ts;
2918 (function (ts) {
2919     // token > SyntaxKind.Identifier => token is a keyword
2920     // Also, If you add a new SyntaxKind be sure to keep the `Markers` section at the bottom in sync
2921     var SyntaxKind;
2922     (function (SyntaxKind) {
2923         SyntaxKind[SyntaxKind["Unknown"] = 0] = "Unknown";
2924         SyntaxKind[SyntaxKind["EndOfFileToken"] = 1] = "EndOfFileToken";
2925         SyntaxKind[SyntaxKind["SingleLineCommentTrivia"] = 2] = "SingleLineCommentTrivia";
2926         SyntaxKind[SyntaxKind["MultiLineCommentTrivia"] = 3] = "MultiLineCommentTrivia";
2927         SyntaxKind[SyntaxKind["NewLineTrivia"] = 4] = "NewLineTrivia";
2928         SyntaxKind[SyntaxKind["WhitespaceTrivia"] = 5] = "WhitespaceTrivia";
2929         // We detect and preserve #! on the first line
2930         SyntaxKind[SyntaxKind["ShebangTrivia"] = 6] = "ShebangTrivia";
2931         // We detect and provide better error recovery when we encounter a git merge marker.  This
2932         // allows us to edit files with git-conflict markers in them in a much more pleasant manner.
2933         SyntaxKind[SyntaxKind["ConflictMarkerTrivia"] = 7] = "ConflictMarkerTrivia";
2934         // Literals
2935         SyntaxKind[SyntaxKind["NumericLiteral"] = 8] = "NumericLiteral";
2936         SyntaxKind[SyntaxKind["BigIntLiteral"] = 9] = "BigIntLiteral";
2937         SyntaxKind[SyntaxKind["StringLiteral"] = 10] = "StringLiteral";
2938         SyntaxKind[SyntaxKind["JsxText"] = 11] = "JsxText";
2939         SyntaxKind[SyntaxKind["JsxTextAllWhiteSpaces"] = 12] = "JsxTextAllWhiteSpaces";
2940         SyntaxKind[SyntaxKind["RegularExpressionLiteral"] = 13] = "RegularExpressionLiteral";
2941         SyntaxKind[SyntaxKind["NoSubstitutionTemplateLiteral"] = 14] = "NoSubstitutionTemplateLiteral";
2942         // Pseudo-literals
2943         SyntaxKind[SyntaxKind["TemplateHead"] = 15] = "TemplateHead";
2944         SyntaxKind[SyntaxKind["TemplateMiddle"] = 16] = "TemplateMiddle";
2945         SyntaxKind[SyntaxKind["TemplateTail"] = 17] = "TemplateTail";
2946         // Punctuation
2947         SyntaxKind[SyntaxKind["OpenBraceToken"] = 18] = "OpenBraceToken";
2948         SyntaxKind[SyntaxKind["CloseBraceToken"] = 19] = "CloseBraceToken";
2949         SyntaxKind[SyntaxKind["OpenParenToken"] = 20] = "OpenParenToken";
2950         SyntaxKind[SyntaxKind["CloseParenToken"] = 21] = "CloseParenToken";
2951         SyntaxKind[SyntaxKind["OpenBracketToken"] = 22] = "OpenBracketToken";
2952         SyntaxKind[SyntaxKind["CloseBracketToken"] = 23] = "CloseBracketToken";
2953         SyntaxKind[SyntaxKind["DotToken"] = 24] = "DotToken";
2954         SyntaxKind[SyntaxKind["DotDotDotToken"] = 25] = "DotDotDotToken";
2955         SyntaxKind[SyntaxKind["SemicolonToken"] = 26] = "SemicolonToken";
2956         SyntaxKind[SyntaxKind["CommaToken"] = 27] = "CommaToken";
2957         SyntaxKind[SyntaxKind["QuestionDotToken"] = 28] = "QuestionDotToken";
2958         SyntaxKind[SyntaxKind["LessThanToken"] = 29] = "LessThanToken";
2959         SyntaxKind[SyntaxKind["LessThanSlashToken"] = 30] = "LessThanSlashToken";
2960         SyntaxKind[SyntaxKind["GreaterThanToken"] = 31] = "GreaterThanToken";
2961         SyntaxKind[SyntaxKind["LessThanEqualsToken"] = 32] = "LessThanEqualsToken";
2962         SyntaxKind[SyntaxKind["GreaterThanEqualsToken"] = 33] = "GreaterThanEqualsToken";
2963         SyntaxKind[SyntaxKind["EqualsEqualsToken"] = 34] = "EqualsEqualsToken";
2964         SyntaxKind[SyntaxKind["ExclamationEqualsToken"] = 35] = "ExclamationEqualsToken";
2965         SyntaxKind[SyntaxKind["EqualsEqualsEqualsToken"] = 36] = "EqualsEqualsEqualsToken";
2966         SyntaxKind[SyntaxKind["ExclamationEqualsEqualsToken"] = 37] = "ExclamationEqualsEqualsToken";
2967         SyntaxKind[SyntaxKind["EqualsGreaterThanToken"] = 38] = "EqualsGreaterThanToken";
2968         SyntaxKind[SyntaxKind["PlusToken"] = 39] = "PlusToken";
2969         SyntaxKind[SyntaxKind["MinusToken"] = 40] = "MinusToken";
2970         SyntaxKind[SyntaxKind["AsteriskToken"] = 41] = "AsteriskToken";
2971         SyntaxKind[SyntaxKind["AsteriskAsteriskToken"] = 42] = "AsteriskAsteriskToken";
2972         SyntaxKind[SyntaxKind["SlashToken"] = 43] = "SlashToken";
2973         SyntaxKind[SyntaxKind["PercentToken"] = 44] = "PercentToken";
2974         SyntaxKind[SyntaxKind["PlusPlusToken"] = 45] = "PlusPlusToken";
2975         SyntaxKind[SyntaxKind["MinusMinusToken"] = 46] = "MinusMinusToken";
2976         SyntaxKind[SyntaxKind["LessThanLessThanToken"] = 47] = "LessThanLessThanToken";
2977         SyntaxKind[SyntaxKind["GreaterThanGreaterThanToken"] = 48] = "GreaterThanGreaterThanToken";
2978         SyntaxKind[SyntaxKind["GreaterThanGreaterThanGreaterThanToken"] = 49] = "GreaterThanGreaterThanGreaterThanToken";
2979         SyntaxKind[SyntaxKind["AmpersandToken"] = 50] = "AmpersandToken";
2980         SyntaxKind[SyntaxKind["BarToken"] = 51] = "BarToken";
2981         SyntaxKind[SyntaxKind["CaretToken"] = 52] = "CaretToken";
2982         SyntaxKind[SyntaxKind["ExclamationToken"] = 53] = "ExclamationToken";
2983         SyntaxKind[SyntaxKind["TildeToken"] = 54] = "TildeToken";
2984         SyntaxKind[SyntaxKind["AmpersandAmpersandToken"] = 55] = "AmpersandAmpersandToken";
2985         SyntaxKind[SyntaxKind["BarBarToken"] = 56] = "BarBarToken";
2986         SyntaxKind[SyntaxKind["QuestionToken"] = 57] = "QuestionToken";
2987         SyntaxKind[SyntaxKind["ColonToken"] = 58] = "ColonToken";
2988         SyntaxKind[SyntaxKind["AtToken"] = 59] = "AtToken";
2989         SyntaxKind[SyntaxKind["QuestionQuestionToken"] = 60] = "QuestionQuestionToken";
2990         /** Only the JSDoc scanner produces BacktickToken. The normal scanner produces NoSubstitutionTemplateLiteral and related kinds. */
2991         SyntaxKind[SyntaxKind["BacktickToken"] = 61] = "BacktickToken";
2992         // Assignments
2993         SyntaxKind[SyntaxKind["EqualsToken"] = 62] = "EqualsToken";
2994         SyntaxKind[SyntaxKind["PlusEqualsToken"] = 63] = "PlusEqualsToken";
2995         SyntaxKind[SyntaxKind["MinusEqualsToken"] = 64] = "MinusEqualsToken";
2996         SyntaxKind[SyntaxKind["AsteriskEqualsToken"] = 65] = "AsteriskEqualsToken";
2997         SyntaxKind[SyntaxKind["AsteriskAsteriskEqualsToken"] = 66] = "AsteriskAsteriskEqualsToken";
2998         SyntaxKind[SyntaxKind["SlashEqualsToken"] = 67] = "SlashEqualsToken";
2999         SyntaxKind[SyntaxKind["PercentEqualsToken"] = 68] = "PercentEqualsToken";
3000         SyntaxKind[SyntaxKind["LessThanLessThanEqualsToken"] = 69] = "LessThanLessThanEqualsToken";
3001         SyntaxKind[SyntaxKind["GreaterThanGreaterThanEqualsToken"] = 70] = "GreaterThanGreaterThanEqualsToken";
3002         SyntaxKind[SyntaxKind["GreaterThanGreaterThanGreaterThanEqualsToken"] = 71] = "GreaterThanGreaterThanGreaterThanEqualsToken";
3003         SyntaxKind[SyntaxKind["AmpersandEqualsToken"] = 72] = "AmpersandEqualsToken";
3004         SyntaxKind[SyntaxKind["BarEqualsToken"] = 73] = "BarEqualsToken";
3005         SyntaxKind[SyntaxKind["CaretEqualsToken"] = 74] = "CaretEqualsToken";
3006         // Identifiers and PrivateIdentifiers
3007         SyntaxKind[SyntaxKind["Identifier"] = 75] = "Identifier";
3008         SyntaxKind[SyntaxKind["PrivateIdentifier"] = 76] = "PrivateIdentifier";
3009         // Reserved words
3010         SyntaxKind[SyntaxKind["BreakKeyword"] = 77] = "BreakKeyword";
3011         SyntaxKind[SyntaxKind["CaseKeyword"] = 78] = "CaseKeyword";
3012         SyntaxKind[SyntaxKind["CatchKeyword"] = 79] = "CatchKeyword";
3013         SyntaxKind[SyntaxKind["ClassKeyword"] = 80] = "ClassKeyword";
3014         SyntaxKind[SyntaxKind["ConstKeyword"] = 81] = "ConstKeyword";
3015         SyntaxKind[SyntaxKind["ContinueKeyword"] = 82] = "ContinueKeyword";
3016         SyntaxKind[SyntaxKind["DebuggerKeyword"] = 83] = "DebuggerKeyword";
3017         SyntaxKind[SyntaxKind["DefaultKeyword"] = 84] = "DefaultKeyword";
3018         SyntaxKind[SyntaxKind["DeleteKeyword"] = 85] = "DeleteKeyword";
3019         SyntaxKind[SyntaxKind["DoKeyword"] = 86] = "DoKeyword";
3020         SyntaxKind[SyntaxKind["ElseKeyword"] = 87] = "ElseKeyword";
3021         SyntaxKind[SyntaxKind["EnumKeyword"] = 88] = "EnumKeyword";
3022         SyntaxKind[SyntaxKind["ExportKeyword"] = 89] = "ExportKeyword";
3023         SyntaxKind[SyntaxKind["ExtendsKeyword"] = 90] = "ExtendsKeyword";
3024         SyntaxKind[SyntaxKind["FalseKeyword"] = 91] = "FalseKeyword";
3025         SyntaxKind[SyntaxKind["FinallyKeyword"] = 92] = "FinallyKeyword";
3026         SyntaxKind[SyntaxKind["ForKeyword"] = 93] = "ForKeyword";
3027         SyntaxKind[SyntaxKind["FunctionKeyword"] = 94] = "FunctionKeyword";
3028         SyntaxKind[SyntaxKind["IfKeyword"] = 95] = "IfKeyword";
3029         SyntaxKind[SyntaxKind["ImportKeyword"] = 96] = "ImportKeyword";
3030         SyntaxKind[SyntaxKind["InKeyword"] = 97] = "InKeyword";
3031         SyntaxKind[SyntaxKind["InstanceOfKeyword"] = 98] = "InstanceOfKeyword";
3032         SyntaxKind[SyntaxKind["NewKeyword"] = 99] = "NewKeyword";
3033         SyntaxKind[SyntaxKind["NullKeyword"] = 100] = "NullKeyword";
3034         SyntaxKind[SyntaxKind["ReturnKeyword"] = 101] = "ReturnKeyword";
3035         SyntaxKind[SyntaxKind["SuperKeyword"] = 102] = "SuperKeyword";
3036         SyntaxKind[SyntaxKind["SwitchKeyword"] = 103] = "SwitchKeyword";
3037         SyntaxKind[SyntaxKind["ThisKeyword"] = 104] = "ThisKeyword";
3038         SyntaxKind[SyntaxKind["ThrowKeyword"] = 105] = "ThrowKeyword";
3039         SyntaxKind[SyntaxKind["TrueKeyword"] = 106] = "TrueKeyword";
3040         SyntaxKind[SyntaxKind["TryKeyword"] = 107] = "TryKeyword";
3041         SyntaxKind[SyntaxKind["TypeOfKeyword"] = 108] = "TypeOfKeyword";
3042         SyntaxKind[SyntaxKind["VarKeyword"] = 109] = "VarKeyword";
3043         SyntaxKind[SyntaxKind["VoidKeyword"] = 110] = "VoidKeyword";
3044         SyntaxKind[SyntaxKind["WhileKeyword"] = 111] = "WhileKeyword";
3045         SyntaxKind[SyntaxKind["WithKeyword"] = 112] = "WithKeyword";
3046         // Strict mode reserved words
3047         SyntaxKind[SyntaxKind["ImplementsKeyword"] = 113] = "ImplementsKeyword";
3048         SyntaxKind[SyntaxKind["InterfaceKeyword"] = 114] = "InterfaceKeyword";
3049         SyntaxKind[SyntaxKind["LetKeyword"] = 115] = "LetKeyword";
3050         SyntaxKind[SyntaxKind["PackageKeyword"] = 116] = "PackageKeyword";
3051         SyntaxKind[SyntaxKind["PrivateKeyword"] = 117] = "PrivateKeyword";
3052         SyntaxKind[SyntaxKind["ProtectedKeyword"] = 118] = "ProtectedKeyword";
3053         SyntaxKind[SyntaxKind["PublicKeyword"] = 119] = "PublicKeyword";
3054         SyntaxKind[SyntaxKind["StaticKeyword"] = 120] = "StaticKeyword";
3055         SyntaxKind[SyntaxKind["YieldKeyword"] = 121] = "YieldKeyword";
3056         // Contextual keywords
3057         SyntaxKind[SyntaxKind["AbstractKeyword"] = 122] = "AbstractKeyword";
3058         SyntaxKind[SyntaxKind["AsKeyword"] = 123] = "AsKeyword";
3059         SyntaxKind[SyntaxKind["AssertsKeyword"] = 124] = "AssertsKeyword";
3060         SyntaxKind[SyntaxKind["AnyKeyword"] = 125] = "AnyKeyword";
3061         SyntaxKind[SyntaxKind["AsyncKeyword"] = 126] = "AsyncKeyword";
3062         SyntaxKind[SyntaxKind["AwaitKeyword"] = 127] = "AwaitKeyword";
3063         SyntaxKind[SyntaxKind["BooleanKeyword"] = 128] = "BooleanKeyword";
3064         SyntaxKind[SyntaxKind["ConstructorKeyword"] = 129] = "ConstructorKeyword";
3065         SyntaxKind[SyntaxKind["DeclareKeyword"] = 130] = "DeclareKeyword";
3066         SyntaxKind[SyntaxKind["GetKeyword"] = 131] = "GetKeyword";
3067         SyntaxKind[SyntaxKind["InferKeyword"] = 132] = "InferKeyword";
3068         SyntaxKind[SyntaxKind["IsKeyword"] = 133] = "IsKeyword";
3069         SyntaxKind[SyntaxKind["KeyOfKeyword"] = 134] = "KeyOfKeyword";
3070         SyntaxKind[SyntaxKind["ModuleKeyword"] = 135] = "ModuleKeyword";
3071         SyntaxKind[SyntaxKind["NamespaceKeyword"] = 136] = "NamespaceKeyword";
3072         SyntaxKind[SyntaxKind["NeverKeyword"] = 137] = "NeverKeyword";
3073         SyntaxKind[SyntaxKind["ReadonlyKeyword"] = 138] = "ReadonlyKeyword";
3074         SyntaxKind[SyntaxKind["RequireKeyword"] = 139] = "RequireKeyword";
3075         SyntaxKind[SyntaxKind["NumberKeyword"] = 140] = "NumberKeyword";
3076         SyntaxKind[SyntaxKind["ObjectKeyword"] = 141] = "ObjectKeyword";
3077         SyntaxKind[SyntaxKind["SetKeyword"] = 142] = "SetKeyword";
3078         SyntaxKind[SyntaxKind["StringKeyword"] = 143] = "StringKeyword";
3079         SyntaxKind[SyntaxKind["SymbolKeyword"] = 144] = "SymbolKeyword";
3080         SyntaxKind[SyntaxKind["TypeKeyword"] = 145] = "TypeKeyword";
3081         SyntaxKind[SyntaxKind["UndefinedKeyword"] = 146] = "UndefinedKeyword";
3082         SyntaxKind[SyntaxKind["UniqueKeyword"] = 147] = "UniqueKeyword";
3083         SyntaxKind[SyntaxKind["UnknownKeyword"] = 148] = "UnknownKeyword";
3084         SyntaxKind[SyntaxKind["FromKeyword"] = 149] = "FromKeyword";
3085         SyntaxKind[SyntaxKind["GlobalKeyword"] = 150] = "GlobalKeyword";
3086         SyntaxKind[SyntaxKind["BigIntKeyword"] = 151] = "BigIntKeyword";
3087         SyntaxKind[SyntaxKind["OfKeyword"] = 152] = "OfKeyword";
3088         // Parse tree nodes
3089         // Names
3090         SyntaxKind[SyntaxKind["QualifiedName"] = 153] = "QualifiedName";
3091         SyntaxKind[SyntaxKind["ComputedPropertyName"] = 154] = "ComputedPropertyName";
3092         // Signature elements
3093         SyntaxKind[SyntaxKind["TypeParameter"] = 155] = "TypeParameter";
3094         SyntaxKind[SyntaxKind["Parameter"] = 156] = "Parameter";
3095         SyntaxKind[SyntaxKind["Decorator"] = 157] = "Decorator";
3096         // TypeMember
3097         SyntaxKind[SyntaxKind["PropertySignature"] = 158] = "PropertySignature";
3098         SyntaxKind[SyntaxKind["PropertyDeclaration"] = 159] = "PropertyDeclaration";
3099         SyntaxKind[SyntaxKind["MethodSignature"] = 160] = "MethodSignature";
3100         SyntaxKind[SyntaxKind["MethodDeclaration"] = 161] = "MethodDeclaration";
3101         SyntaxKind[SyntaxKind["Constructor"] = 162] = "Constructor";
3102         SyntaxKind[SyntaxKind["GetAccessor"] = 163] = "GetAccessor";
3103         SyntaxKind[SyntaxKind["SetAccessor"] = 164] = "SetAccessor";
3104         SyntaxKind[SyntaxKind["CallSignature"] = 165] = "CallSignature";
3105         SyntaxKind[SyntaxKind["ConstructSignature"] = 166] = "ConstructSignature";
3106         SyntaxKind[SyntaxKind["IndexSignature"] = 167] = "IndexSignature";
3107         // Type
3108         SyntaxKind[SyntaxKind["TypePredicate"] = 168] = "TypePredicate";
3109         SyntaxKind[SyntaxKind["TypeReference"] = 169] = "TypeReference";
3110         SyntaxKind[SyntaxKind["FunctionType"] = 170] = "FunctionType";
3111         SyntaxKind[SyntaxKind["ConstructorType"] = 171] = "ConstructorType";
3112         SyntaxKind[SyntaxKind["TypeQuery"] = 172] = "TypeQuery";
3113         SyntaxKind[SyntaxKind["TypeLiteral"] = 173] = "TypeLiteral";
3114         SyntaxKind[SyntaxKind["ArrayType"] = 174] = "ArrayType";
3115         SyntaxKind[SyntaxKind["TupleType"] = 175] = "TupleType";
3116         SyntaxKind[SyntaxKind["OptionalType"] = 176] = "OptionalType";
3117         SyntaxKind[SyntaxKind["RestType"] = 177] = "RestType";
3118         SyntaxKind[SyntaxKind["UnionType"] = 178] = "UnionType";
3119         SyntaxKind[SyntaxKind["IntersectionType"] = 179] = "IntersectionType";
3120         SyntaxKind[SyntaxKind["ConditionalType"] = 180] = "ConditionalType";
3121         SyntaxKind[SyntaxKind["InferType"] = 181] = "InferType";
3122         SyntaxKind[SyntaxKind["ParenthesizedType"] = 182] = "ParenthesizedType";
3123         SyntaxKind[SyntaxKind["ThisType"] = 183] = "ThisType";
3124         SyntaxKind[SyntaxKind["TypeOperator"] = 184] = "TypeOperator";
3125         SyntaxKind[SyntaxKind["IndexedAccessType"] = 185] = "IndexedAccessType";
3126         SyntaxKind[SyntaxKind["MappedType"] = 186] = "MappedType";
3127         SyntaxKind[SyntaxKind["LiteralType"] = 187] = "LiteralType";
3128         SyntaxKind[SyntaxKind["ImportType"] = 188] = "ImportType";
3129         // Binding patterns
3130         SyntaxKind[SyntaxKind["ObjectBindingPattern"] = 189] = "ObjectBindingPattern";
3131         SyntaxKind[SyntaxKind["ArrayBindingPattern"] = 190] = "ArrayBindingPattern";
3132         SyntaxKind[SyntaxKind["BindingElement"] = 191] = "BindingElement";
3133         // Expression
3134         SyntaxKind[SyntaxKind["ArrayLiteralExpression"] = 192] = "ArrayLiteralExpression";
3135         SyntaxKind[SyntaxKind["ObjectLiteralExpression"] = 193] = "ObjectLiteralExpression";
3136         SyntaxKind[SyntaxKind["PropertyAccessExpression"] = 194] = "PropertyAccessExpression";
3137         SyntaxKind[SyntaxKind["ElementAccessExpression"] = 195] = "ElementAccessExpression";
3138         SyntaxKind[SyntaxKind["CallExpression"] = 196] = "CallExpression";
3139         SyntaxKind[SyntaxKind["NewExpression"] = 197] = "NewExpression";
3140         SyntaxKind[SyntaxKind["TaggedTemplateExpression"] = 198] = "TaggedTemplateExpression";
3141         SyntaxKind[SyntaxKind["TypeAssertionExpression"] = 199] = "TypeAssertionExpression";
3142         SyntaxKind[SyntaxKind["ParenthesizedExpression"] = 200] = "ParenthesizedExpression";
3143         SyntaxKind[SyntaxKind["FunctionExpression"] = 201] = "FunctionExpression";
3144         SyntaxKind[SyntaxKind["ArrowFunction"] = 202] = "ArrowFunction";
3145         SyntaxKind[SyntaxKind["DeleteExpression"] = 203] = "DeleteExpression";
3146         SyntaxKind[SyntaxKind["TypeOfExpression"] = 204] = "TypeOfExpression";
3147         SyntaxKind[SyntaxKind["VoidExpression"] = 205] = "VoidExpression";
3148         SyntaxKind[SyntaxKind["AwaitExpression"] = 206] = "AwaitExpression";
3149         SyntaxKind[SyntaxKind["PrefixUnaryExpression"] = 207] = "PrefixUnaryExpression";
3150         SyntaxKind[SyntaxKind["PostfixUnaryExpression"] = 208] = "PostfixUnaryExpression";
3151         SyntaxKind[SyntaxKind["BinaryExpression"] = 209] = "BinaryExpression";
3152         SyntaxKind[SyntaxKind["ConditionalExpression"] = 210] = "ConditionalExpression";
3153         SyntaxKind[SyntaxKind["TemplateExpression"] = 211] = "TemplateExpression";
3154         SyntaxKind[SyntaxKind["YieldExpression"] = 212] = "YieldExpression";
3155         SyntaxKind[SyntaxKind["SpreadElement"] = 213] = "SpreadElement";
3156         SyntaxKind[SyntaxKind["ClassExpression"] = 214] = "ClassExpression";
3157         SyntaxKind[SyntaxKind["OmittedExpression"] = 215] = "OmittedExpression";
3158         SyntaxKind[SyntaxKind["ExpressionWithTypeArguments"] = 216] = "ExpressionWithTypeArguments";
3159         SyntaxKind[SyntaxKind["AsExpression"] = 217] = "AsExpression";
3160         SyntaxKind[SyntaxKind["NonNullExpression"] = 218] = "NonNullExpression";
3161         SyntaxKind[SyntaxKind["MetaProperty"] = 219] = "MetaProperty";
3162         SyntaxKind[SyntaxKind["SyntheticExpression"] = 220] = "SyntheticExpression";
3163         // Misc
3164         SyntaxKind[SyntaxKind["TemplateSpan"] = 221] = "TemplateSpan";
3165         SyntaxKind[SyntaxKind["SemicolonClassElement"] = 222] = "SemicolonClassElement";
3166         // Element
3167         SyntaxKind[SyntaxKind["Block"] = 223] = "Block";
3168         SyntaxKind[SyntaxKind["EmptyStatement"] = 224] = "EmptyStatement";
3169         SyntaxKind[SyntaxKind["VariableStatement"] = 225] = "VariableStatement";
3170         SyntaxKind[SyntaxKind["ExpressionStatement"] = 226] = "ExpressionStatement";
3171         SyntaxKind[SyntaxKind["IfStatement"] = 227] = "IfStatement";
3172         SyntaxKind[SyntaxKind["DoStatement"] = 228] = "DoStatement";
3173         SyntaxKind[SyntaxKind["WhileStatement"] = 229] = "WhileStatement";
3174         SyntaxKind[SyntaxKind["ForStatement"] = 230] = "ForStatement";
3175         SyntaxKind[SyntaxKind["ForInStatement"] = 231] = "ForInStatement";
3176         SyntaxKind[SyntaxKind["ForOfStatement"] = 232] = "ForOfStatement";
3177         SyntaxKind[SyntaxKind["ContinueStatement"] = 233] = "ContinueStatement";
3178         SyntaxKind[SyntaxKind["BreakStatement"] = 234] = "BreakStatement";
3179         SyntaxKind[SyntaxKind["ReturnStatement"] = 235] = "ReturnStatement";
3180         SyntaxKind[SyntaxKind["WithStatement"] = 236] = "WithStatement";
3181         SyntaxKind[SyntaxKind["SwitchStatement"] = 237] = "SwitchStatement";
3182         SyntaxKind[SyntaxKind["LabeledStatement"] = 238] = "LabeledStatement";
3183         SyntaxKind[SyntaxKind["ThrowStatement"] = 239] = "ThrowStatement";
3184         SyntaxKind[SyntaxKind["TryStatement"] = 240] = "TryStatement";
3185         SyntaxKind[SyntaxKind["DebuggerStatement"] = 241] = "DebuggerStatement";
3186         SyntaxKind[SyntaxKind["VariableDeclaration"] = 242] = "VariableDeclaration";
3187         SyntaxKind[SyntaxKind["VariableDeclarationList"] = 243] = "VariableDeclarationList";
3188         SyntaxKind[SyntaxKind["FunctionDeclaration"] = 244] = "FunctionDeclaration";
3189         SyntaxKind[SyntaxKind["ClassDeclaration"] = 245] = "ClassDeclaration";
3190         SyntaxKind[SyntaxKind["InterfaceDeclaration"] = 246] = "InterfaceDeclaration";
3191         SyntaxKind[SyntaxKind["TypeAliasDeclaration"] = 247] = "TypeAliasDeclaration";
3192         SyntaxKind[SyntaxKind["EnumDeclaration"] = 248] = "EnumDeclaration";
3193         SyntaxKind[SyntaxKind["ModuleDeclaration"] = 249] = "ModuleDeclaration";
3194         SyntaxKind[SyntaxKind["ModuleBlock"] = 250] = "ModuleBlock";
3195         SyntaxKind[SyntaxKind["CaseBlock"] = 251] = "CaseBlock";
3196         SyntaxKind[SyntaxKind["NamespaceExportDeclaration"] = 252] = "NamespaceExportDeclaration";
3197         SyntaxKind[SyntaxKind["ImportEqualsDeclaration"] = 253] = "ImportEqualsDeclaration";
3198         SyntaxKind[SyntaxKind["ImportDeclaration"] = 254] = "ImportDeclaration";
3199         SyntaxKind[SyntaxKind["ImportClause"] = 255] = "ImportClause";
3200         SyntaxKind[SyntaxKind["NamespaceImport"] = 256] = "NamespaceImport";
3201         SyntaxKind[SyntaxKind["NamedImports"] = 257] = "NamedImports";
3202         SyntaxKind[SyntaxKind["ImportSpecifier"] = 258] = "ImportSpecifier";
3203         SyntaxKind[SyntaxKind["ExportAssignment"] = 259] = "ExportAssignment";
3204         SyntaxKind[SyntaxKind["ExportDeclaration"] = 260] = "ExportDeclaration";
3205         SyntaxKind[SyntaxKind["NamedExports"] = 261] = "NamedExports";
3206         SyntaxKind[SyntaxKind["NamespaceExport"] = 262] = "NamespaceExport";
3207         SyntaxKind[SyntaxKind["ExportSpecifier"] = 263] = "ExportSpecifier";
3208         SyntaxKind[SyntaxKind["MissingDeclaration"] = 264] = "MissingDeclaration";
3209         // Module references
3210         SyntaxKind[SyntaxKind["ExternalModuleReference"] = 265] = "ExternalModuleReference";
3211         // JSX
3212         SyntaxKind[SyntaxKind["JsxElement"] = 266] = "JsxElement";
3213         SyntaxKind[SyntaxKind["JsxSelfClosingElement"] = 267] = "JsxSelfClosingElement";
3214         SyntaxKind[SyntaxKind["JsxOpeningElement"] = 268] = "JsxOpeningElement";
3215         SyntaxKind[SyntaxKind["JsxClosingElement"] = 269] = "JsxClosingElement";
3216         SyntaxKind[SyntaxKind["JsxFragment"] = 270] = "JsxFragment";
3217         SyntaxKind[SyntaxKind["JsxOpeningFragment"] = 271] = "JsxOpeningFragment";
3218         SyntaxKind[SyntaxKind["JsxClosingFragment"] = 272] = "JsxClosingFragment";
3219         SyntaxKind[SyntaxKind["JsxAttribute"] = 273] = "JsxAttribute";
3220         SyntaxKind[SyntaxKind["JsxAttributes"] = 274] = "JsxAttributes";
3221         SyntaxKind[SyntaxKind["JsxSpreadAttribute"] = 275] = "JsxSpreadAttribute";
3222         SyntaxKind[SyntaxKind["JsxExpression"] = 276] = "JsxExpression";
3223         // Clauses
3224         SyntaxKind[SyntaxKind["CaseClause"] = 277] = "CaseClause";
3225         SyntaxKind[SyntaxKind["DefaultClause"] = 278] = "DefaultClause";
3226         SyntaxKind[SyntaxKind["HeritageClause"] = 279] = "HeritageClause";
3227         SyntaxKind[SyntaxKind["CatchClause"] = 280] = "CatchClause";
3228         // Property assignments
3229         SyntaxKind[SyntaxKind["PropertyAssignment"] = 281] = "PropertyAssignment";
3230         SyntaxKind[SyntaxKind["ShorthandPropertyAssignment"] = 282] = "ShorthandPropertyAssignment";
3231         SyntaxKind[SyntaxKind["SpreadAssignment"] = 283] = "SpreadAssignment";
3232         // Enum
3233         SyntaxKind[SyntaxKind["EnumMember"] = 284] = "EnumMember";
3234         // Unparsed
3235         SyntaxKind[SyntaxKind["UnparsedPrologue"] = 285] = "UnparsedPrologue";
3236         SyntaxKind[SyntaxKind["UnparsedPrepend"] = 286] = "UnparsedPrepend";
3237         SyntaxKind[SyntaxKind["UnparsedText"] = 287] = "UnparsedText";
3238         SyntaxKind[SyntaxKind["UnparsedInternalText"] = 288] = "UnparsedInternalText";
3239         SyntaxKind[SyntaxKind["UnparsedSyntheticReference"] = 289] = "UnparsedSyntheticReference";
3240         // Top-level nodes
3241         SyntaxKind[SyntaxKind["SourceFile"] = 290] = "SourceFile";
3242         SyntaxKind[SyntaxKind["Bundle"] = 291] = "Bundle";
3243         SyntaxKind[SyntaxKind["UnparsedSource"] = 292] = "UnparsedSource";
3244         SyntaxKind[SyntaxKind["InputFiles"] = 293] = "InputFiles";
3245         // JSDoc nodes
3246         SyntaxKind[SyntaxKind["JSDocTypeExpression"] = 294] = "JSDocTypeExpression";
3247         // The * type
3248         SyntaxKind[SyntaxKind["JSDocAllType"] = 295] = "JSDocAllType";
3249         // The ? type
3250         SyntaxKind[SyntaxKind["JSDocUnknownType"] = 296] = "JSDocUnknownType";
3251         SyntaxKind[SyntaxKind["JSDocNullableType"] = 297] = "JSDocNullableType";
3252         SyntaxKind[SyntaxKind["JSDocNonNullableType"] = 298] = "JSDocNonNullableType";
3253         SyntaxKind[SyntaxKind["JSDocOptionalType"] = 299] = "JSDocOptionalType";
3254         SyntaxKind[SyntaxKind["JSDocFunctionType"] = 300] = "JSDocFunctionType";
3255         SyntaxKind[SyntaxKind["JSDocVariadicType"] = 301] = "JSDocVariadicType";
3256         // https://jsdoc.app/about-namepaths.html
3257         SyntaxKind[SyntaxKind["JSDocNamepathType"] = 302] = "JSDocNamepathType";
3258         SyntaxKind[SyntaxKind["JSDocComment"] = 303] = "JSDocComment";
3259         SyntaxKind[SyntaxKind["JSDocTypeLiteral"] = 304] = "JSDocTypeLiteral";
3260         SyntaxKind[SyntaxKind["JSDocSignature"] = 305] = "JSDocSignature";
3261         SyntaxKind[SyntaxKind["JSDocTag"] = 306] = "JSDocTag";
3262         SyntaxKind[SyntaxKind["JSDocAugmentsTag"] = 307] = "JSDocAugmentsTag";
3263         SyntaxKind[SyntaxKind["JSDocImplementsTag"] = 308] = "JSDocImplementsTag";
3264         SyntaxKind[SyntaxKind["JSDocAuthorTag"] = 309] = "JSDocAuthorTag";
3265         SyntaxKind[SyntaxKind["JSDocClassTag"] = 310] = "JSDocClassTag";
3266         SyntaxKind[SyntaxKind["JSDocPublicTag"] = 311] = "JSDocPublicTag";
3267         SyntaxKind[SyntaxKind["JSDocPrivateTag"] = 312] = "JSDocPrivateTag";
3268         SyntaxKind[SyntaxKind["JSDocProtectedTag"] = 313] = "JSDocProtectedTag";
3269         SyntaxKind[SyntaxKind["JSDocReadonlyTag"] = 314] = "JSDocReadonlyTag";
3270         SyntaxKind[SyntaxKind["JSDocCallbackTag"] = 315] = "JSDocCallbackTag";
3271         SyntaxKind[SyntaxKind["JSDocEnumTag"] = 316] = "JSDocEnumTag";
3272         SyntaxKind[SyntaxKind["JSDocParameterTag"] = 317] = "JSDocParameterTag";
3273         SyntaxKind[SyntaxKind["JSDocReturnTag"] = 318] = "JSDocReturnTag";
3274         SyntaxKind[SyntaxKind["JSDocThisTag"] = 319] = "JSDocThisTag";
3275         SyntaxKind[SyntaxKind["JSDocTypeTag"] = 320] = "JSDocTypeTag";
3276         SyntaxKind[SyntaxKind["JSDocTemplateTag"] = 321] = "JSDocTemplateTag";
3277         SyntaxKind[SyntaxKind["JSDocTypedefTag"] = 322] = "JSDocTypedefTag";
3278         SyntaxKind[SyntaxKind["JSDocPropertyTag"] = 323] = "JSDocPropertyTag";
3279         // Synthesized list
3280         SyntaxKind[SyntaxKind["SyntaxList"] = 324] = "SyntaxList";
3281         // Transformation nodes
3282         SyntaxKind[SyntaxKind["NotEmittedStatement"] = 325] = "NotEmittedStatement";
3283         SyntaxKind[SyntaxKind["PartiallyEmittedExpression"] = 326] = "PartiallyEmittedExpression";
3284         SyntaxKind[SyntaxKind["CommaListExpression"] = 327] = "CommaListExpression";
3285         SyntaxKind[SyntaxKind["MergeDeclarationMarker"] = 328] = "MergeDeclarationMarker";
3286         SyntaxKind[SyntaxKind["EndOfDeclarationMarker"] = 329] = "EndOfDeclarationMarker";
3287         SyntaxKind[SyntaxKind["SyntheticReferenceExpression"] = 330] = "SyntheticReferenceExpression";
3288         // Enum value count
3289         SyntaxKind[SyntaxKind["Count"] = 331] = "Count";
3290         // Markers
3291         SyntaxKind[SyntaxKind["FirstAssignment"] = 62] = "FirstAssignment";
3292         SyntaxKind[SyntaxKind["LastAssignment"] = 74] = "LastAssignment";
3293         SyntaxKind[SyntaxKind["FirstCompoundAssignment"] = 63] = "FirstCompoundAssignment";
3294         SyntaxKind[SyntaxKind["LastCompoundAssignment"] = 74] = "LastCompoundAssignment";
3295         SyntaxKind[SyntaxKind["FirstReservedWord"] = 77] = "FirstReservedWord";
3296         SyntaxKind[SyntaxKind["LastReservedWord"] = 112] = "LastReservedWord";
3297         SyntaxKind[SyntaxKind["FirstKeyword"] = 77] = "FirstKeyword";
3298         SyntaxKind[SyntaxKind["LastKeyword"] = 152] = "LastKeyword";
3299         SyntaxKind[SyntaxKind["FirstFutureReservedWord"] = 113] = "FirstFutureReservedWord";
3300         SyntaxKind[SyntaxKind["LastFutureReservedWord"] = 121] = "LastFutureReservedWord";
3301         SyntaxKind[SyntaxKind["FirstTypeNode"] = 168] = "FirstTypeNode";
3302         SyntaxKind[SyntaxKind["LastTypeNode"] = 188] = "LastTypeNode";
3303         SyntaxKind[SyntaxKind["FirstPunctuation"] = 18] = "FirstPunctuation";
3304         SyntaxKind[SyntaxKind["LastPunctuation"] = 74] = "LastPunctuation";
3305         SyntaxKind[SyntaxKind["FirstToken"] = 0] = "FirstToken";
3306         SyntaxKind[SyntaxKind["LastToken"] = 152] = "LastToken";
3307         SyntaxKind[SyntaxKind["FirstTriviaToken"] = 2] = "FirstTriviaToken";
3308         SyntaxKind[SyntaxKind["LastTriviaToken"] = 7] = "LastTriviaToken";
3309         SyntaxKind[SyntaxKind["FirstLiteralToken"] = 8] = "FirstLiteralToken";
3310         SyntaxKind[SyntaxKind["LastLiteralToken"] = 14] = "LastLiteralToken";
3311         SyntaxKind[SyntaxKind["FirstTemplateToken"] = 14] = "FirstTemplateToken";
3312         SyntaxKind[SyntaxKind["LastTemplateToken"] = 17] = "LastTemplateToken";
3313         SyntaxKind[SyntaxKind["FirstBinaryOperator"] = 29] = "FirstBinaryOperator";
3314         SyntaxKind[SyntaxKind["LastBinaryOperator"] = 74] = "LastBinaryOperator";
3315         SyntaxKind[SyntaxKind["FirstStatement"] = 225] = "FirstStatement";
3316         SyntaxKind[SyntaxKind["LastStatement"] = 241] = "LastStatement";
3317         SyntaxKind[SyntaxKind["FirstNode"] = 153] = "FirstNode";
3318         SyntaxKind[SyntaxKind["FirstJSDocNode"] = 294] = "FirstJSDocNode";
3319         SyntaxKind[SyntaxKind["LastJSDocNode"] = 323] = "LastJSDocNode";
3320         SyntaxKind[SyntaxKind["FirstJSDocTagNode"] = 306] = "FirstJSDocTagNode";
3321         SyntaxKind[SyntaxKind["LastJSDocTagNode"] = 323] = "LastJSDocTagNode";
3322         /* @internal */ SyntaxKind[SyntaxKind["FirstContextualKeyword"] = 122] = "FirstContextualKeyword";
3323         /* @internal */ SyntaxKind[SyntaxKind["LastContextualKeyword"] = 152] = "LastContextualKeyword";
3324     })(SyntaxKind = ts.SyntaxKind || (ts.SyntaxKind = {}));
3325     var NodeFlags;
3326     (function (NodeFlags) {
3327         NodeFlags[NodeFlags["None"] = 0] = "None";
3328         NodeFlags[NodeFlags["Let"] = 1] = "Let";
3329         NodeFlags[NodeFlags["Const"] = 2] = "Const";
3330         NodeFlags[NodeFlags["NestedNamespace"] = 4] = "NestedNamespace";
3331         NodeFlags[NodeFlags["Synthesized"] = 8] = "Synthesized";
3332         NodeFlags[NodeFlags["Namespace"] = 16] = "Namespace";
3333         NodeFlags[NodeFlags["OptionalChain"] = 32] = "OptionalChain";
3334         NodeFlags[NodeFlags["ExportContext"] = 64] = "ExportContext";
3335         NodeFlags[NodeFlags["ContainsThis"] = 128] = "ContainsThis";
3336         NodeFlags[NodeFlags["HasImplicitReturn"] = 256] = "HasImplicitReturn";
3337         NodeFlags[NodeFlags["HasExplicitReturn"] = 512] = "HasExplicitReturn";
3338         NodeFlags[NodeFlags["GlobalAugmentation"] = 1024] = "GlobalAugmentation";
3339         NodeFlags[NodeFlags["HasAsyncFunctions"] = 2048] = "HasAsyncFunctions";
3340         NodeFlags[NodeFlags["DisallowInContext"] = 4096] = "DisallowInContext";
3341         NodeFlags[NodeFlags["YieldContext"] = 8192] = "YieldContext";
3342         NodeFlags[NodeFlags["DecoratorContext"] = 16384] = "DecoratorContext";
3343         NodeFlags[NodeFlags["AwaitContext"] = 32768] = "AwaitContext";
3344         NodeFlags[NodeFlags["ThisNodeHasError"] = 65536] = "ThisNodeHasError";
3345         NodeFlags[NodeFlags["JavaScriptFile"] = 131072] = "JavaScriptFile";
3346         NodeFlags[NodeFlags["ThisNodeOrAnySubNodesHasError"] = 262144] = "ThisNodeOrAnySubNodesHasError";
3347         NodeFlags[NodeFlags["HasAggregatedChildData"] = 524288] = "HasAggregatedChildData";
3348         // These flags will be set when the parser encounters a dynamic import expression or 'import.meta' to avoid
3349         // walking the tree if the flags are not set. However, these flags are just a approximation
3350         // (hence why it's named "PossiblyContainsDynamicImport") because once set, the flags never get cleared.
3351         // During editing, if a dynamic import is removed, incremental parsing will *NOT* clear this flag.
3352         // This means that the tree will always be traversed during module resolution, or when looking for external module indicators.
3353         // However, the removal operation should not occur often and in the case of the
3354         // removal, it is likely that users will add the import anyway.
3355         // The advantage of this approach is its simplicity. For the case of batch compilation,
3356         // we guarantee that users won't have to pay the price of walking the tree if a dynamic import isn't used.
3357         /* @internal */ NodeFlags[NodeFlags["PossiblyContainsDynamicImport"] = 1048576] = "PossiblyContainsDynamicImport";
3358         /* @internal */ NodeFlags[NodeFlags["PossiblyContainsImportMeta"] = 2097152] = "PossiblyContainsImportMeta";
3359         NodeFlags[NodeFlags["JSDoc"] = 4194304] = "JSDoc";
3360         /* @internal */ NodeFlags[NodeFlags["Ambient"] = 8388608] = "Ambient";
3361         /* @internal */ NodeFlags[NodeFlags["InWithStatement"] = 16777216] = "InWithStatement";
3362         NodeFlags[NodeFlags["JsonFile"] = 33554432] = "JsonFile";
3363         /* @internal */ NodeFlags[NodeFlags["TypeCached"] = 67108864] = "TypeCached";
3364         NodeFlags[NodeFlags["BlockScoped"] = 3] = "BlockScoped";
3365         NodeFlags[NodeFlags["ReachabilityCheckFlags"] = 768] = "ReachabilityCheckFlags";
3366         NodeFlags[NodeFlags["ReachabilityAndEmitFlags"] = 2816] = "ReachabilityAndEmitFlags";
3367         // Parsing context flags
3368         NodeFlags[NodeFlags["ContextFlags"] = 25358336] = "ContextFlags";
3369         // Exclude these flags when parsing a Type
3370         NodeFlags[NodeFlags["TypeExcludesFlags"] = 40960] = "TypeExcludesFlags";
3371         // Represents all flags that are potentially set once and
3372         // never cleared on SourceFiles which get re-used in between incremental parses.
3373         // See the comment above on `PossiblyContainsDynamicImport` and `PossiblyContainsImportMeta`.
3374         /* @internal */ NodeFlags[NodeFlags["PermanentlySetIncrementalFlags"] = 3145728] = "PermanentlySetIncrementalFlags";
3375     })(NodeFlags = ts.NodeFlags || (ts.NodeFlags = {}));
3376     var ModifierFlags;
3377     (function (ModifierFlags) {
3378         ModifierFlags[ModifierFlags["None"] = 0] = "None";
3379         ModifierFlags[ModifierFlags["Export"] = 1] = "Export";
3380         ModifierFlags[ModifierFlags["Ambient"] = 2] = "Ambient";
3381         ModifierFlags[ModifierFlags["Public"] = 4] = "Public";
3382         ModifierFlags[ModifierFlags["Private"] = 8] = "Private";
3383         ModifierFlags[ModifierFlags["Protected"] = 16] = "Protected";
3384         ModifierFlags[ModifierFlags["Static"] = 32] = "Static";
3385         ModifierFlags[ModifierFlags["Readonly"] = 64] = "Readonly";
3386         ModifierFlags[ModifierFlags["Abstract"] = 128] = "Abstract";
3387         ModifierFlags[ModifierFlags["Async"] = 256] = "Async";
3388         ModifierFlags[ModifierFlags["Default"] = 512] = "Default";
3389         ModifierFlags[ModifierFlags["Const"] = 2048] = "Const";
3390         ModifierFlags[ModifierFlags["HasComputedFlags"] = 536870912] = "HasComputedFlags";
3391         ModifierFlags[ModifierFlags["AccessibilityModifier"] = 28] = "AccessibilityModifier";
3392         // Accessibility modifiers and 'readonly' can be attached to a parameter in a constructor to make it a property.
3393         ModifierFlags[ModifierFlags["ParameterPropertyModifier"] = 92] = "ParameterPropertyModifier";
3394         ModifierFlags[ModifierFlags["NonPublicAccessibilityModifier"] = 24] = "NonPublicAccessibilityModifier";
3395         ModifierFlags[ModifierFlags["TypeScriptModifier"] = 2270] = "TypeScriptModifier";
3396         ModifierFlags[ModifierFlags["ExportDefault"] = 513] = "ExportDefault";
3397         ModifierFlags[ModifierFlags["All"] = 3071] = "All";
3398     })(ModifierFlags = ts.ModifierFlags || (ts.ModifierFlags = {}));
3399     var JsxFlags;
3400     (function (JsxFlags) {
3401         JsxFlags[JsxFlags["None"] = 0] = "None";
3402         /** An element from a named property of the JSX.IntrinsicElements interface */
3403         JsxFlags[JsxFlags["IntrinsicNamedElement"] = 1] = "IntrinsicNamedElement";
3404         /** An element inferred from the string index signature of the JSX.IntrinsicElements interface */
3405         JsxFlags[JsxFlags["IntrinsicIndexedElement"] = 2] = "IntrinsicIndexedElement";
3406         JsxFlags[JsxFlags["IntrinsicElement"] = 3] = "IntrinsicElement";
3407     })(JsxFlags = ts.JsxFlags || (ts.JsxFlags = {}));
3408     /* @internal */
3409     var RelationComparisonResult;
3410     (function (RelationComparisonResult) {
3411         RelationComparisonResult[RelationComparisonResult["Succeeded"] = 1] = "Succeeded";
3412         RelationComparisonResult[RelationComparisonResult["Failed"] = 2] = "Failed";
3413         RelationComparisonResult[RelationComparisonResult["Reported"] = 4] = "Reported";
3414         RelationComparisonResult[RelationComparisonResult["ReportsUnmeasurable"] = 8] = "ReportsUnmeasurable";
3415         RelationComparisonResult[RelationComparisonResult["ReportsUnreliable"] = 16] = "ReportsUnreliable";
3416         RelationComparisonResult[RelationComparisonResult["ReportsMask"] = 24] = "ReportsMask";
3417     })(RelationComparisonResult = ts.RelationComparisonResult || (ts.RelationComparisonResult = {}));
3418     /*@internal*/
3419     var GeneratedIdentifierFlags;
3420     (function (GeneratedIdentifierFlags) {
3421         // Kinds
3422         GeneratedIdentifierFlags[GeneratedIdentifierFlags["None"] = 0] = "None";
3423         GeneratedIdentifierFlags[GeneratedIdentifierFlags["Auto"] = 1] = "Auto";
3424         GeneratedIdentifierFlags[GeneratedIdentifierFlags["Loop"] = 2] = "Loop";
3425         GeneratedIdentifierFlags[GeneratedIdentifierFlags["Unique"] = 3] = "Unique";
3426         GeneratedIdentifierFlags[GeneratedIdentifierFlags["Node"] = 4] = "Node";
3427         GeneratedIdentifierFlags[GeneratedIdentifierFlags["KindMask"] = 7] = "KindMask";
3428         // Flags
3429         GeneratedIdentifierFlags[GeneratedIdentifierFlags["ReservedInNestedScopes"] = 8] = "ReservedInNestedScopes";
3430         GeneratedIdentifierFlags[GeneratedIdentifierFlags["Optimistic"] = 16] = "Optimistic";
3431         GeneratedIdentifierFlags[GeneratedIdentifierFlags["FileLevel"] = 32] = "FileLevel";
3432     })(GeneratedIdentifierFlags = ts.GeneratedIdentifierFlags || (ts.GeneratedIdentifierFlags = {}));
3433     var TokenFlags;
3434     (function (TokenFlags) {
3435         TokenFlags[TokenFlags["None"] = 0] = "None";
3436         /* @internal */
3437         TokenFlags[TokenFlags["PrecedingLineBreak"] = 1] = "PrecedingLineBreak";
3438         /* @internal */
3439         TokenFlags[TokenFlags["PrecedingJSDocComment"] = 2] = "PrecedingJSDocComment";
3440         /* @internal */
3441         TokenFlags[TokenFlags["Unterminated"] = 4] = "Unterminated";
3442         /* @internal */
3443         TokenFlags[TokenFlags["ExtendedUnicodeEscape"] = 8] = "ExtendedUnicodeEscape";
3444         TokenFlags[TokenFlags["Scientific"] = 16] = "Scientific";
3445         TokenFlags[TokenFlags["Octal"] = 32] = "Octal";
3446         TokenFlags[TokenFlags["HexSpecifier"] = 64] = "HexSpecifier";
3447         TokenFlags[TokenFlags["BinarySpecifier"] = 128] = "BinarySpecifier";
3448         TokenFlags[TokenFlags["OctalSpecifier"] = 256] = "OctalSpecifier";
3449         /* @internal */
3450         TokenFlags[TokenFlags["ContainsSeparator"] = 512] = "ContainsSeparator";
3451         /* @internal */
3452         TokenFlags[TokenFlags["UnicodeEscape"] = 1024] = "UnicodeEscape";
3453         /* @internal */
3454         TokenFlags[TokenFlags["ContainsInvalidEscape"] = 2048] = "ContainsInvalidEscape";
3455         /* @internal */
3456         TokenFlags[TokenFlags["BinaryOrOctalSpecifier"] = 384] = "BinaryOrOctalSpecifier";
3457         /* @internal */
3458         TokenFlags[TokenFlags["NumericLiteralFlags"] = 1008] = "NumericLiteralFlags";
3459     })(TokenFlags = ts.TokenFlags || (ts.TokenFlags = {}));
3460     // NOTE: Ensure this is up-to-date with src/debug/debug.ts
3461     var FlowFlags;
3462     (function (FlowFlags) {
3463         FlowFlags[FlowFlags["Unreachable"] = 1] = "Unreachable";
3464         FlowFlags[FlowFlags["Start"] = 2] = "Start";
3465         FlowFlags[FlowFlags["BranchLabel"] = 4] = "BranchLabel";
3466         FlowFlags[FlowFlags["LoopLabel"] = 8] = "LoopLabel";
3467         FlowFlags[FlowFlags["Assignment"] = 16] = "Assignment";
3468         FlowFlags[FlowFlags["TrueCondition"] = 32] = "TrueCondition";
3469         FlowFlags[FlowFlags["FalseCondition"] = 64] = "FalseCondition";
3470         FlowFlags[FlowFlags["SwitchClause"] = 128] = "SwitchClause";
3471         FlowFlags[FlowFlags["ArrayMutation"] = 256] = "ArrayMutation";
3472         FlowFlags[FlowFlags["Call"] = 512] = "Call";
3473         FlowFlags[FlowFlags["ReduceLabel"] = 1024] = "ReduceLabel";
3474         FlowFlags[FlowFlags["Referenced"] = 2048] = "Referenced";
3475         FlowFlags[FlowFlags["Shared"] = 4096] = "Shared";
3476         FlowFlags[FlowFlags["Label"] = 12] = "Label";
3477         FlowFlags[FlowFlags["Condition"] = 96] = "Condition";
3478     })(FlowFlags = ts.FlowFlags || (ts.FlowFlags = {}));
3479     /* @internal */
3480     var CommentDirectiveType;
3481     (function (CommentDirectiveType) {
3482         CommentDirectiveType[CommentDirectiveType["ExpectError"] = 0] = "ExpectError";
3483         CommentDirectiveType[CommentDirectiveType["Ignore"] = 1] = "Ignore";
3484     })(CommentDirectiveType = ts.CommentDirectiveType || (ts.CommentDirectiveType = {}));
3485     var OperationCanceledException = /** @class */ (function () {
3486         function OperationCanceledException() {
3487         }
3488         return OperationCanceledException;
3489     }());
3490     ts.OperationCanceledException = OperationCanceledException;
3491     /*@internal*/
3492     var RefFileKind;
3493     (function (RefFileKind) {
3494         RefFileKind[RefFileKind["Import"] = 0] = "Import";
3495         RefFileKind[RefFileKind["ReferenceFile"] = 1] = "ReferenceFile";
3496         RefFileKind[RefFileKind["TypeReferenceDirective"] = 2] = "TypeReferenceDirective";
3497     })(RefFileKind = ts.RefFileKind || (ts.RefFileKind = {}));
3498     /* @internal */
3499     var StructureIsReused;
3500     (function (StructureIsReused) {
3501         StructureIsReused[StructureIsReused["Not"] = 0] = "Not";
3502         StructureIsReused[StructureIsReused["SafeModules"] = 1] = "SafeModules";
3503         StructureIsReused[StructureIsReused["Completely"] = 2] = "Completely";
3504     })(StructureIsReused = ts.StructureIsReused || (ts.StructureIsReused = {}));
3505     /** Return code used by getEmitOutput function to indicate status of the function */
3506     var ExitStatus;
3507     (function (ExitStatus) {
3508         // Compiler ran successfully.  Either this was a simple do-nothing compilation (for example,
3509         // when -version or -help was provided, or this was a normal compilation, no diagnostics
3510         // were produced, and all outputs were generated successfully.
3511         ExitStatus[ExitStatus["Success"] = 0] = "Success";
3512         // Diagnostics were produced and because of them no code was generated.
3513         ExitStatus[ExitStatus["DiagnosticsPresent_OutputsSkipped"] = 1] = "DiagnosticsPresent_OutputsSkipped";
3514         // Diagnostics were produced and outputs were generated in spite of them.
3515         ExitStatus[ExitStatus["DiagnosticsPresent_OutputsGenerated"] = 2] = "DiagnosticsPresent_OutputsGenerated";
3516         // When build skipped because passed in project is invalid
3517         ExitStatus[ExitStatus["InvalidProject_OutputsSkipped"] = 3] = "InvalidProject_OutputsSkipped";
3518         // When build is skipped because project references form cycle
3519         ExitStatus[ExitStatus["ProjectReferenceCycle_OutputsSkipped"] = 4] = "ProjectReferenceCycle_OutputsSkipped";
3520         /** @deprecated Use ProjectReferenceCycle_OutputsSkipped instead. */
3521         ExitStatus[ExitStatus["ProjectReferenceCycle_OutputsSkupped"] = 4] = "ProjectReferenceCycle_OutputsSkupped";
3522     })(ExitStatus = ts.ExitStatus || (ts.ExitStatus = {}));
3523     /* @internal */
3524     var UnionReduction;
3525     (function (UnionReduction) {
3526         UnionReduction[UnionReduction["None"] = 0] = "None";
3527         UnionReduction[UnionReduction["Literal"] = 1] = "Literal";
3528         UnionReduction[UnionReduction["Subtype"] = 2] = "Subtype";
3529     })(UnionReduction = ts.UnionReduction || (ts.UnionReduction = {}));
3530     /* @internal */
3531     var ContextFlags;
3532     (function (ContextFlags) {
3533         ContextFlags[ContextFlags["None"] = 0] = "None";
3534         ContextFlags[ContextFlags["Signature"] = 1] = "Signature";
3535         ContextFlags[ContextFlags["NoConstraints"] = 2] = "NoConstraints";
3536         ContextFlags[ContextFlags["Completions"] = 4] = "Completions";
3537     })(ContextFlags = ts.ContextFlags || (ts.ContextFlags = {}));
3538     // NOTE: If modifying this enum, must modify `TypeFormatFlags` too!
3539     var NodeBuilderFlags;
3540     (function (NodeBuilderFlags) {
3541         NodeBuilderFlags[NodeBuilderFlags["None"] = 0] = "None";
3542         // Options
3543         NodeBuilderFlags[NodeBuilderFlags["NoTruncation"] = 1] = "NoTruncation";
3544         NodeBuilderFlags[NodeBuilderFlags["WriteArrayAsGenericType"] = 2] = "WriteArrayAsGenericType";
3545         NodeBuilderFlags[NodeBuilderFlags["GenerateNamesForShadowedTypeParams"] = 4] = "GenerateNamesForShadowedTypeParams";
3546         NodeBuilderFlags[NodeBuilderFlags["UseStructuralFallback"] = 8] = "UseStructuralFallback";
3547         NodeBuilderFlags[NodeBuilderFlags["ForbidIndexedAccessSymbolReferences"] = 16] = "ForbidIndexedAccessSymbolReferences";
3548         NodeBuilderFlags[NodeBuilderFlags["WriteTypeArgumentsOfSignature"] = 32] = "WriteTypeArgumentsOfSignature";
3549         NodeBuilderFlags[NodeBuilderFlags["UseFullyQualifiedType"] = 64] = "UseFullyQualifiedType";
3550         NodeBuilderFlags[NodeBuilderFlags["UseOnlyExternalAliasing"] = 128] = "UseOnlyExternalAliasing";
3551         NodeBuilderFlags[NodeBuilderFlags["SuppressAnyReturnType"] = 256] = "SuppressAnyReturnType";
3552         NodeBuilderFlags[NodeBuilderFlags["WriteTypeParametersInQualifiedName"] = 512] = "WriteTypeParametersInQualifiedName";
3553         NodeBuilderFlags[NodeBuilderFlags["MultilineObjectLiterals"] = 1024] = "MultilineObjectLiterals";
3554         NodeBuilderFlags[NodeBuilderFlags["WriteClassExpressionAsTypeLiteral"] = 2048] = "WriteClassExpressionAsTypeLiteral";
3555         NodeBuilderFlags[NodeBuilderFlags["UseTypeOfFunction"] = 4096] = "UseTypeOfFunction";
3556         NodeBuilderFlags[NodeBuilderFlags["OmitParameterModifiers"] = 8192] = "OmitParameterModifiers";
3557         NodeBuilderFlags[NodeBuilderFlags["UseAliasDefinedOutsideCurrentScope"] = 16384] = "UseAliasDefinedOutsideCurrentScope";
3558         NodeBuilderFlags[NodeBuilderFlags["UseSingleQuotesForStringLiteralType"] = 268435456] = "UseSingleQuotesForStringLiteralType";
3559         NodeBuilderFlags[NodeBuilderFlags["NoTypeReduction"] = 536870912] = "NoTypeReduction";
3560         // Error handling
3561         NodeBuilderFlags[NodeBuilderFlags["AllowThisInObjectLiteral"] = 32768] = "AllowThisInObjectLiteral";
3562         NodeBuilderFlags[NodeBuilderFlags["AllowQualifedNameInPlaceOfIdentifier"] = 65536] = "AllowQualifedNameInPlaceOfIdentifier";
3563         NodeBuilderFlags[NodeBuilderFlags["AllowAnonymousIdentifier"] = 131072] = "AllowAnonymousIdentifier";
3564         NodeBuilderFlags[NodeBuilderFlags["AllowEmptyUnionOrIntersection"] = 262144] = "AllowEmptyUnionOrIntersection";
3565         NodeBuilderFlags[NodeBuilderFlags["AllowEmptyTuple"] = 524288] = "AllowEmptyTuple";
3566         NodeBuilderFlags[NodeBuilderFlags["AllowUniqueESSymbolType"] = 1048576] = "AllowUniqueESSymbolType";
3567         NodeBuilderFlags[NodeBuilderFlags["AllowEmptyIndexInfoType"] = 2097152] = "AllowEmptyIndexInfoType";
3568         // Errors (cont.)
3569         NodeBuilderFlags[NodeBuilderFlags["AllowNodeModulesRelativePaths"] = 67108864] = "AllowNodeModulesRelativePaths";
3570         /* @internal */ NodeBuilderFlags[NodeBuilderFlags["DoNotIncludeSymbolChain"] = 134217728] = "DoNotIncludeSymbolChain";
3571         NodeBuilderFlags[NodeBuilderFlags["IgnoreErrors"] = 70221824] = "IgnoreErrors";
3572         // State
3573         NodeBuilderFlags[NodeBuilderFlags["InObjectTypeLiteral"] = 4194304] = "InObjectTypeLiteral";
3574         NodeBuilderFlags[NodeBuilderFlags["InTypeAlias"] = 8388608] = "InTypeAlias";
3575         NodeBuilderFlags[NodeBuilderFlags["InInitialEntityName"] = 16777216] = "InInitialEntityName";
3576         NodeBuilderFlags[NodeBuilderFlags["InReverseMappedType"] = 33554432] = "InReverseMappedType";
3577     })(NodeBuilderFlags = ts.NodeBuilderFlags || (ts.NodeBuilderFlags = {}));
3578     // Ensure the shared flags between this and `NodeBuilderFlags` stay in alignment
3579     var TypeFormatFlags;
3580     (function (TypeFormatFlags) {
3581         TypeFormatFlags[TypeFormatFlags["None"] = 0] = "None";
3582         TypeFormatFlags[TypeFormatFlags["NoTruncation"] = 1] = "NoTruncation";
3583         TypeFormatFlags[TypeFormatFlags["WriteArrayAsGenericType"] = 2] = "WriteArrayAsGenericType";
3584         // hole because there's a hole in node builder flags
3585         TypeFormatFlags[TypeFormatFlags["UseStructuralFallback"] = 8] = "UseStructuralFallback";
3586         // hole because there's a hole in node builder flags
3587         TypeFormatFlags[TypeFormatFlags["WriteTypeArgumentsOfSignature"] = 32] = "WriteTypeArgumentsOfSignature";
3588         TypeFormatFlags[TypeFormatFlags["UseFullyQualifiedType"] = 64] = "UseFullyQualifiedType";
3589         // hole because `UseOnlyExternalAliasing` is here in node builder flags, but functions which take old flags use `SymbolFormatFlags` instead
3590         TypeFormatFlags[TypeFormatFlags["SuppressAnyReturnType"] = 256] = "SuppressAnyReturnType";
3591         // hole because `WriteTypeParametersInQualifiedName` is here in node builder flags, but functions which take old flags use `SymbolFormatFlags` for this instead
3592         TypeFormatFlags[TypeFormatFlags["MultilineObjectLiterals"] = 1024] = "MultilineObjectLiterals";
3593         TypeFormatFlags[TypeFormatFlags["WriteClassExpressionAsTypeLiteral"] = 2048] = "WriteClassExpressionAsTypeLiteral";
3594         TypeFormatFlags[TypeFormatFlags["UseTypeOfFunction"] = 4096] = "UseTypeOfFunction";
3595         TypeFormatFlags[TypeFormatFlags["OmitParameterModifiers"] = 8192] = "OmitParameterModifiers";
3596         TypeFormatFlags[TypeFormatFlags["UseAliasDefinedOutsideCurrentScope"] = 16384] = "UseAliasDefinedOutsideCurrentScope";
3597         TypeFormatFlags[TypeFormatFlags["UseSingleQuotesForStringLiteralType"] = 268435456] = "UseSingleQuotesForStringLiteralType";
3598         TypeFormatFlags[TypeFormatFlags["NoTypeReduction"] = 536870912] = "NoTypeReduction";
3599         // Error Handling
3600         TypeFormatFlags[TypeFormatFlags["AllowUniqueESSymbolType"] = 1048576] = "AllowUniqueESSymbolType";
3601         // TypeFormatFlags exclusive
3602         TypeFormatFlags[TypeFormatFlags["AddUndefined"] = 131072] = "AddUndefined";
3603         TypeFormatFlags[TypeFormatFlags["WriteArrowStyleSignature"] = 262144] = "WriteArrowStyleSignature";
3604         // State
3605         TypeFormatFlags[TypeFormatFlags["InArrayType"] = 524288] = "InArrayType";
3606         TypeFormatFlags[TypeFormatFlags["InElementType"] = 2097152] = "InElementType";
3607         TypeFormatFlags[TypeFormatFlags["InFirstTypeArgument"] = 4194304] = "InFirstTypeArgument";
3608         TypeFormatFlags[TypeFormatFlags["InTypeAlias"] = 8388608] = "InTypeAlias";
3609         /** @deprecated */ TypeFormatFlags[TypeFormatFlags["WriteOwnNameForAnyLike"] = 0] = "WriteOwnNameForAnyLike";
3610         TypeFormatFlags[TypeFormatFlags["NodeBuilderFlagsMask"] = 814775659] = "NodeBuilderFlagsMask";
3611     })(TypeFormatFlags = ts.TypeFormatFlags || (ts.TypeFormatFlags = {}));
3612     var SymbolFormatFlags;
3613     (function (SymbolFormatFlags) {
3614         SymbolFormatFlags[SymbolFormatFlags["None"] = 0] = "None";
3615         // Write symbols's type argument if it is instantiated symbol
3616         // eg. class C<T> { p: T }   <-- Show p as C<T>.p here
3617         //     var a: C<number>;
3618         //     var p = a.p; <--- Here p is property of C<number> so show it as C<number>.p instead of just C.p
3619         SymbolFormatFlags[SymbolFormatFlags["WriteTypeParametersOrArguments"] = 1] = "WriteTypeParametersOrArguments";
3620         // Use only external alias information to get the symbol name in the given context
3621         // eg.  module m { export class c { } } import x = m.c;
3622         // When this flag is specified m.c will be used to refer to the class instead of alias symbol x
3623         SymbolFormatFlags[SymbolFormatFlags["UseOnlyExternalAliasing"] = 2] = "UseOnlyExternalAliasing";
3624         // Build symbol name using any nodes needed, instead of just components of an entity name
3625         SymbolFormatFlags[SymbolFormatFlags["AllowAnyNodeKind"] = 4] = "AllowAnyNodeKind";
3626         // Prefer aliases which are not directly visible
3627         SymbolFormatFlags[SymbolFormatFlags["UseAliasDefinedOutsideCurrentScope"] = 8] = "UseAliasDefinedOutsideCurrentScope";
3628         // Skip building an accessible symbol chain
3629         /* @internal */ SymbolFormatFlags[SymbolFormatFlags["DoNotIncludeSymbolChain"] = 16] = "DoNotIncludeSymbolChain";
3630     })(SymbolFormatFlags = ts.SymbolFormatFlags || (ts.SymbolFormatFlags = {}));
3631     /* @internal */
3632     var SymbolAccessibility;
3633     (function (SymbolAccessibility) {
3634         SymbolAccessibility[SymbolAccessibility["Accessible"] = 0] = "Accessible";
3635         SymbolAccessibility[SymbolAccessibility["NotAccessible"] = 1] = "NotAccessible";
3636         SymbolAccessibility[SymbolAccessibility["CannotBeNamed"] = 2] = "CannotBeNamed";
3637     })(SymbolAccessibility = ts.SymbolAccessibility || (ts.SymbolAccessibility = {}));
3638     /* @internal */
3639     var SyntheticSymbolKind;
3640     (function (SyntheticSymbolKind) {
3641         SyntheticSymbolKind[SyntheticSymbolKind["UnionOrIntersection"] = 0] = "UnionOrIntersection";
3642         SyntheticSymbolKind[SyntheticSymbolKind["Spread"] = 1] = "Spread";
3643     })(SyntheticSymbolKind = ts.SyntheticSymbolKind || (ts.SyntheticSymbolKind = {}));
3644     var TypePredicateKind;
3645     (function (TypePredicateKind) {
3646         TypePredicateKind[TypePredicateKind["This"] = 0] = "This";
3647         TypePredicateKind[TypePredicateKind["Identifier"] = 1] = "Identifier";
3648         TypePredicateKind[TypePredicateKind["AssertsThis"] = 2] = "AssertsThis";
3649         TypePredicateKind[TypePredicateKind["AssertsIdentifier"] = 3] = "AssertsIdentifier";
3650     })(TypePredicateKind = ts.TypePredicateKind || (ts.TypePredicateKind = {}));
3651     /** Indicates how to serialize the name for a TypeReferenceNode when emitting decorator metadata */
3652     /* @internal */
3653     var TypeReferenceSerializationKind;
3654     (function (TypeReferenceSerializationKind) {
3655         // The TypeReferenceNode could not be resolved.
3656         // The type name should be emitted using a safe fallback.
3657         TypeReferenceSerializationKind[TypeReferenceSerializationKind["Unknown"] = 0] = "Unknown";
3658         // The TypeReferenceNode resolves to a type with a constructor
3659         // function that can be reached at runtime (e.g. a `class`
3660         // declaration or a `var` declaration for the static side
3661         // of a type, such as the global `Promise` type in lib.d.ts).
3662         TypeReferenceSerializationKind[TypeReferenceSerializationKind["TypeWithConstructSignatureAndValue"] = 1] = "TypeWithConstructSignatureAndValue";
3663         // The TypeReferenceNode resolves to a Void-like, Nullable, or Never type.
3664         TypeReferenceSerializationKind[TypeReferenceSerializationKind["VoidNullableOrNeverType"] = 2] = "VoidNullableOrNeverType";
3665         // The TypeReferenceNode resolves to a Number-like type.
3666         TypeReferenceSerializationKind[TypeReferenceSerializationKind["NumberLikeType"] = 3] = "NumberLikeType";
3667         // The TypeReferenceNode resolves to a BigInt-like type.
3668         TypeReferenceSerializationKind[TypeReferenceSerializationKind["BigIntLikeType"] = 4] = "BigIntLikeType";
3669         // The TypeReferenceNode resolves to a String-like type.
3670         TypeReferenceSerializationKind[TypeReferenceSerializationKind["StringLikeType"] = 5] = "StringLikeType";
3671         // The TypeReferenceNode resolves to a Boolean-like type.
3672         TypeReferenceSerializationKind[TypeReferenceSerializationKind["BooleanType"] = 6] = "BooleanType";
3673         // The TypeReferenceNode resolves to an Array-like type.
3674         TypeReferenceSerializationKind[TypeReferenceSerializationKind["ArrayLikeType"] = 7] = "ArrayLikeType";
3675         // The TypeReferenceNode resolves to the ESSymbol type.
3676         TypeReferenceSerializationKind[TypeReferenceSerializationKind["ESSymbolType"] = 8] = "ESSymbolType";
3677         // The TypeReferenceNode resolved to the global Promise constructor symbol.
3678         TypeReferenceSerializationKind[TypeReferenceSerializationKind["Promise"] = 9] = "Promise";
3679         // The TypeReferenceNode resolves to a Function type or a type with call signatures.
3680         TypeReferenceSerializationKind[TypeReferenceSerializationKind["TypeWithCallSignature"] = 10] = "TypeWithCallSignature";
3681         // The TypeReferenceNode resolves to any other type.
3682         TypeReferenceSerializationKind[TypeReferenceSerializationKind["ObjectType"] = 11] = "ObjectType";
3683     })(TypeReferenceSerializationKind = ts.TypeReferenceSerializationKind || (ts.TypeReferenceSerializationKind = {}));
3684     var SymbolFlags;
3685     (function (SymbolFlags) {
3686         SymbolFlags[SymbolFlags["None"] = 0] = "None";
3687         SymbolFlags[SymbolFlags["FunctionScopedVariable"] = 1] = "FunctionScopedVariable";
3688         SymbolFlags[SymbolFlags["BlockScopedVariable"] = 2] = "BlockScopedVariable";
3689         SymbolFlags[SymbolFlags["Property"] = 4] = "Property";
3690         SymbolFlags[SymbolFlags["EnumMember"] = 8] = "EnumMember";
3691         SymbolFlags[SymbolFlags["Function"] = 16] = "Function";
3692         SymbolFlags[SymbolFlags["Class"] = 32] = "Class";
3693         SymbolFlags[SymbolFlags["Interface"] = 64] = "Interface";
3694         SymbolFlags[SymbolFlags["ConstEnum"] = 128] = "ConstEnum";
3695         SymbolFlags[SymbolFlags["RegularEnum"] = 256] = "RegularEnum";
3696         SymbolFlags[SymbolFlags["ValueModule"] = 512] = "ValueModule";
3697         SymbolFlags[SymbolFlags["NamespaceModule"] = 1024] = "NamespaceModule";
3698         SymbolFlags[SymbolFlags["TypeLiteral"] = 2048] = "TypeLiteral";
3699         SymbolFlags[SymbolFlags["ObjectLiteral"] = 4096] = "ObjectLiteral";
3700         SymbolFlags[SymbolFlags["Method"] = 8192] = "Method";
3701         SymbolFlags[SymbolFlags["Constructor"] = 16384] = "Constructor";
3702         SymbolFlags[SymbolFlags["GetAccessor"] = 32768] = "GetAccessor";
3703         SymbolFlags[SymbolFlags["SetAccessor"] = 65536] = "SetAccessor";
3704         SymbolFlags[SymbolFlags["Signature"] = 131072] = "Signature";
3705         SymbolFlags[SymbolFlags["TypeParameter"] = 262144] = "TypeParameter";
3706         SymbolFlags[SymbolFlags["TypeAlias"] = 524288] = "TypeAlias";
3707         SymbolFlags[SymbolFlags["ExportValue"] = 1048576] = "ExportValue";
3708         SymbolFlags[SymbolFlags["Alias"] = 2097152] = "Alias";
3709         SymbolFlags[SymbolFlags["Prototype"] = 4194304] = "Prototype";
3710         SymbolFlags[SymbolFlags["ExportStar"] = 8388608] = "ExportStar";
3711         SymbolFlags[SymbolFlags["Optional"] = 16777216] = "Optional";
3712         SymbolFlags[SymbolFlags["Transient"] = 33554432] = "Transient";
3713         SymbolFlags[SymbolFlags["Assignment"] = 67108864] = "Assignment";
3714         SymbolFlags[SymbolFlags["ModuleExports"] = 134217728] = "ModuleExports";
3715         /* @internal */
3716         SymbolFlags[SymbolFlags["All"] = 67108863] = "All";
3717         SymbolFlags[SymbolFlags["Enum"] = 384] = "Enum";
3718         SymbolFlags[SymbolFlags["Variable"] = 3] = "Variable";
3719         SymbolFlags[SymbolFlags["Value"] = 111551] = "Value";
3720         SymbolFlags[SymbolFlags["Type"] = 788968] = "Type";
3721         SymbolFlags[SymbolFlags["Namespace"] = 1920] = "Namespace";
3722         SymbolFlags[SymbolFlags["Module"] = 1536] = "Module";
3723         SymbolFlags[SymbolFlags["Accessor"] = 98304] = "Accessor";
3724         // Variables can be redeclared, but can not redeclare a block-scoped declaration with the
3725         // same name, or any other value that is not a variable, e.g. ValueModule or Class
3726         SymbolFlags[SymbolFlags["FunctionScopedVariableExcludes"] = 111550] = "FunctionScopedVariableExcludes";
3727         // Block-scoped declarations are not allowed to be re-declared
3728         // they can not merge with anything in the value space
3729         SymbolFlags[SymbolFlags["BlockScopedVariableExcludes"] = 111551] = "BlockScopedVariableExcludes";
3730         SymbolFlags[SymbolFlags["ParameterExcludes"] = 111551] = "ParameterExcludes";
3731         SymbolFlags[SymbolFlags["PropertyExcludes"] = 0] = "PropertyExcludes";
3732         SymbolFlags[SymbolFlags["EnumMemberExcludes"] = 900095] = "EnumMemberExcludes";
3733         SymbolFlags[SymbolFlags["FunctionExcludes"] = 110991] = "FunctionExcludes";
3734         SymbolFlags[SymbolFlags["ClassExcludes"] = 899503] = "ClassExcludes";
3735         SymbolFlags[SymbolFlags["InterfaceExcludes"] = 788872] = "InterfaceExcludes";
3736         SymbolFlags[SymbolFlags["RegularEnumExcludes"] = 899327] = "RegularEnumExcludes";
3737         SymbolFlags[SymbolFlags["ConstEnumExcludes"] = 899967] = "ConstEnumExcludes";
3738         SymbolFlags[SymbolFlags["ValueModuleExcludes"] = 110735] = "ValueModuleExcludes";
3739         SymbolFlags[SymbolFlags["NamespaceModuleExcludes"] = 0] = "NamespaceModuleExcludes";
3740         SymbolFlags[SymbolFlags["MethodExcludes"] = 103359] = "MethodExcludes";
3741         SymbolFlags[SymbolFlags["GetAccessorExcludes"] = 46015] = "GetAccessorExcludes";
3742         SymbolFlags[SymbolFlags["SetAccessorExcludes"] = 78783] = "SetAccessorExcludes";
3743         SymbolFlags[SymbolFlags["TypeParameterExcludes"] = 526824] = "TypeParameterExcludes";
3744         SymbolFlags[SymbolFlags["TypeAliasExcludes"] = 788968] = "TypeAliasExcludes";
3745         SymbolFlags[SymbolFlags["AliasExcludes"] = 2097152] = "AliasExcludes";
3746         SymbolFlags[SymbolFlags["ModuleMember"] = 2623475] = "ModuleMember";
3747         SymbolFlags[SymbolFlags["ExportHasLocal"] = 944] = "ExportHasLocal";
3748         SymbolFlags[SymbolFlags["BlockScoped"] = 418] = "BlockScoped";
3749         SymbolFlags[SymbolFlags["PropertyOrAccessor"] = 98308] = "PropertyOrAccessor";
3750         SymbolFlags[SymbolFlags["ClassMember"] = 106500] = "ClassMember";
3751         /* @internal */
3752         SymbolFlags[SymbolFlags["ExportSupportsDefaultModifier"] = 112] = "ExportSupportsDefaultModifier";
3753         /* @internal */
3754         SymbolFlags[SymbolFlags["ExportDoesNotSupportDefaultModifier"] = -113] = "ExportDoesNotSupportDefaultModifier";
3755         /* @internal */
3756         // The set of things we consider semantically classifiable.  Used to speed up the LS during
3757         // classification.
3758         SymbolFlags[SymbolFlags["Classifiable"] = 2885600] = "Classifiable";
3759         /* @internal */
3760         SymbolFlags[SymbolFlags["LateBindingContainer"] = 6256] = "LateBindingContainer";
3761     })(SymbolFlags = ts.SymbolFlags || (ts.SymbolFlags = {}));
3762     /* @internal */
3763     var EnumKind;
3764     (function (EnumKind) {
3765         EnumKind[EnumKind["Numeric"] = 0] = "Numeric";
3766         EnumKind[EnumKind["Literal"] = 1] = "Literal"; // Literal enum (each member has a TypeFlags.EnumLiteral type)
3767     })(EnumKind = ts.EnumKind || (ts.EnumKind = {}));
3768     /* @internal */
3769     var CheckFlags;
3770     (function (CheckFlags) {
3771         CheckFlags[CheckFlags["Instantiated"] = 1] = "Instantiated";
3772         CheckFlags[CheckFlags["SyntheticProperty"] = 2] = "SyntheticProperty";
3773         CheckFlags[CheckFlags["SyntheticMethod"] = 4] = "SyntheticMethod";
3774         CheckFlags[CheckFlags["Readonly"] = 8] = "Readonly";
3775         CheckFlags[CheckFlags["ReadPartial"] = 16] = "ReadPartial";
3776         CheckFlags[CheckFlags["WritePartial"] = 32] = "WritePartial";
3777         CheckFlags[CheckFlags["HasNonUniformType"] = 64] = "HasNonUniformType";
3778         CheckFlags[CheckFlags["HasLiteralType"] = 128] = "HasLiteralType";
3779         CheckFlags[CheckFlags["ContainsPublic"] = 256] = "ContainsPublic";
3780         CheckFlags[CheckFlags["ContainsProtected"] = 512] = "ContainsProtected";
3781         CheckFlags[CheckFlags["ContainsPrivate"] = 1024] = "ContainsPrivate";
3782         CheckFlags[CheckFlags["ContainsStatic"] = 2048] = "ContainsStatic";
3783         CheckFlags[CheckFlags["Late"] = 4096] = "Late";
3784         CheckFlags[CheckFlags["ReverseMapped"] = 8192] = "ReverseMapped";
3785         CheckFlags[CheckFlags["OptionalParameter"] = 16384] = "OptionalParameter";
3786         CheckFlags[CheckFlags["RestParameter"] = 32768] = "RestParameter";
3787         CheckFlags[CheckFlags["DeferredType"] = 65536] = "DeferredType";
3788         CheckFlags[CheckFlags["HasNeverType"] = 131072] = "HasNeverType";
3789         CheckFlags[CheckFlags["Mapped"] = 262144] = "Mapped";
3790         CheckFlags[CheckFlags["StripOptional"] = 524288] = "StripOptional";
3791         CheckFlags[CheckFlags["Synthetic"] = 6] = "Synthetic";
3792         CheckFlags[CheckFlags["Discriminant"] = 192] = "Discriminant";
3793         CheckFlags[CheckFlags["Partial"] = 48] = "Partial";
3794     })(CheckFlags = ts.CheckFlags || (ts.CheckFlags = {}));
3795     var InternalSymbolName;
3796     (function (InternalSymbolName) {
3797         InternalSymbolName["Call"] = "__call";
3798         InternalSymbolName["Constructor"] = "__constructor";
3799         InternalSymbolName["New"] = "__new";
3800         InternalSymbolName["Index"] = "__index";
3801         InternalSymbolName["ExportStar"] = "__export";
3802         InternalSymbolName["Global"] = "__global";
3803         InternalSymbolName["Missing"] = "__missing";
3804         InternalSymbolName["Type"] = "__type";
3805         InternalSymbolName["Object"] = "__object";
3806         InternalSymbolName["JSXAttributes"] = "__jsxAttributes";
3807         InternalSymbolName["Class"] = "__class";
3808         InternalSymbolName["Function"] = "__function";
3809         InternalSymbolName["Computed"] = "__computed";
3810         InternalSymbolName["Resolving"] = "__resolving__";
3811         InternalSymbolName["ExportEquals"] = "export=";
3812         InternalSymbolName["Default"] = "default";
3813         InternalSymbolName["This"] = "this";
3814     })(InternalSymbolName = ts.InternalSymbolName || (ts.InternalSymbolName = {}));
3815     /* @internal */
3816     var NodeCheckFlags;
3817     (function (NodeCheckFlags) {
3818         NodeCheckFlags[NodeCheckFlags["TypeChecked"] = 1] = "TypeChecked";
3819         NodeCheckFlags[NodeCheckFlags["LexicalThis"] = 2] = "LexicalThis";
3820         NodeCheckFlags[NodeCheckFlags["CaptureThis"] = 4] = "CaptureThis";
3821         NodeCheckFlags[NodeCheckFlags["CaptureNewTarget"] = 8] = "CaptureNewTarget";
3822         NodeCheckFlags[NodeCheckFlags["SuperInstance"] = 256] = "SuperInstance";
3823         NodeCheckFlags[NodeCheckFlags["SuperStatic"] = 512] = "SuperStatic";
3824         NodeCheckFlags[NodeCheckFlags["ContextChecked"] = 1024] = "ContextChecked";
3825         NodeCheckFlags[NodeCheckFlags["AsyncMethodWithSuper"] = 2048] = "AsyncMethodWithSuper";
3826         NodeCheckFlags[NodeCheckFlags["AsyncMethodWithSuperBinding"] = 4096] = "AsyncMethodWithSuperBinding";
3827         NodeCheckFlags[NodeCheckFlags["CaptureArguments"] = 8192] = "CaptureArguments";
3828         NodeCheckFlags[NodeCheckFlags["EnumValuesComputed"] = 16384] = "EnumValuesComputed";
3829         NodeCheckFlags[NodeCheckFlags["LexicalModuleMergesWithClass"] = 32768] = "LexicalModuleMergesWithClass";
3830         NodeCheckFlags[NodeCheckFlags["LoopWithCapturedBlockScopedBinding"] = 65536] = "LoopWithCapturedBlockScopedBinding";
3831         NodeCheckFlags[NodeCheckFlags["ContainsCapturedBlockScopeBinding"] = 131072] = "ContainsCapturedBlockScopeBinding";
3832         NodeCheckFlags[NodeCheckFlags["CapturedBlockScopedBinding"] = 262144] = "CapturedBlockScopedBinding";
3833         NodeCheckFlags[NodeCheckFlags["BlockScopedBindingInLoop"] = 524288] = "BlockScopedBindingInLoop";
3834         NodeCheckFlags[NodeCheckFlags["ClassWithBodyScopedClassBinding"] = 1048576] = "ClassWithBodyScopedClassBinding";
3835         NodeCheckFlags[NodeCheckFlags["BodyScopedClassBinding"] = 2097152] = "BodyScopedClassBinding";
3836         NodeCheckFlags[NodeCheckFlags["NeedsLoopOutParameter"] = 4194304] = "NeedsLoopOutParameter";
3837         NodeCheckFlags[NodeCheckFlags["AssignmentsMarked"] = 8388608] = "AssignmentsMarked";
3838         NodeCheckFlags[NodeCheckFlags["ClassWithConstructorReference"] = 16777216] = "ClassWithConstructorReference";
3839         NodeCheckFlags[NodeCheckFlags["ConstructorReferenceInClass"] = 33554432] = "ConstructorReferenceInClass";
3840         NodeCheckFlags[NodeCheckFlags["ContainsClassWithPrivateIdentifiers"] = 67108864] = "ContainsClassWithPrivateIdentifiers";
3841     })(NodeCheckFlags = ts.NodeCheckFlags || (ts.NodeCheckFlags = {}));
3842     var TypeFlags;
3843     (function (TypeFlags) {
3844         TypeFlags[TypeFlags["Any"] = 1] = "Any";
3845         TypeFlags[TypeFlags["Unknown"] = 2] = "Unknown";
3846         TypeFlags[TypeFlags["String"] = 4] = "String";
3847         TypeFlags[TypeFlags["Number"] = 8] = "Number";
3848         TypeFlags[TypeFlags["Boolean"] = 16] = "Boolean";
3849         TypeFlags[TypeFlags["Enum"] = 32] = "Enum";
3850         TypeFlags[TypeFlags["BigInt"] = 64] = "BigInt";
3851         TypeFlags[TypeFlags["StringLiteral"] = 128] = "StringLiteral";
3852         TypeFlags[TypeFlags["NumberLiteral"] = 256] = "NumberLiteral";
3853         TypeFlags[TypeFlags["BooleanLiteral"] = 512] = "BooleanLiteral";
3854         TypeFlags[TypeFlags["EnumLiteral"] = 1024] = "EnumLiteral";
3855         TypeFlags[TypeFlags["BigIntLiteral"] = 2048] = "BigIntLiteral";
3856         TypeFlags[TypeFlags["ESSymbol"] = 4096] = "ESSymbol";
3857         TypeFlags[TypeFlags["UniqueESSymbol"] = 8192] = "UniqueESSymbol";
3858         TypeFlags[TypeFlags["Void"] = 16384] = "Void";
3859         TypeFlags[TypeFlags["Undefined"] = 32768] = "Undefined";
3860         TypeFlags[TypeFlags["Null"] = 65536] = "Null";
3861         TypeFlags[TypeFlags["Never"] = 131072] = "Never";
3862         TypeFlags[TypeFlags["TypeParameter"] = 262144] = "TypeParameter";
3863         TypeFlags[TypeFlags["Object"] = 524288] = "Object";
3864         TypeFlags[TypeFlags["Union"] = 1048576] = "Union";
3865         TypeFlags[TypeFlags["Intersection"] = 2097152] = "Intersection";
3866         TypeFlags[TypeFlags["Index"] = 4194304] = "Index";
3867         TypeFlags[TypeFlags["IndexedAccess"] = 8388608] = "IndexedAccess";
3868         TypeFlags[TypeFlags["Conditional"] = 16777216] = "Conditional";
3869         TypeFlags[TypeFlags["Substitution"] = 33554432] = "Substitution";
3870         TypeFlags[TypeFlags["NonPrimitive"] = 67108864] = "NonPrimitive";
3871         /* @internal */
3872         TypeFlags[TypeFlags["AnyOrUnknown"] = 3] = "AnyOrUnknown";
3873         /* @internal */
3874         TypeFlags[TypeFlags["Nullable"] = 98304] = "Nullable";
3875         TypeFlags[TypeFlags["Literal"] = 2944] = "Literal";
3876         TypeFlags[TypeFlags["Unit"] = 109440] = "Unit";
3877         TypeFlags[TypeFlags["StringOrNumberLiteral"] = 384] = "StringOrNumberLiteral";
3878         /* @internal */
3879         TypeFlags[TypeFlags["StringOrNumberLiteralOrUnique"] = 8576] = "StringOrNumberLiteralOrUnique";
3880         /* @internal */
3881         TypeFlags[TypeFlags["DefinitelyFalsy"] = 117632] = "DefinitelyFalsy";
3882         TypeFlags[TypeFlags["PossiblyFalsy"] = 117724] = "PossiblyFalsy";
3883         /* @internal */
3884         TypeFlags[TypeFlags["Intrinsic"] = 67359327] = "Intrinsic";
3885         /* @internal */
3886         TypeFlags[TypeFlags["Primitive"] = 131068] = "Primitive";
3887         TypeFlags[TypeFlags["StringLike"] = 132] = "StringLike";
3888         TypeFlags[TypeFlags["NumberLike"] = 296] = "NumberLike";
3889         TypeFlags[TypeFlags["BigIntLike"] = 2112] = "BigIntLike";
3890         TypeFlags[TypeFlags["BooleanLike"] = 528] = "BooleanLike";
3891         TypeFlags[TypeFlags["EnumLike"] = 1056] = "EnumLike";
3892         TypeFlags[TypeFlags["ESSymbolLike"] = 12288] = "ESSymbolLike";
3893         TypeFlags[TypeFlags["VoidLike"] = 49152] = "VoidLike";
3894         /* @internal */
3895         TypeFlags[TypeFlags["DisjointDomains"] = 67238908] = "DisjointDomains";
3896         TypeFlags[TypeFlags["UnionOrIntersection"] = 3145728] = "UnionOrIntersection";
3897         TypeFlags[TypeFlags["StructuredType"] = 3670016] = "StructuredType";
3898         TypeFlags[TypeFlags["TypeVariable"] = 8650752] = "TypeVariable";
3899         TypeFlags[TypeFlags["InstantiableNonPrimitive"] = 58982400] = "InstantiableNonPrimitive";
3900         TypeFlags[TypeFlags["InstantiablePrimitive"] = 4194304] = "InstantiablePrimitive";
3901         TypeFlags[TypeFlags["Instantiable"] = 63176704] = "Instantiable";
3902         TypeFlags[TypeFlags["StructuredOrInstantiable"] = 66846720] = "StructuredOrInstantiable";
3903         /* @internal */
3904         TypeFlags[TypeFlags["ObjectFlagsType"] = 3899393] = "ObjectFlagsType";
3905         /* @internal */
3906         TypeFlags[TypeFlags["Simplifiable"] = 25165824] = "Simplifiable";
3907         /* @internal */
3908         TypeFlags[TypeFlags["Substructure"] = 66584576] = "Substructure";
3909         // 'Narrowable' types are types where narrowing actually narrows.
3910         // This *should* be every type other than null, undefined, void, and never
3911         TypeFlags[TypeFlags["Narrowable"] = 133970943] = "Narrowable";
3912         TypeFlags[TypeFlags["NotUnionOrUnit"] = 67637251] = "NotUnionOrUnit";
3913         /* @internal */
3914         TypeFlags[TypeFlags["NotPrimitiveUnion"] = 66994211] = "NotPrimitiveUnion";
3915         // The following flags are aggregated during union and intersection type construction
3916         /* @internal */
3917         TypeFlags[TypeFlags["IncludesMask"] = 71041023] = "IncludesMask";
3918         // The following flags are used for different purposes during union and intersection type construction
3919         /* @internal */
3920         TypeFlags[TypeFlags["IncludesStructuredOrInstantiable"] = 262144] = "IncludesStructuredOrInstantiable";
3921         /* @internal */
3922         TypeFlags[TypeFlags["IncludesNonWideningType"] = 4194304] = "IncludesNonWideningType";
3923         /* @internal */
3924         TypeFlags[TypeFlags["IncludesWildcard"] = 8388608] = "IncludesWildcard";
3925         /* @internal */
3926         TypeFlags[TypeFlags["IncludesEmptyObject"] = 16777216] = "IncludesEmptyObject";
3927     })(TypeFlags = ts.TypeFlags || (ts.TypeFlags = {}));
3928     var ObjectFlags;
3929     (function (ObjectFlags) {
3930         ObjectFlags[ObjectFlags["Class"] = 1] = "Class";
3931         ObjectFlags[ObjectFlags["Interface"] = 2] = "Interface";
3932         ObjectFlags[ObjectFlags["Reference"] = 4] = "Reference";
3933         ObjectFlags[ObjectFlags["Tuple"] = 8] = "Tuple";
3934         ObjectFlags[ObjectFlags["Anonymous"] = 16] = "Anonymous";
3935         ObjectFlags[ObjectFlags["Mapped"] = 32] = "Mapped";
3936         ObjectFlags[ObjectFlags["Instantiated"] = 64] = "Instantiated";
3937         ObjectFlags[ObjectFlags["ObjectLiteral"] = 128] = "ObjectLiteral";
3938         ObjectFlags[ObjectFlags["EvolvingArray"] = 256] = "EvolvingArray";
3939         ObjectFlags[ObjectFlags["ObjectLiteralPatternWithComputedProperties"] = 512] = "ObjectLiteralPatternWithComputedProperties";
3940         ObjectFlags[ObjectFlags["ContainsSpread"] = 1024] = "ContainsSpread";
3941         ObjectFlags[ObjectFlags["ReverseMapped"] = 2048] = "ReverseMapped";
3942         ObjectFlags[ObjectFlags["JsxAttributes"] = 4096] = "JsxAttributes";
3943         ObjectFlags[ObjectFlags["MarkerType"] = 8192] = "MarkerType";
3944         ObjectFlags[ObjectFlags["JSLiteral"] = 16384] = "JSLiteral";
3945         ObjectFlags[ObjectFlags["FreshLiteral"] = 32768] = "FreshLiteral";
3946         ObjectFlags[ObjectFlags["ArrayLiteral"] = 65536] = "ArrayLiteral";
3947         ObjectFlags[ObjectFlags["ObjectRestType"] = 131072] = "ObjectRestType";
3948         /* @internal */
3949         ObjectFlags[ObjectFlags["PrimitiveUnion"] = 262144] = "PrimitiveUnion";
3950         /* @internal */
3951         ObjectFlags[ObjectFlags["ContainsWideningType"] = 524288] = "ContainsWideningType";
3952         /* @internal */
3953         ObjectFlags[ObjectFlags["ContainsObjectOrArrayLiteral"] = 1048576] = "ContainsObjectOrArrayLiteral";
3954         /* @internal */
3955         ObjectFlags[ObjectFlags["NonInferrableType"] = 2097152] = "NonInferrableType";
3956         /* @internal */
3957         ObjectFlags[ObjectFlags["IsGenericObjectTypeComputed"] = 4194304] = "IsGenericObjectTypeComputed";
3958         /* @internal */
3959         ObjectFlags[ObjectFlags["IsGenericObjectType"] = 8388608] = "IsGenericObjectType";
3960         /* @internal */
3961         ObjectFlags[ObjectFlags["IsGenericIndexTypeComputed"] = 16777216] = "IsGenericIndexTypeComputed";
3962         /* @internal */
3963         ObjectFlags[ObjectFlags["IsGenericIndexType"] = 33554432] = "IsGenericIndexType";
3964         /* @internal */
3965         ObjectFlags[ObjectFlags["CouldContainTypeVariablesComputed"] = 67108864] = "CouldContainTypeVariablesComputed";
3966         /* @internal */
3967         ObjectFlags[ObjectFlags["CouldContainTypeVariables"] = 134217728] = "CouldContainTypeVariables";
3968         /* @internal */
3969         ObjectFlags[ObjectFlags["ContainsIntersections"] = 268435456] = "ContainsIntersections";
3970         /* @internal */
3971         ObjectFlags[ObjectFlags["IsNeverIntersectionComputed"] = 268435456] = "IsNeverIntersectionComputed";
3972         /* @internal */
3973         ObjectFlags[ObjectFlags["IsNeverIntersection"] = 536870912] = "IsNeverIntersection";
3974         ObjectFlags[ObjectFlags["ClassOrInterface"] = 3] = "ClassOrInterface";
3975         /* @internal */
3976         ObjectFlags[ObjectFlags["RequiresWidening"] = 1572864] = "RequiresWidening";
3977         /* @internal */
3978         ObjectFlags[ObjectFlags["PropagatingFlags"] = 3670016] = "PropagatingFlags";
3979     })(ObjectFlags = ts.ObjectFlags || (ts.ObjectFlags = {}));
3980     /* @internal */
3981     var VarianceFlags;
3982     (function (VarianceFlags) {
3983         VarianceFlags[VarianceFlags["Invariant"] = 0] = "Invariant";
3984         VarianceFlags[VarianceFlags["Covariant"] = 1] = "Covariant";
3985         VarianceFlags[VarianceFlags["Contravariant"] = 2] = "Contravariant";
3986         VarianceFlags[VarianceFlags["Bivariant"] = 3] = "Bivariant";
3987         VarianceFlags[VarianceFlags["Independent"] = 4] = "Independent";
3988         VarianceFlags[VarianceFlags["VarianceMask"] = 7] = "VarianceMask";
3989         VarianceFlags[VarianceFlags["Unmeasurable"] = 8] = "Unmeasurable";
3990         VarianceFlags[VarianceFlags["Unreliable"] = 16] = "Unreliable";
3991         VarianceFlags[VarianceFlags["AllowsStructuralFallback"] = 24] = "AllowsStructuralFallback";
3992     })(VarianceFlags = ts.VarianceFlags || (ts.VarianceFlags = {}));
3993     /* @internal */
3994     var JsxReferenceKind;
3995     (function (JsxReferenceKind) {
3996         JsxReferenceKind[JsxReferenceKind["Component"] = 0] = "Component";
3997         JsxReferenceKind[JsxReferenceKind["Function"] = 1] = "Function";
3998         JsxReferenceKind[JsxReferenceKind["Mixed"] = 2] = "Mixed";
3999     })(JsxReferenceKind = ts.JsxReferenceKind || (ts.JsxReferenceKind = {}));
4000     var SignatureKind;
4001     (function (SignatureKind) {
4002         SignatureKind[SignatureKind["Call"] = 0] = "Call";
4003         SignatureKind[SignatureKind["Construct"] = 1] = "Construct";
4004     })(SignatureKind = ts.SignatureKind || (ts.SignatureKind = {}));
4005     /* @internal */
4006     var SignatureFlags;
4007     (function (SignatureFlags) {
4008         SignatureFlags[SignatureFlags["None"] = 0] = "None";
4009         SignatureFlags[SignatureFlags["HasRestParameter"] = 1] = "HasRestParameter";
4010         SignatureFlags[SignatureFlags["HasLiteralTypes"] = 2] = "HasLiteralTypes";
4011         SignatureFlags[SignatureFlags["IsInnerCallChain"] = 4] = "IsInnerCallChain";
4012         SignatureFlags[SignatureFlags["IsOuterCallChain"] = 8] = "IsOuterCallChain";
4013         SignatureFlags[SignatureFlags["IsUntypedSignatureInJSFile"] = 16] = "IsUntypedSignatureInJSFile";
4014         // We do not propagate `IsInnerCallChain` to instantiated signatures, as that would result in us
4015         // attempting to add `| undefined` on each recursive call to `getReturnTypeOfSignature` when
4016         // instantiating the return type.
4017         SignatureFlags[SignatureFlags["PropagatingFlags"] = 3] = "PropagatingFlags";
4018         SignatureFlags[SignatureFlags["CallChainFlags"] = 12] = "CallChainFlags";
4019     })(SignatureFlags = ts.SignatureFlags || (ts.SignatureFlags = {}));
4020     var IndexKind;
4021     (function (IndexKind) {
4022         IndexKind[IndexKind["String"] = 0] = "String";
4023         IndexKind[IndexKind["Number"] = 1] = "Number";
4024     })(IndexKind = ts.IndexKind || (ts.IndexKind = {}));
4025     /* @internal */
4026     var TypeMapKind;
4027     (function (TypeMapKind) {
4028         TypeMapKind[TypeMapKind["Simple"] = 0] = "Simple";
4029         TypeMapKind[TypeMapKind["Array"] = 1] = "Array";
4030         TypeMapKind[TypeMapKind["Function"] = 2] = "Function";
4031         TypeMapKind[TypeMapKind["Composite"] = 3] = "Composite";
4032         TypeMapKind[TypeMapKind["Merged"] = 4] = "Merged";
4033     })(TypeMapKind = ts.TypeMapKind || (ts.TypeMapKind = {}));
4034     var InferencePriority;
4035     (function (InferencePriority) {
4036         InferencePriority[InferencePriority["NakedTypeVariable"] = 1] = "NakedTypeVariable";
4037         InferencePriority[InferencePriority["HomomorphicMappedType"] = 2] = "HomomorphicMappedType";
4038         InferencePriority[InferencePriority["PartialHomomorphicMappedType"] = 4] = "PartialHomomorphicMappedType";
4039         InferencePriority[InferencePriority["MappedTypeConstraint"] = 8] = "MappedTypeConstraint";
4040         InferencePriority[InferencePriority["ContravariantConditional"] = 16] = "ContravariantConditional";
4041         InferencePriority[InferencePriority["ReturnType"] = 32] = "ReturnType";
4042         InferencePriority[InferencePriority["LiteralKeyof"] = 64] = "LiteralKeyof";
4043         InferencePriority[InferencePriority["NoConstraints"] = 128] = "NoConstraints";
4044         InferencePriority[InferencePriority["AlwaysStrict"] = 256] = "AlwaysStrict";
4045         InferencePriority[InferencePriority["MaxValue"] = 512] = "MaxValue";
4046         InferencePriority[InferencePriority["PriorityImpliesCombination"] = 104] = "PriorityImpliesCombination";
4047         InferencePriority[InferencePriority["Circularity"] = -1] = "Circularity";
4048     })(InferencePriority = ts.InferencePriority || (ts.InferencePriority = {}));
4049     /* @internal */
4050     var InferenceFlags;
4051     (function (InferenceFlags) {
4052         InferenceFlags[InferenceFlags["None"] = 0] = "None";
4053         InferenceFlags[InferenceFlags["NoDefault"] = 1] = "NoDefault";
4054         InferenceFlags[InferenceFlags["AnyDefault"] = 2] = "AnyDefault";
4055         InferenceFlags[InferenceFlags["SkippedGenericFunction"] = 4] = "SkippedGenericFunction";
4056     })(InferenceFlags = ts.InferenceFlags || (ts.InferenceFlags = {}));
4057     /**
4058      * Ternary values are defined such that
4059      * x & y is False if either x or y is False.
4060      * x & y is Maybe if either x or y is Maybe, but neither x or y is False.
4061      * x & y is True if both x and y are True.
4062      * x | y is False if both x and y are False.
4063      * x | y is Maybe if either x or y is Maybe, but neither x or y is True.
4064      * x | y is True if either x or y is True.
4065      */
4066     /* @internal */
4067     var Ternary;
4068     (function (Ternary) {
4069         Ternary[Ternary["False"] = 0] = "False";
4070         Ternary[Ternary["Maybe"] = 1] = "Maybe";
4071         Ternary[Ternary["True"] = -1] = "True";
4072     })(Ternary = ts.Ternary || (ts.Ternary = {}));
4073     /* @internal */
4074     var AssignmentDeclarationKind;
4075     (function (AssignmentDeclarationKind) {
4076         AssignmentDeclarationKind[AssignmentDeclarationKind["None"] = 0] = "None";
4077         /// exports.name = expr
4078         AssignmentDeclarationKind[AssignmentDeclarationKind["ExportsProperty"] = 1] = "ExportsProperty";
4079         /// module.exports = expr
4080         AssignmentDeclarationKind[AssignmentDeclarationKind["ModuleExports"] = 2] = "ModuleExports";
4081         /// className.prototype.name = expr
4082         AssignmentDeclarationKind[AssignmentDeclarationKind["PrototypeProperty"] = 3] = "PrototypeProperty";
4083         /// this.name = expr
4084         AssignmentDeclarationKind[AssignmentDeclarationKind["ThisProperty"] = 4] = "ThisProperty";
4085         // F.name = expr
4086         AssignmentDeclarationKind[AssignmentDeclarationKind["Property"] = 5] = "Property";
4087         // F.prototype = { ... }
4088         AssignmentDeclarationKind[AssignmentDeclarationKind["Prototype"] = 6] = "Prototype";
4089         // Object.defineProperty(x, 'name', { value: any, writable?: boolean (false by default) });
4090         // Object.defineProperty(x, 'name', { get: Function, set: Function });
4091         // Object.defineProperty(x, 'name', { get: Function });
4092         // Object.defineProperty(x, 'name', { set: Function });
4093         AssignmentDeclarationKind[AssignmentDeclarationKind["ObjectDefinePropertyValue"] = 7] = "ObjectDefinePropertyValue";
4094         // Object.defineProperty(exports || module.exports, 'name', ...);
4095         AssignmentDeclarationKind[AssignmentDeclarationKind["ObjectDefinePropertyExports"] = 8] = "ObjectDefinePropertyExports";
4096         // Object.defineProperty(Foo.prototype, 'name', ...);
4097         AssignmentDeclarationKind[AssignmentDeclarationKind["ObjectDefinePrototypeProperty"] = 9] = "ObjectDefinePrototypeProperty";
4098     })(AssignmentDeclarationKind = ts.AssignmentDeclarationKind || (ts.AssignmentDeclarationKind = {}));
4099     var DiagnosticCategory;
4100     (function (DiagnosticCategory) {
4101         DiagnosticCategory[DiagnosticCategory["Warning"] = 0] = "Warning";
4102         DiagnosticCategory[DiagnosticCategory["Error"] = 1] = "Error";
4103         DiagnosticCategory[DiagnosticCategory["Suggestion"] = 2] = "Suggestion";
4104         DiagnosticCategory[DiagnosticCategory["Message"] = 3] = "Message";
4105     })(DiagnosticCategory = ts.DiagnosticCategory || (ts.DiagnosticCategory = {}));
4106     /* @internal */
4107     function diagnosticCategoryName(d, lowerCase) {
4108         if (lowerCase === void 0) { lowerCase = true; }
4109         var name = DiagnosticCategory[d.category];
4110         return lowerCase ? name.toLowerCase() : name;
4111     }
4112     ts.diagnosticCategoryName = diagnosticCategoryName;
4113     var ModuleResolutionKind;
4114     (function (ModuleResolutionKind) {
4115         ModuleResolutionKind[ModuleResolutionKind["Classic"] = 1] = "Classic";
4116         ModuleResolutionKind[ModuleResolutionKind["NodeJs"] = 2] = "NodeJs";
4117     })(ModuleResolutionKind = ts.ModuleResolutionKind || (ts.ModuleResolutionKind = {}));
4118     var WatchFileKind;
4119     (function (WatchFileKind) {
4120         WatchFileKind[WatchFileKind["FixedPollingInterval"] = 0] = "FixedPollingInterval";
4121         WatchFileKind[WatchFileKind["PriorityPollingInterval"] = 1] = "PriorityPollingInterval";
4122         WatchFileKind[WatchFileKind["DynamicPriorityPolling"] = 2] = "DynamicPriorityPolling";
4123         WatchFileKind[WatchFileKind["UseFsEvents"] = 3] = "UseFsEvents";
4124         WatchFileKind[WatchFileKind["UseFsEventsOnParentDirectory"] = 4] = "UseFsEventsOnParentDirectory";
4125     })(WatchFileKind = ts.WatchFileKind || (ts.WatchFileKind = {}));
4126     var WatchDirectoryKind;
4127     (function (WatchDirectoryKind) {
4128         WatchDirectoryKind[WatchDirectoryKind["UseFsEvents"] = 0] = "UseFsEvents";
4129         WatchDirectoryKind[WatchDirectoryKind["FixedPollingInterval"] = 1] = "FixedPollingInterval";
4130         WatchDirectoryKind[WatchDirectoryKind["DynamicPriorityPolling"] = 2] = "DynamicPriorityPolling";
4131     })(WatchDirectoryKind = ts.WatchDirectoryKind || (ts.WatchDirectoryKind = {}));
4132     var PollingWatchKind;
4133     (function (PollingWatchKind) {
4134         PollingWatchKind[PollingWatchKind["FixedInterval"] = 0] = "FixedInterval";
4135         PollingWatchKind[PollingWatchKind["PriorityInterval"] = 1] = "PriorityInterval";
4136         PollingWatchKind[PollingWatchKind["DynamicPriority"] = 2] = "DynamicPriority";
4137     })(PollingWatchKind = ts.PollingWatchKind || (ts.PollingWatchKind = {}));
4138     var ModuleKind;
4139     (function (ModuleKind) {
4140         ModuleKind[ModuleKind["None"] = 0] = "None";
4141         ModuleKind[ModuleKind["CommonJS"] = 1] = "CommonJS";
4142         ModuleKind[ModuleKind["AMD"] = 2] = "AMD";
4143         ModuleKind[ModuleKind["UMD"] = 3] = "UMD";
4144         ModuleKind[ModuleKind["System"] = 4] = "System";
4145         // NOTE: ES module kinds should be contiguous to more easily check whether a module kind is *any* ES module kind.
4146         //       Non-ES module kinds should not come between ES2015 (the earliest ES module kind) and ESNext (the last ES
4147         //       module kind).
4148         ModuleKind[ModuleKind["ES2015"] = 5] = "ES2015";
4149         ModuleKind[ModuleKind["ES2020"] = 6] = "ES2020";
4150         ModuleKind[ModuleKind["ESNext"] = 99] = "ESNext";
4151     })(ModuleKind = ts.ModuleKind || (ts.ModuleKind = {}));
4152     var JsxEmit;
4153     (function (JsxEmit) {
4154         JsxEmit[JsxEmit["None"] = 0] = "None";
4155         JsxEmit[JsxEmit["Preserve"] = 1] = "Preserve";
4156         JsxEmit[JsxEmit["React"] = 2] = "React";
4157         JsxEmit[JsxEmit["ReactNative"] = 3] = "ReactNative";
4158     })(JsxEmit = ts.JsxEmit || (ts.JsxEmit = {}));
4159     var ImportsNotUsedAsValues;
4160     (function (ImportsNotUsedAsValues) {
4161         ImportsNotUsedAsValues[ImportsNotUsedAsValues["Remove"] = 0] = "Remove";
4162         ImportsNotUsedAsValues[ImportsNotUsedAsValues["Preserve"] = 1] = "Preserve";
4163         ImportsNotUsedAsValues[ImportsNotUsedAsValues["Error"] = 2] = "Error";
4164     })(ImportsNotUsedAsValues = ts.ImportsNotUsedAsValues || (ts.ImportsNotUsedAsValues = {}));
4165     var NewLineKind;
4166     (function (NewLineKind) {
4167         NewLineKind[NewLineKind["CarriageReturnLineFeed"] = 0] = "CarriageReturnLineFeed";
4168         NewLineKind[NewLineKind["LineFeed"] = 1] = "LineFeed";
4169     })(NewLineKind = ts.NewLineKind || (ts.NewLineKind = {}));
4170     var ScriptKind;
4171     (function (ScriptKind) {
4172         ScriptKind[ScriptKind["Unknown"] = 0] = "Unknown";
4173         ScriptKind[ScriptKind["JS"] = 1] = "JS";
4174         ScriptKind[ScriptKind["JSX"] = 2] = "JSX";
4175         ScriptKind[ScriptKind["TS"] = 3] = "TS";
4176         ScriptKind[ScriptKind["TSX"] = 4] = "TSX";
4177         ScriptKind[ScriptKind["External"] = 5] = "External";
4178         ScriptKind[ScriptKind["JSON"] = 6] = "JSON";
4179         /**
4180          * Used on extensions that doesn't define the ScriptKind but the content defines it.
4181          * Deferred extensions are going to be included in all project contexts.
4182          */
4183         ScriptKind[ScriptKind["Deferred"] = 7] = "Deferred";
4184     })(ScriptKind = ts.ScriptKind || (ts.ScriptKind = {}));
4185     var ScriptTarget;
4186     (function (ScriptTarget) {
4187         ScriptTarget[ScriptTarget["ES3"] = 0] = "ES3";
4188         ScriptTarget[ScriptTarget["ES5"] = 1] = "ES5";
4189         ScriptTarget[ScriptTarget["ES2015"] = 2] = "ES2015";
4190         ScriptTarget[ScriptTarget["ES2016"] = 3] = "ES2016";
4191         ScriptTarget[ScriptTarget["ES2017"] = 4] = "ES2017";
4192         ScriptTarget[ScriptTarget["ES2018"] = 5] = "ES2018";
4193         ScriptTarget[ScriptTarget["ES2019"] = 6] = "ES2019";
4194         ScriptTarget[ScriptTarget["ES2020"] = 7] = "ES2020";
4195         ScriptTarget[ScriptTarget["ESNext"] = 99] = "ESNext";
4196         ScriptTarget[ScriptTarget["JSON"] = 100] = "JSON";
4197         ScriptTarget[ScriptTarget["Latest"] = 99] = "Latest";
4198     })(ScriptTarget = ts.ScriptTarget || (ts.ScriptTarget = {}));
4199     var LanguageVariant;
4200     (function (LanguageVariant) {
4201         LanguageVariant[LanguageVariant["Standard"] = 0] = "Standard";
4202         LanguageVariant[LanguageVariant["JSX"] = 1] = "JSX";
4203     })(LanguageVariant = ts.LanguageVariant || (ts.LanguageVariant = {}));
4204     var WatchDirectoryFlags;
4205     (function (WatchDirectoryFlags) {
4206         WatchDirectoryFlags[WatchDirectoryFlags["None"] = 0] = "None";
4207         WatchDirectoryFlags[WatchDirectoryFlags["Recursive"] = 1] = "Recursive";
4208     })(WatchDirectoryFlags = ts.WatchDirectoryFlags || (ts.WatchDirectoryFlags = {}));
4209     /* @internal */
4210     var CharacterCodes;
4211     (function (CharacterCodes) {
4212         CharacterCodes[CharacterCodes["nullCharacter"] = 0] = "nullCharacter";
4213         CharacterCodes[CharacterCodes["maxAsciiCharacter"] = 127] = "maxAsciiCharacter";
4214         CharacterCodes[CharacterCodes["lineFeed"] = 10] = "lineFeed";
4215         CharacterCodes[CharacterCodes["carriageReturn"] = 13] = "carriageReturn";
4216         CharacterCodes[CharacterCodes["lineSeparator"] = 8232] = "lineSeparator";
4217         CharacterCodes[CharacterCodes["paragraphSeparator"] = 8233] = "paragraphSeparator";
4218         CharacterCodes[CharacterCodes["nextLine"] = 133] = "nextLine";
4219         // Unicode 3.0 space characters
4220         CharacterCodes[CharacterCodes["space"] = 32] = "space";
4221         CharacterCodes[CharacterCodes["nonBreakingSpace"] = 160] = "nonBreakingSpace";
4222         CharacterCodes[CharacterCodes["enQuad"] = 8192] = "enQuad";
4223         CharacterCodes[CharacterCodes["emQuad"] = 8193] = "emQuad";
4224         CharacterCodes[CharacterCodes["enSpace"] = 8194] = "enSpace";
4225         CharacterCodes[CharacterCodes["emSpace"] = 8195] = "emSpace";
4226         CharacterCodes[CharacterCodes["threePerEmSpace"] = 8196] = "threePerEmSpace";
4227         CharacterCodes[CharacterCodes["fourPerEmSpace"] = 8197] = "fourPerEmSpace";
4228         CharacterCodes[CharacterCodes["sixPerEmSpace"] = 8198] = "sixPerEmSpace";
4229         CharacterCodes[CharacterCodes["figureSpace"] = 8199] = "figureSpace";
4230         CharacterCodes[CharacterCodes["punctuationSpace"] = 8200] = "punctuationSpace";
4231         CharacterCodes[CharacterCodes["thinSpace"] = 8201] = "thinSpace";
4232         CharacterCodes[CharacterCodes["hairSpace"] = 8202] = "hairSpace";
4233         CharacterCodes[CharacterCodes["zeroWidthSpace"] = 8203] = "zeroWidthSpace";
4234         CharacterCodes[CharacterCodes["narrowNoBreakSpace"] = 8239] = "narrowNoBreakSpace";
4235         CharacterCodes[CharacterCodes["ideographicSpace"] = 12288] = "ideographicSpace";
4236         CharacterCodes[CharacterCodes["mathematicalSpace"] = 8287] = "mathematicalSpace";
4237         CharacterCodes[CharacterCodes["ogham"] = 5760] = "ogham";
4238         CharacterCodes[CharacterCodes["_"] = 95] = "_";
4239         CharacterCodes[CharacterCodes["$"] = 36] = "$";
4240         CharacterCodes[CharacterCodes["_0"] = 48] = "_0";
4241         CharacterCodes[CharacterCodes["_1"] = 49] = "_1";
4242         CharacterCodes[CharacterCodes["_2"] = 50] = "_2";
4243         CharacterCodes[CharacterCodes["_3"] = 51] = "_3";
4244         CharacterCodes[CharacterCodes["_4"] = 52] = "_4";
4245         CharacterCodes[CharacterCodes["_5"] = 53] = "_5";
4246         CharacterCodes[CharacterCodes["_6"] = 54] = "_6";
4247         CharacterCodes[CharacterCodes["_7"] = 55] = "_7";
4248         CharacterCodes[CharacterCodes["_8"] = 56] = "_8";
4249         CharacterCodes[CharacterCodes["_9"] = 57] = "_9";
4250         CharacterCodes[CharacterCodes["a"] = 97] = "a";
4251         CharacterCodes[CharacterCodes["b"] = 98] = "b";
4252         CharacterCodes[CharacterCodes["c"] = 99] = "c";
4253         CharacterCodes[CharacterCodes["d"] = 100] = "d";
4254         CharacterCodes[CharacterCodes["e"] = 101] = "e";
4255         CharacterCodes[CharacterCodes["f"] = 102] = "f";
4256         CharacterCodes[CharacterCodes["g"] = 103] = "g";
4257         CharacterCodes[CharacterCodes["h"] = 104] = "h";
4258         CharacterCodes[CharacterCodes["i"] = 105] = "i";
4259         CharacterCodes[CharacterCodes["j"] = 106] = "j";
4260         CharacterCodes[CharacterCodes["k"] = 107] = "k";
4261         CharacterCodes[CharacterCodes["l"] = 108] = "l";
4262         CharacterCodes[CharacterCodes["m"] = 109] = "m";
4263         CharacterCodes[CharacterCodes["n"] = 110] = "n";
4264         CharacterCodes[CharacterCodes["o"] = 111] = "o";
4265         CharacterCodes[CharacterCodes["p"] = 112] = "p";
4266         CharacterCodes[CharacterCodes["q"] = 113] = "q";
4267         CharacterCodes[CharacterCodes["r"] = 114] = "r";
4268         CharacterCodes[CharacterCodes["s"] = 115] = "s";
4269         CharacterCodes[CharacterCodes["t"] = 116] = "t";
4270         CharacterCodes[CharacterCodes["u"] = 117] = "u";
4271         CharacterCodes[CharacterCodes["v"] = 118] = "v";
4272         CharacterCodes[CharacterCodes["w"] = 119] = "w";
4273         CharacterCodes[CharacterCodes["x"] = 120] = "x";
4274         CharacterCodes[CharacterCodes["y"] = 121] = "y";
4275         CharacterCodes[CharacterCodes["z"] = 122] = "z";
4276         CharacterCodes[CharacterCodes["A"] = 65] = "A";
4277         CharacterCodes[CharacterCodes["B"] = 66] = "B";
4278         CharacterCodes[CharacterCodes["C"] = 67] = "C";
4279         CharacterCodes[CharacterCodes["D"] = 68] = "D";
4280         CharacterCodes[CharacterCodes["E"] = 69] = "E";
4281         CharacterCodes[CharacterCodes["F"] = 70] = "F";
4282         CharacterCodes[CharacterCodes["G"] = 71] = "G";
4283         CharacterCodes[CharacterCodes["H"] = 72] = "H";
4284         CharacterCodes[CharacterCodes["I"] = 73] = "I";
4285         CharacterCodes[CharacterCodes["J"] = 74] = "J";
4286         CharacterCodes[CharacterCodes["K"] = 75] = "K";
4287         CharacterCodes[CharacterCodes["L"] = 76] = "L";
4288         CharacterCodes[CharacterCodes["M"] = 77] = "M";
4289         CharacterCodes[CharacterCodes["N"] = 78] = "N";
4290         CharacterCodes[CharacterCodes["O"] = 79] = "O";
4291         CharacterCodes[CharacterCodes["P"] = 80] = "P";
4292         CharacterCodes[CharacterCodes["Q"] = 81] = "Q";
4293         CharacterCodes[CharacterCodes["R"] = 82] = "R";
4294         CharacterCodes[CharacterCodes["S"] = 83] = "S";
4295         CharacterCodes[CharacterCodes["T"] = 84] = "T";
4296         CharacterCodes[CharacterCodes["U"] = 85] = "U";
4297         CharacterCodes[CharacterCodes["V"] = 86] = "V";
4298         CharacterCodes[CharacterCodes["W"] = 87] = "W";
4299         CharacterCodes[CharacterCodes["X"] = 88] = "X";
4300         CharacterCodes[CharacterCodes["Y"] = 89] = "Y";
4301         CharacterCodes[CharacterCodes["Z"] = 90] = "Z";
4302         CharacterCodes[CharacterCodes["ampersand"] = 38] = "ampersand";
4303         CharacterCodes[CharacterCodes["asterisk"] = 42] = "asterisk";
4304         CharacterCodes[CharacterCodes["at"] = 64] = "at";
4305         CharacterCodes[CharacterCodes["backslash"] = 92] = "backslash";
4306         CharacterCodes[CharacterCodes["backtick"] = 96] = "backtick";
4307         CharacterCodes[CharacterCodes["bar"] = 124] = "bar";
4308         CharacterCodes[CharacterCodes["caret"] = 94] = "caret";
4309         CharacterCodes[CharacterCodes["closeBrace"] = 125] = "closeBrace";
4310         CharacterCodes[CharacterCodes["closeBracket"] = 93] = "closeBracket";
4311         CharacterCodes[CharacterCodes["closeParen"] = 41] = "closeParen";
4312         CharacterCodes[CharacterCodes["colon"] = 58] = "colon";
4313         CharacterCodes[CharacterCodes["comma"] = 44] = "comma";
4314         CharacterCodes[CharacterCodes["dot"] = 46] = "dot";
4315         CharacterCodes[CharacterCodes["doubleQuote"] = 34] = "doubleQuote";
4316         CharacterCodes[CharacterCodes["equals"] = 61] = "equals";
4317         CharacterCodes[CharacterCodes["exclamation"] = 33] = "exclamation";
4318         CharacterCodes[CharacterCodes["greaterThan"] = 62] = "greaterThan";
4319         CharacterCodes[CharacterCodes["hash"] = 35] = "hash";
4320         CharacterCodes[CharacterCodes["lessThan"] = 60] = "lessThan";
4321         CharacterCodes[CharacterCodes["minus"] = 45] = "minus";
4322         CharacterCodes[CharacterCodes["openBrace"] = 123] = "openBrace";
4323         CharacterCodes[CharacterCodes["openBracket"] = 91] = "openBracket";
4324         CharacterCodes[CharacterCodes["openParen"] = 40] = "openParen";
4325         CharacterCodes[CharacterCodes["percent"] = 37] = "percent";
4326         CharacterCodes[CharacterCodes["plus"] = 43] = "plus";
4327         CharacterCodes[CharacterCodes["question"] = 63] = "question";
4328         CharacterCodes[CharacterCodes["semicolon"] = 59] = "semicolon";
4329         CharacterCodes[CharacterCodes["singleQuote"] = 39] = "singleQuote";
4330         CharacterCodes[CharacterCodes["slash"] = 47] = "slash";
4331         CharacterCodes[CharacterCodes["tilde"] = 126] = "tilde";
4332         CharacterCodes[CharacterCodes["backspace"] = 8] = "backspace";
4333         CharacterCodes[CharacterCodes["formFeed"] = 12] = "formFeed";
4334         CharacterCodes[CharacterCodes["byteOrderMark"] = 65279] = "byteOrderMark";
4335         CharacterCodes[CharacterCodes["tab"] = 9] = "tab";
4336         CharacterCodes[CharacterCodes["verticalTab"] = 11] = "verticalTab";
4337     })(CharacterCodes = ts.CharacterCodes || (ts.CharacterCodes = {}));
4338     var Extension;
4339     (function (Extension) {
4340         Extension["Ts"] = ".ts";
4341         Extension["Tsx"] = ".tsx";
4342         Extension["Dts"] = ".d.ts";
4343         Extension["Js"] = ".js";
4344         Extension["Jsx"] = ".jsx";
4345         Extension["Json"] = ".json";
4346         Extension["TsBuildInfo"] = ".tsbuildinfo";
4347     })(Extension = ts.Extension || (ts.Extension = {}));
4348     /* @internal */
4349     var TransformFlags;
4350     (function (TransformFlags) {
4351         TransformFlags[TransformFlags["None"] = 0] = "None";
4352         // Facts
4353         // - Flags used to indicate that a node or subtree contains syntax that requires transformation.
4354         TransformFlags[TransformFlags["ContainsTypeScript"] = 1] = "ContainsTypeScript";
4355         TransformFlags[TransformFlags["ContainsJsx"] = 2] = "ContainsJsx";
4356         TransformFlags[TransformFlags["ContainsESNext"] = 4] = "ContainsESNext";
4357         TransformFlags[TransformFlags["ContainsES2020"] = 8] = "ContainsES2020";
4358         TransformFlags[TransformFlags["ContainsES2019"] = 16] = "ContainsES2019";
4359         TransformFlags[TransformFlags["ContainsES2018"] = 32] = "ContainsES2018";
4360         TransformFlags[TransformFlags["ContainsES2017"] = 64] = "ContainsES2017";
4361         TransformFlags[TransformFlags["ContainsES2016"] = 128] = "ContainsES2016";
4362         TransformFlags[TransformFlags["ContainsES2015"] = 256] = "ContainsES2015";
4363         TransformFlags[TransformFlags["ContainsGenerator"] = 512] = "ContainsGenerator";
4364         TransformFlags[TransformFlags["ContainsDestructuringAssignment"] = 1024] = "ContainsDestructuringAssignment";
4365         // Markers
4366         // - Flags used to indicate that a subtree contains a specific transformation.
4367         TransformFlags[TransformFlags["ContainsTypeScriptClassSyntax"] = 2048] = "ContainsTypeScriptClassSyntax";
4368         TransformFlags[TransformFlags["ContainsLexicalThis"] = 4096] = "ContainsLexicalThis";
4369         TransformFlags[TransformFlags["ContainsRestOrSpread"] = 8192] = "ContainsRestOrSpread";
4370         TransformFlags[TransformFlags["ContainsObjectRestOrSpread"] = 16384] = "ContainsObjectRestOrSpread";
4371         TransformFlags[TransformFlags["ContainsComputedPropertyName"] = 32768] = "ContainsComputedPropertyName";
4372         TransformFlags[TransformFlags["ContainsBlockScopedBinding"] = 65536] = "ContainsBlockScopedBinding";
4373         TransformFlags[TransformFlags["ContainsBindingPattern"] = 131072] = "ContainsBindingPattern";
4374         TransformFlags[TransformFlags["ContainsYield"] = 262144] = "ContainsYield";
4375         TransformFlags[TransformFlags["ContainsAwait"] = 524288] = "ContainsAwait";
4376         TransformFlags[TransformFlags["ContainsHoistedDeclarationOrCompletion"] = 1048576] = "ContainsHoistedDeclarationOrCompletion";
4377         TransformFlags[TransformFlags["ContainsDynamicImport"] = 2097152] = "ContainsDynamicImport";
4378         TransformFlags[TransformFlags["ContainsClassFields"] = 4194304] = "ContainsClassFields";
4379         // Please leave this as 1 << 29.
4380         // It is the maximum bit we can set before we outgrow the size of a v8 small integer (SMI) on an x86 system.
4381         // It is a good reminder of how much room we have left
4382         TransformFlags[TransformFlags["HasComputedFlags"] = 536870912] = "HasComputedFlags";
4383         // Assertions
4384         // - Bitmasks that are used to assert facts about the syntax of a node and its subtree.
4385         TransformFlags[TransformFlags["AssertTypeScript"] = 1] = "AssertTypeScript";
4386         TransformFlags[TransformFlags["AssertJsx"] = 2] = "AssertJsx";
4387         TransformFlags[TransformFlags["AssertESNext"] = 4] = "AssertESNext";
4388         TransformFlags[TransformFlags["AssertES2020"] = 8] = "AssertES2020";
4389         TransformFlags[TransformFlags["AssertES2019"] = 16] = "AssertES2019";
4390         TransformFlags[TransformFlags["AssertES2018"] = 32] = "AssertES2018";
4391         TransformFlags[TransformFlags["AssertES2017"] = 64] = "AssertES2017";
4392         TransformFlags[TransformFlags["AssertES2016"] = 128] = "AssertES2016";
4393         TransformFlags[TransformFlags["AssertES2015"] = 256] = "AssertES2015";
4394         TransformFlags[TransformFlags["AssertGenerator"] = 512] = "AssertGenerator";
4395         TransformFlags[TransformFlags["AssertDestructuringAssignment"] = 1024] = "AssertDestructuringAssignment";
4396         // Scope Exclusions
4397         // - Bitmasks that exclude flags from propagating out of a specific context
4398         //   into the subtree flags of their container.
4399         TransformFlags[TransformFlags["OuterExpressionExcludes"] = 536870912] = "OuterExpressionExcludes";
4400         TransformFlags[TransformFlags["PropertyAccessExcludes"] = 536870912] = "PropertyAccessExcludes";
4401         TransformFlags[TransformFlags["NodeExcludes"] = 536870912] = "NodeExcludes";
4402         TransformFlags[TransformFlags["ArrowFunctionExcludes"] = 538920960] = "ArrowFunctionExcludes";
4403         TransformFlags[TransformFlags["FunctionExcludes"] = 538925056] = "FunctionExcludes";
4404         TransformFlags[TransformFlags["ConstructorExcludes"] = 538923008] = "ConstructorExcludes";
4405         TransformFlags[TransformFlags["MethodOrAccessorExcludes"] = 538923008] = "MethodOrAccessorExcludes";
4406         TransformFlags[TransformFlags["PropertyExcludes"] = 536875008] = "PropertyExcludes";
4407         TransformFlags[TransformFlags["ClassExcludes"] = 536905728] = "ClassExcludes";
4408         TransformFlags[TransformFlags["ModuleExcludes"] = 537991168] = "ModuleExcludes";
4409         TransformFlags[TransformFlags["TypeExcludes"] = -2] = "TypeExcludes";
4410         TransformFlags[TransformFlags["ObjectLiteralExcludes"] = 536922112] = "ObjectLiteralExcludes";
4411         TransformFlags[TransformFlags["ArrayLiteralOrCallOrNewExcludes"] = 536879104] = "ArrayLiteralOrCallOrNewExcludes";
4412         TransformFlags[TransformFlags["VariableDeclarationListExcludes"] = 537018368] = "VariableDeclarationListExcludes";
4413         TransformFlags[TransformFlags["ParameterExcludes"] = 536870912] = "ParameterExcludes";
4414         TransformFlags[TransformFlags["CatchClauseExcludes"] = 536887296] = "CatchClauseExcludes";
4415         TransformFlags[TransformFlags["BindingPatternExcludes"] = 536879104] = "BindingPatternExcludes";
4416         // Propagating flags
4417         // - Bitmasks for flags that should propagate from a child
4418         TransformFlags[TransformFlags["PropertyNamePropagatingFlags"] = 4096] = "PropertyNamePropagatingFlags";
4419         // Masks
4420         // - Additional bitmasks
4421     })(TransformFlags = ts.TransformFlags || (ts.TransformFlags = {}));
4422     var EmitFlags;
4423     (function (EmitFlags) {
4424         EmitFlags[EmitFlags["None"] = 0] = "None";
4425         EmitFlags[EmitFlags["SingleLine"] = 1] = "SingleLine";
4426         EmitFlags[EmitFlags["AdviseOnEmitNode"] = 2] = "AdviseOnEmitNode";
4427         EmitFlags[EmitFlags["NoSubstitution"] = 4] = "NoSubstitution";
4428         EmitFlags[EmitFlags["CapturesThis"] = 8] = "CapturesThis";
4429         EmitFlags[EmitFlags["NoLeadingSourceMap"] = 16] = "NoLeadingSourceMap";
4430         EmitFlags[EmitFlags["NoTrailingSourceMap"] = 32] = "NoTrailingSourceMap";
4431         EmitFlags[EmitFlags["NoSourceMap"] = 48] = "NoSourceMap";
4432         EmitFlags[EmitFlags["NoNestedSourceMaps"] = 64] = "NoNestedSourceMaps";
4433         EmitFlags[EmitFlags["NoTokenLeadingSourceMaps"] = 128] = "NoTokenLeadingSourceMaps";
4434         EmitFlags[EmitFlags["NoTokenTrailingSourceMaps"] = 256] = "NoTokenTrailingSourceMaps";
4435         EmitFlags[EmitFlags["NoTokenSourceMaps"] = 384] = "NoTokenSourceMaps";
4436         EmitFlags[EmitFlags["NoLeadingComments"] = 512] = "NoLeadingComments";
4437         EmitFlags[EmitFlags["NoTrailingComments"] = 1024] = "NoTrailingComments";
4438         EmitFlags[EmitFlags["NoComments"] = 1536] = "NoComments";
4439         EmitFlags[EmitFlags["NoNestedComments"] = 2048] = "NoNestedComments";
4440         EmitFlags[EmitFlags["HelperName"] = 4096] = "HelperName";
4441         EmitFlags[EmitFlags["ExportName"] = 8192] = "ExportName";
4442         EmitFlags[EmitFlags["LocalName"] = 16384] = "LocalName";
4443         EmitFlags[EmitFlags["InternalName"] = 32768] = "InternalName";
4444         EmitFlags[EmitFlags["Indented"] = 65536] = "Indented";
4445         EmitFlags[EmitFlags["NoIndentation"] = 131072] = "NoIndentation";
4446         EmitFlags[EmitFlags["AsyncFunctionBody"] = 262144] = "AsyncFunctionBody";
4447         EmitFlags[EmitFlags["ReuseTempVariableScope"] = 524288] = "ReuseTempVariableScope";
4448         EmitFlags[EmitFlags["CustomPrologue"] = 1048576] = "CustomPrologue";
4449         EmitFlags[EmitFlags["NoHoisting"] = 2097152] = "NoHoisting";
4450         EmitFlags[EmitFlags["HasEndOfDeclarationMarker"] = 4194304] = "HasEndOfDeclarationMarker";
4451         EmitFlags[EmitFlags["Iterator"] = 8388608] = "Iterator";
4452         EmitFlags[EmitFlags["NoAsciiEscaping"] = 16777216] = "NoAsciiEscaping";
4453         /*@internal*/ EmitFlags[EmitFlags["TypeScriptClassWrapper"] = 33554432] = "TypeScriptClassWrapper";
4454         /*@internal*/ EmitFlags[EmitFlags["NeverApplyImportHelper"] = 67108864] = "NeverApplyImportHelper";
4455         /*@internal*/ EmitFlags[EmitFlags["IgnoreSourceNewlines"] = 134217728] = "IgnoreSourceNewlines";
4456     })(EmitFlags = ts.EmitFlags || (ts.EmitFlags = {}));
4457     /**
4458      * Used by the checker, this enum keeps track of external emit helpers that should be type
4459      * checked.
4460      */
4461     /* @internal */
4462     var ExternalEmitHelpers;
4463     (function (ExternalEmitHelpers) {
4464         ExternalEmitHelpers[ExternalEmitHelpers["Extends"] = 1] = "Extends";
4465         ExternalEmitHelpers[ExternalEmitHelpers["Assign"] = 2] = "Assign";
4466         ExternalEmitHelpers[ExternalEmitHelpers["Rest"] = 4] = "Rest";
4467         ExternalEmitHelpers[ExternalEmitHelpers["Decorate"] = 8] = "Decorate";
4468         ExternalEmitHelpers[ExternalEmitHelpers["Metadata"] = 16] = "Metadata";
4469         ExternalEmitHelpers[ExternalEmitHelpers["Param"] = 32] = "Param";
4470         ExternalEmitHelpers[ExternalEmitHelpers["Awaiter"] = 64] = "Awaiter";
4471         ExternalEmitHelpers[ExternalEmitHelpers["Generator"] = 128] = "Generator";
4472         ExternalEmitHelpers[ExternalEmitHelpers["Values"] = 256] = "Values";
4473         ExternalEmitHelpers[ExternalEmitHelpers["Read"] = 512] = "Read";
4474         ExternalEmitHelpers[ExternalEmitHelpers["Spread"] = 1024] = "Spread";
4475         ExternalEmitHelpers[ExternalEmitHelpers["SpreadArrays"] = 2048] = "SpreadArrays";
4476         ExternalEmitHelpers[ExternalEmitHelpers["Await"] = 4096] = "Await";
4477         ExternalEmitHelpers[ExternalEmitHelpers["AsyncGenerator"] = 8192] = "AsyncGenerator";
4478         ExternalEmitHelpers[ExternalEmitHelpers["AsyncDelegator"] = 16384] = "AsyncDelegator";
4479         ExternalEmitHelpers[ExternalEmitHelpers["AsyncValues"] = 32768] = "AsyncValues";
4480         ExternalEmitHelpers[ExternalEmitHelpers["ExportStar"] = 65536] = "ExportStar";
4481         ExternalEmitHelpers[ExternalEmitHelpers["MakeTemplateObject"] = 131072] = "MakeTemplateObject";
4482         ExternalEmitHelpers[ExternalEmitHelpers["ClassPrivateFieldGet"] = 262144] = "ClassPrivateFieldGet";
4483         ExternalEmitHelpers[ExternalEmitHelpers["ClassPrivateFieldSet"] = 524288] = "ClassPrivateFieldSet";
4484         ExternalEmitHelpers[ExternalEmitHelpers["CreateBinding"] = 1048576] = "CreateBinding";
4485         ExternalEmitHelpers[ExternalEmitHelpers["FirstEmitHelper"] = 1] = "FirstEmitHelper";
4486         ExternalEmitHelpers[ExternalEmitHelpers["LastEmitHelper"] = 1048576] = "LastEmitHelper";
4487         // Helpers included by ES2015 for..of
4488         ExternalEmitHelpers[ExternalEmitHelpers["ForOfIncludes"] = 256] = "ForOfIncludes";
4489         // Helpers included by ES2017 for..await..of
4490         ExternalEmitHelpers[ExternalEmitHelpers["ForAwaitOfIncludes"] = 32768] = "ForAwaitOfIncludes";
4491         // Helpers included by ES2017 async generators
4492         ExternalEmitHelpers[ExternalEmitHelpers["AsyncGeneratorIncludes"] = 12288] = "AsyncGeneratorIncludes";
4493         // Helpers included by yield* in ES2017 async generators
4494         ExternalEmitHelpers[ExternalEmitHelpers["AsyncDelegatorIncludes"] = 53248] = "AsyncDelegatorIncludes";
4495         // Helpers included by ES2015 spread
4496         ExternalEmitHelpers[ExternalEmitHelpers["SpreadIncludes"] = 1536] = "SpreadIncludes";
4497     })(ExternalEmitHelpers = ts.ExternalEmitHelpers || (ts.ExternalEmitHelpers = {}));
4498     var EmitHint;
4499     (function (EmitHint) {
4500         EmitHint[EmitHint["SourceFile"] = 0] = "SourceFile";
4501         EmitHint[EmitHint["Expression"] = 1] = "Expression";
4502         EmitHint[EmitHint["IdentifierName"] = 2] = "IdentifierName";
4503         EmitHint[EmitHint["MappedTypeParameter"] = 3] = "MappedTypeParameter";
4504         EmitHint[EmitHint["Unspecified"] = 4] = "Unspecified";
4505         EmitHint[EmitHint["EmbeddedStatement"] = 5] = "EmbeddedStatement";
4506         EmitHint[EmitHint["JsxAttributeValue"] = 6] = "JsxAttributeValue";
4507     })(EmitHint = ts.EmitHint || (ts.EmitHint = {}));
4508     /* @internal */
4509     var LexicalEnvironmentFlags;
4510     (function (LexicalEnvironmentFlags) {
4511         LexicalEnvironmentFlags[LexicalEnvironmentFlags["None"] = 0] = "None";
4512         LexicalEnvironmentFlags[LexicalEnvironmentFlags["InParameters"] = 1] = "InParameters";
4513         LexicalEnvironmentFlags[LexicalEnvironmentFlags["VariablesHoistedInParameters"] = 2] = "VariablesHoistedInParameters"; // a temp variable was hoisted while visiting a parameter list
4514     })(LexicalEnvironmentFlags = ts.LexicalEnvironmentFlags || (ts.LexicalEnvironmentFlags = {}));
4515     /*@internal*/
4516     var BundleFileSectionKind;
4517     (function (BundleFileSectionKind) {
4518         BundleFileSectionKind["Prologue"] = "prologue";
4519         BundleFileSectionKind["EmitHelpers"] = "emitHelpers";
4520         BundleFileSectionKind["NoDefaultLib"] = "no-default-lib";
4521         BundleFileSectionKind["Reference"] = "reference";
4522         BundleFileSectionKind["Type"] = "type";
4523         BundleFileSectionKind["Lib"] = "lib";
4524         BundleFileSectionKind["Prepend"] = "prepend";
4525         BundleFileSectionKind["Text"] = "text";
4526         BundleFileSectionKind["Internal"] = "internal";
4527         // comments?
4528     })(BundleFileSectionKind = ts.BundleFileSectionKind || (ts.BundleFileSectionKind = {}));
4529     var ListFormat;
4530     (function (ListFormat) {
4531         ListFormat[ListFormat["None"] = 0] = "None";
4532         // Line separators
4533         ListFormat[ListFormat["SingleLine"] = 0] = "SingleLine";
4534         ListFormat[ListFormat["MultiLine"] = 1] = "MultiLine";
4535         ListFormat[ListFormat["PreserveLines"] = 2] = "PreserveLines";
4536         ListFormat[ListFormat["LinesMask"] = 3] = "LinesMask";
4537         // Delimiters
4538         ListFormat[ListFormat["NotDelimited"] = 0] = "NotDelimited";
4539         ListFormat[ListFormat["BarDelimited"] = 4] = "BarDelimited";
4540         ListFormat[ListFormat["AmpersandDelimited"] = 8] = "AmpersandDelimited";
4541         ListFormat[ListFormat["CommaDelimited"] = 16] = "CommaDelimited";
4542         ListFormat[ListFormat["AsteriskDelimited"] = 32] = "AsteriskDelimited";
4543         ListFormat[ListFormat["DelimitersMask"] = 60] = "DelimitersMask";
4544         ListFormat[ListFormat["AllowTrailingComma"] = 64] = "AllowTrailingComma";
4545         // Whitespace
4546         ListFormat[ListFormat["Indented"] = 128] = "Indented";
4547         ListFormat[ListFormat["SpaceBetweenBraces"] = 256] = "SpaceBetweenBraces";
4548         ListFormat[ListFormat["SpaceBetweenSiblings"] = 512] = "SpaceBetweenSiblings";
4549         // Brackets/Braces
4550         ListFormat[ListFormat["Braces"] = 1024] = "Braces";
4551         ListFormat[ListFormat["Parenthesis"] = 2048] = "Parenthesis";
4552         ListFormat[ListFormat["AngleBrackets"] = 4096] = "AngleBrackets";
4553         ListFormat[ListFormat["SquareBrackets"] = 8192] = "SquareBrackets";
4554         ListFormat[ListFormat["BracketsMask"] = 15360] = "BracketsMask";
4555         ListFormat[ListFormat["OptionalIfUndefined"] = 16384] = "OptionalIfUndefined";
4556         ListFormat[ListFormat["OptionalIfEmpty"] = 32768] = "OptionalIfEmpty";
4557         ListFormat[ListFormat["Optional"] = 49152] = "Optional";
4558         // Other
4559         ListFormat[ListFormat["PreferNewLine"] = 65536] = "PreferNewLine";
4560         ListFormat[ListFormat["NoTrailingNewLine"] = 131072] = "NoTrailingNewLine";
4561         ListFormat[ListFormat["NoInterveningComments"] = 262144] = "NoInterveningComments";
4562         ListFormat[ListFormat["NoSpaceIfEmpty"] = 524288] = "NoSpaceIfEmpty";
4563         ListFormat[ListFormat["SingleElement"] = 1048576] = "SingleElement";
4564         ListFormat[ListFormat["SpaceAfterList"] = 2097152] = "SpaceAfterList";
4565         // Precomputed Formats
4566         ListFormat[ListFormat["Modifiers"] = 262656] = "Modifiers";
4567         ListFormat[ListFormat["HeritageClauses"] = 512] = "HeritageClauses";
4568         ListFormat[ListFormat["SingleLineTypeLiteralMembers"] = 768] = "SingleLineTypeLiteralMembers";
4569         ListFormat[ListFormat["MultiLineTypeLiteralMembers"] = 32897] = "MultiLineTypeLiteralMembers";
4570         ListFormat[ListFormat["TupleTypeElements"] = 528] = "TupleTypeElements";
4571         ListFormat[ListFormat["UnionTypeConstituents"] = 516] = "UnionTypeConstituents";
4572         ListFormat[ListFormat["IntersectionTypeConstituents"] = 520] = "IntersectionTypeConstituents";
4573         ListFormat[ListFormat["ObjectBindingPatternElements"] = 525136] = "ObjectBindingPatternElements";
4574         ListFormat[ListFormat["ArrayBindingPatternElements"] = 524880] = "ArrayBindingPatternElements";
4575         ListFormat[ListFormat["ObjectLiteralExpressionProperties"] = 526226] = "ObjectLiteralExpressionProperties";
4576         ListFormat[ListFormat["ArrayLiteralExpressionElements"] = 8914] = "ArrayLiteralExpressionElements";
4577         ListFormat[ListFormat["CommaListElements"] = 528] = "CommaListElements";
4578         ListFormat[ListFormat["CallExpressionArguments"] = 2576] = "CallExpressionArguments";
4579         ListFormat[ListFormat["NewExpressionArguments"] = 18960] = "NewExpressionArguments";
4580         ListFormat[ListFormat["TemplateExpressionSpans"] = 262144] = "TemplateExpressionSpans";
4581         ListFormat[ListFormat["SingleLineBlockStatements"] = 768] = "SingleLineBlockStatements";
4582         ListFormat[ListFormat["MultiLineBlockStatements"] = 129] = "MultiLineBlockStatements";
4583         ListFormat[ListFormat["VariableDeclarationList"] = 528] = "VariableDeclarationList";
4584         ListFormat[ListFormat["SingleLineFunctionBodyStatements"] = 768] = "SingleLineFunctionBodyStatements";
4585         ListFormat[ListFormat["MultiLineFunctionBodyStatements"] = 1] = "MultiLineFunctionBodyStatements";
4586         ListFormat[ListFormat["ClassHeritageClauses"] = 0] = "ClassHeritageClauses";
4587         ListFormat[ListFormat["ClassMembers"] = 129] = "ClassMembers";
4588         ListFormat[ListFormat["InterfaceMembers"] = 129] = "InterfaceMembers";
4589         ListFormat[ListFormat["EnumMembers"] = 145] = "EnumMembers";
4590         ListFormat[ListFormat["CaseBlockClauses"] = 129] = "CaseBlockClauses";
4591         ListFormat[ListFormat["NamedImportsOrExportsElements"] = 525136] = "NamedImportsOrExportsElements";
4592         ListFormat[ListFormat["JsxElementOrFragmentChildren"] = 262144] = "JsxElementOrFragmentChildren";
4593         ListFormat[ListFormat["JsxElementAttributes"] = 262656] = "JsxElementAttributes";
4594         ListFormat[ListFormat["CaseOrDefaultClauseStatements"] = 163969] = "CaseOrDefaultClauseStatements";
4595         ListFormat[ListFormat["HeritageClauseTypes"] = 528] = "HeritageClauseTypes";
4596         ListFormat[ListFormat["SourceFileStatements"] = 131073] = "SourceFileStatements";
4597         ListFormat[ListFormat["Decorators"] = 2146305] = "Decorators";
4598         ListFormat[ListFormat["TypeArguments"] = 53776] = "TypeArguments";
4599         ListFormat[ListFormat["TypeParameters"] = 53776] = "TypeParameters";
4600         ListFormat[ListFormat["Parameters"] = 2576] = "Parameters";
4601         ListFormat[ListFormat["IndexSignatureParameters"] = 8848] = "IndexSignatureParameters";
4602         ListFormat[ListFormat["JSDocComment"] = 33] = "JSDocComment";
4603     })(ListFormat = ts.ListFormat || (ts.ListFormat = {}));
4604     /* @internal */
4605     var PragmaKindFlags;
4606     (function (PragmaKindFlags) {
4607         PragmaKindFlags[PragmaKindFlags["None"] = 0] = "None";
4608         /**
4609          * Triple slash comment of the form
4610          * /// <pragma-name argname="value" />
4611          */
4612         PragmaKindFlags[PragmaKindFlags["TripleSlashXML"] = 1] = "TripleSlashXML";
4613         /**
4614          * Single line comment of the form
4615          * // @pragma-name argval1 argval2
4616          * or
4617          * /// @pragma-name argval1 argval2
4618          */
4619         PragmaKindFlags[PragmaKindFlags["SingleLine"] = 2] = "SingleLine";
4620         /**
4621          * Multiline non-jsdoc pragma of the form
4622          * /* @pragma-name argval1 argval2 * /
4623          */
4624         PragmaKindFlags[PragmaKindFlags["MultiLine"] = 4] = "MultiLine";
4625         PragmaKindFlags[PragmaKindFlags["All"] = 7] = "All";
4626         PragmaKindFlags[PragmaKindFlags["Default"] = 7] = "Default";
4627     })(PragmaKindFlags = ts.PragmaKindFlags || (ts.PragmaKindFlags = {}));
4628     // While not strictly a type, this is here because `PragmaMap` needs to be here to be used with `SourceFile`, and we don't
4629     //  fancy effectively defining it twice, once in value-space and once in type-space
4630     /* @internal */
4631     ts.commentPragmas = {
4632         "reference": {
4633             args: [
4634                 { name: "types", optional: true, captureSpan: true },
4635                 { name: "lib", optional: true, captureSpan: true },
4636                 { name: "path", optional: true, captureSpan: true },
4637                 { name: "no-default-lib", optional: true }
4638             ],
4639             kind: 1 /* TripleSlashXML */
4640         },
4641         "amd-dependency": {
4642             args: [{ name: "path" }, { name: "name", optional: true }],
4643             kind: 1 /* TripleSlashXML */
4644         },
4645         "amd-module": {
4646             args: [{ name: "name" }],
4647             kind: 1 /* TripleSlashXML */
4648         },
4649         "ts-check": {
4650             kind: 2 /* SingleLine */
4651         },
4652         "ts-nocheck": {
4653             kind: 2 /* SingleLine */
4654         },
4655         "jsx": {
4656             args: [{ name: "factory" }],
4657             kind: 4 /* MultiLine */
4658         },
4659     };
4660 })(ts || (ts = {}));
4661 var ts;
4662 (function (ts) {
4663     /**
4664      * djb2 hashing algorithm
4665      * http://www.cse.yorku.ca/~oz/hash.html
4666      */
4667     /* @internal */
4668     function generateDjb2Hash(data) {
4669         var acc = 5381;
4670         for (var i = 0; i < data.length; i++) {
4671             acc = ((acc << 5) + acc) + data.charCodeAt(i);
4672         }
4673         return acc.toString();
4674     }
4675     ts.generateDjb2Hash = generateDjb2Hash;
4676     /**
4677      * Set a high stack trace limit to provide more information in case of an error.
4678      * Called for command-line and server use cases.
4679      * Not called if TypeScript is used as a library.
4680      */
4681     /* @internal */
4682     function setStackTraceLimit() {
4683         if (Error.stackTraceLimit < 100) { // Also tests that we won't set the property if it doesn't exist.
4684             Error.stackTraceLimit = 100;
4685         }
4686     }
4687     ts.setStackTraceLimit = setStackTraceLimit;
4688     var FileWatcherEventKind;
4689     (function (FileWatcherEventKind) {
4690         FileWatcherEventKind[FileWatcherEventKind["Created"] = 0] = "Created";
4691         FileWatcherEventKind[FileWatcherEventKind["Changed"] = 1] = "Changed";
4692         FileWatcherEventKind[FileWatcherEventKind["Deleted"] = 2] = "Deleted";
4693     })(FileWatcherEventKind = ts.FileWatcherEventKind || (ts.FileWatcherEventKind = {}));
4694     /* @internal */
4695     var PollingInterval;
4696     (function (PollingInterval) {
4697         PollingInterval[PollingInterval["High"] = 2000] = "High";
4698         PollingInterval[PollingInterval["Medium"] = 500] = "Medium";
4699         PollingInterval[PollingInterval["Low"] = 250] = "Low";
4700     })(PollingInterval = ts.PollingInterval || (ts.PollingInterval = {}));
4701     /* @internal */
4702     ts.missingFileModifiedTime = new Date(0); // Any subsequent modification will occur after this time
4703     function createPollingIntervalBasedLevels(levels) {
4704         var _a;
4705         return _a = {},
4706             _a[PollingInterval.Low] = levels.Low,
4707             _a[PollingInterval.Medium] = levels.Medium,
4708             _a[PollingInterval.High] = levels.High,
4709             _a;
4710     }
4711     var defaultChunkLevels = { Low: 32, Medium: 64, High: 256 };
4712     var pollingChunkSize = createPollingIntervalBasedLevels(defaultChunkLevels);
4713     /* @internal */
4714     ts.unchangedPollThresholds = createPollingIntervalBasedLevels(defaultChunkLevels);
4715     /* @internal */
4716     function setCustomPollingValues(system) {
4717         if (!system.getEnvironmentVariable) {
4718             return;
4719         }
4720         var pollingIntervalChanged = setCustomLevels("TSC_WATCH_POLLINGINTERVAL", PollingInterval);
4721         pollingChunkSize = getCustomPollingBasedLevels("TSC_WATCH_POLLINGCHUNKSIZE", defaultChunkLevels) || pollingChunkSize;
4722         ts.unchangedPollThresholds = getCustomPollingBasedLevels("TSC_WATCH_UNCHANGEDPOLLTHRESHOLDS", defaultChunkLevels) || ts.unchangedPollThresholds;
4723         function getLevel(envVar, level) {
4724             return system.getEnvironmentVariable(envVar + "_" + level.toUpperCase());
4725         }
4726         function getCustomLevels(baseVariable) {
4727             var customLevels;
4728             setCustomLevel("Low");
4729             setCustomLevel("Medium");
4730             setCustomLevel("High");
4731             return customLevels;
4732             function setCustomLevel(level) {
4733                 var customLevel = getLevel(baseVariable, level);
4734                 if (customLevel) {
4735                     (customLevels || (customLevels = {}))[level] = Number(customLevel);
4736                 }
4737             }
4738         }
4739         function setCustomLevels(baseVariable, levels) {
4740             var customLevels = getCustomLevels(baseVariable);
4741             if (customLevels) {
4742                 setLevel("Low");
4743                 setLevel("Medium");
4744                 setLevel("High");
4745                 return true;
4746             }
4747             return false;
4748             function setLevel(level) {
4749                 levels[level] = customLevels[level] || levels[level];
4750             }
4751         }
4752         function getCustomPollingBasedLevels(baseVariable, defaultLevels) {
4753             var customLevels = getCustomLevels(baseVariable);
4754             return (pollingIntervalChanged || customLevels) &&
4755                 createPollingIntervalBasedLevels(customLevels ? __assign(__assign({}, defaultLevels), customLevels) : defaultLevels);
4756         }
4757     }
4758     ts.setCustomPollingValues = setCustomPollingValues;
4759     /* @internal */
4760     function createDynamicPriorityPollingWatchFile(host) {
4761         var watchedFiles = [];
4762         var changedFilesInLastPoll = [];
4763         var lowPollingIntervalQueue = createPollingIntervalQueue(PollingInterval.Low);
4764         var mediumPollingIntervalQueue = createPollingIntervalQueue(PollingInterval.Medium);
4765         var highPollingIntervalQueue = createPollingIntervalQueue(PollingInterval.High);
4766         return watchFile;
4767         function watchFile(fileName, callback, defaultPollingInterval) {
4768             var file = {
4769                 fileName: fileName,
4770                 callback: callback,
4771                 unchangedPolls: 0,
4772                 mtime: getModifiedTime(fileName)
4773             };
4774             watchedFiles.push(file);
4775             addToPollingIntervalQueue(file, defaultPollingInterval);
4776             return {
4777                 close: function () {
4778                     file.isClosed = true;
4779                     // Remove from watchedFiles
4780                     ts.unorderedRemoveItem(watchedFiles, file);
4781                     // Do not update polling interval queue since that will happen as part of polling
4782                 }
4783             };
4784         }
4785         function createPollingIntervalQueue(pollingInterval) {
4786             var queue = [];
4787             queue.pollingInterval = pollingInterval;
4788             queue.pollIndex = 0;
4789             queue.pollScheduled = false;
4790             return queue;
4791         }
4792         function pollPollingIntervalQueue(queue) {
4793             queue.pollIndex = pollQueue(queue, queue.pollingInterval, queue.pollIndex, pollingChunkSize[queue.pollingInterval]);
4794             // Set the next polling index and timeout
4795             if (queue.length) {
4796                 scheduleNextPoll(queue.pollingInterval);
4797             }
4798             else {
4799                 ts.Debug.assert(queue.pollIndex === 0);
4800                 queue.pollScheduled = false;
4801             }
4802         }
4803         function pollLowPollingIntervalQueue(queue) {
4804             // Always poll complete list of changedFilesInLastPoll
4805             pollQueue(changedFilesInLastPoll, PollingInterval.Low, /*pollIndex*/ 0, changedFilesInLastPoll.length);
4806             // Finally do the actual polling of the queue
4807             pollPollingIntervalQueue(queue);
4808             // Schedule poll if there are files in changedFilesInLastPoll but no files in the actual queue
4809             // as pollPollingIntervalQueue wont schedule for next poll
4810             if (!queue.pollScheduled && changedFilesInLastPoll.length) {
4811                 scheduleNextPoll(PollingInterval.Low);
4812             }
4813         }
4814         function pollQueue(queue, pollingInterval, pollIndex, chunkSize) {
4815             // Max visit would be all elements of the queue
4816             var needsVisit = queue.length;
4817             var definedValueCopyToIndex = pollIndex;
4818             for (var polled = 0; polled < chunkSize && needsVisit > 0; nextPollIndex(), needsVisit--) {
4819                 var watchedFile = queue[pollIndex];
4820                 if (!watchedFile) {
4821                     continue;
4822                 }
4823                 else if (watchedFile.isClosed) {
4824                     queue[pollIndex] = undefined;
4825                     continue;
4826                 }
4827                 polled++;
4828                 var fileChanged = onWatchedFileStat(watchedFile, getModifiedTime(watchedFile.fileName));
4829                 if (watchedFile.isClosed) {
4830                     // Closed watcher as part of callback
4831                     queue[pollIndex] = undefined;
4832                 }
4833                 else if (fileChanged) {
4834                     watchedFile.unchangedPolls = 0;
4835                     // Changed files go to changedFilesInLastPoll queue
4836                     if (queue !== changedFilesInLastPoll) {
4837                         queue[pollIndex] = undefined;
4838                         addChangedFileToLowPollingIntervalQueue(watchedFile);
4839                     }
4840                 }
4841                 else if (watchedFile.unchangedPolls !== ts.unchangedPollThresholds[pollingInterval]) {
4842                     watchedFile.unchangedPolls++;
4843                 }
4844                 else if (queue === changedFilesInLastPoll) {
4845                     // Restart unchangedPollCount for unchanged file and move to low polling interval queue
4846                     watchedFile.unchangedPolls = 1;
4847                     queue[pollIndex] = undefined;
4848                     addToPollingIntervalQueue(watchedFile, PollingInterval.Low);
4849                 }
4850                 else if (pollingInterval !== PollingInterval.High) {
4851                     watchedFile.unchangedPolls++;
4852                     queue[pollIndex] = undefined;
4853                     addToPollingIntervalQueue(watchedFile, pollingInterval === PollingInterval.Low ? PollingInterval.Medium : PollingInterval.High);
4854                 }
4855                 if (queue[pollIndex]) {
4856                     // Copy this file to the non hole location
4857                     if (definedValueCopyToIndex < pollIndex) {
4858                         queue[definedValueCopyToIndex] = watchedFile;
4859                         queue[pollIndex] = undefined;
4860                     }
4861                     definedValueCopyToIndex++;
4862                 }
4863             }
4864             // Return next poll index
4865             return pollIndex;
4866             function nextPollIndex() {
4867                 pollIndex++;
4868                 if (pollIndex === queue.length) {
4869                     if (definedValueCopyToIndex < pollIndex) {
4870                         // There are holes from nextDefinedValueIndex to end of queue, change queue size
4871                         queue.length = definedValueCopyToIndex;
4872                     }
4873                     pollIndex = 0;
4874                     definedValueCopyToIndex = 0;
4875                 }
4876             }
4877         }
4878         function pollingIntervalQueue(pollingInterval) {
4879             switch (pollingInterval) {
4880                 case PollingInterval.Low:
4881                     return lowPollingIntervalQueue;
4882                 case PollingInterval.Medium:
4883                     return mediumPollingIntervalQueue;
4884                 case PollingInterval.High:
4885                     return highPollingIntervalQueue;
4886             }
4887         }
4888         function addToPollingIntervalQueue(file, pollingInterval) {
4889             pollingIntervalQueue(pollingInterval).push(file);
4890             scheduleNextPollIfNotAlreadyScheduled(pollingInterval);
4891         }
4892         function addChangedFileToLowPollingIntervalQueue(file) {
4893             changedFilesInLastPoll.push(file);
4894             scheduleNextPollIfNotAlreadyScheduled(PollingInterval.Low);
4895         }
4896         function scheduleNextPollIfNotAlreadyScheduled(pollingInterval) {
4897             if (!pollingIntervalQueue(pollingInterval).pollScheduled) {
4898                 scheduleNextPoll(pollingInterval);
4899             }
4900         }
4901         function scheduleNextPoll(pollingInterval) {
4902             pollingIntervalQueue(pollingInterval).pollScheduled = host.setTimeout(pollingInterval === PollingInterval.Low ? pollLowPollingIntervalQueue : pollPollingIntervalQueue, pollingInterval, pollingIntervalQueue(pollingInterval));
4903         }
4904         function getModifiedTime(fileName) {
4905             return host.getModifiedTime(fileName) || ts.missingFileModifiedTime;
4906         }
4907     }
4908     ts.createDynamicPriorityPollingWatchFile = createDynamicPriorityPollingWatchFile;
4909     function createUseFsEventsOnParentDirectoryWatchFile(fsWatch, useCaseSensitiveFileNames) {
4910         // One file can have multiple watchers
4911         var fileWatcherCallbacks = ts.createMultiMap();
4912         var dirWatchers = ts.createMap();
4913         var toCanonicalName = ts.createGetCanonicalFileName(useCaseSensitiveFileNames);
4914         return nonPollingWatchFile;
4915         function nonPollingWatchFile(fileName, callback, _pollingInterval, fallbackOptions) {
4916             var filePath = toCanonicalName(fileName);
4917             fileWatcherCallbacks.add(filePath, callback);
4918             var dirPath = ts.getDirectoryPath(filePath) || ".";
4919             var watcher = dirWatchers.get(dirPath) ||
4920                 createDirectoryWatcher(ts.getDirectoryPath(fileName) || ".", dirPath, fallbackOptions);
4921             watcher.referenceCount++;
4922             return {
4923                 close: function () {
4924                     if (watcher.referenceCount === 1) {
4925                         watcher.close();
4926                         dirWatchers.delete(dirPath);
4927                     }
4928                     else {
4929                         watcher.referenceCount--;
4930                     }
4931                     fileWatcherCallbacks.remove(filePath, callback);
4932                 }
4933             };
4934         }
4935         function createDirectoryWatcher(dirName, dirPath, fallbackOptions) {
4936             var watcher = fsWatch(dirName, 1 /* Directory */, function (_eventName, relativeFileName) {
4937                 // When files are deleted from disk, the triggered "rename" event would have a relativefileName of "undefined"
4938                 if (!ts.isString(relativeFileName)) {
4939                     return;
4940                 }
4941                 var fileName = ts.getNormalizedAbsolutePath(relativeFileName, dirName);
4942                 // Some applications save a working file via rename operations
4943                 var callbacks = fileName && fileWatcherCallbacks.get(toCanonicalName(fileName));
4944                 if (callbacks) {
4945                     for (var _i = 0, callbacks_1 = callbacks; _i < callbacks_1.length; _i++) {
4946                         var fileCallback = callbacks_1[_i];
4947                         fileCallback(fileName, FileWatcherEventKind.Changed);
4948                     }
4949                 }
4950             }, 
4951             /*recursive*/ false, PollingInterval.Medium, fallbackOptions);
4952             watcher.referenceCount = 0;
4953             dirWatchers.set(dirPath, watcher);
4954             return watcher;
4955         }
4956     }
4957     /* @internal */
4958     function createSingleFileWatcherPerName(watchFile, useCaseSensitiveFileNames) {
4959         var cache = ts.createMap();
4960         var callbacksCache = ts.createMultiMap();
4961         var toCanonicalFileName = ts.createGetCanonicalFileName(useCaseSensitiveFileNames);
4962         return function (fileName, callback, pollingInterval, options) {
4963             var path = toCanonicalFileName(fileName);
4964             var existing = cache.get(path);
4965             if (existing) {
4966                 existing.refCount++;
4967             }
4968             else {
4969                 cache.set(path, {
4970                     watcher: watchFile(fileName, function (fileName, eventKind) { return ts.forEach(callbacksCache.get(path), function (cb) { return cb(fileName, eventKind); }); }, pollingInterval, options),
4971                     refCount: 1
4972                 });
4973             }
4974             callbacksCache.add(path, callback);
4975             return {
4976                 close: function () {
4977                     var watcher = ts.Debug.checkDefined(cache.get(path));
4978                     callbacksCache.remove(path, callback);
4979                     watcher.refCount--;
4980                     if (watcher.refCount)
4981                         return;
4982                     cache.delete(path);
4983                     ts.closeFileWatcherOf(watcher);
4984                 }
4985             };
4986         };
4987     }
4988     ts.createSingleFileWatcherPerName = createSingleFileWatcherPerName;
4989     /**
4990      * Returns true if file status changed
4991      */
4992     /*@internal*/
4993     function onWatchedFileStat(watchedFile, modifiedTime) {
4994         var oldTime = watchedFile.mtime.getTime();
4995         var newTime = modifiedTime.getTime();
4996         if (oldTime !== newTime) {
4997             watchedFile.mtime = modifiedTime;
4998             watchedFile.callback(watchedFile.fileName, getFileWatcherEventKind(oldTime, newTime));
4999             return true;
5000         }
5001         return false;
5002     }
5003     ts.onWatchedFileStat = onWatchedFileStat;
5004     /*@internal*/
5005     function getFileWatcherEventKind(oldTime, newTime) {
5006         return oldTime === 0
5007             ? FileWatcherEventKind.Created
5008             : newTime === 0
5009                 ? FileWatcherEventKind.Deleted
5010                 : FileWatcherEventKind.Changed;
5011     }
5012     ts.getFileWatcherEventKind = getFileWatcherEventKind;
5013     /*@internal*/
5014     ts.ignoredPaths = ["/node_modules/.", "/.git", "/.#"];
5015     /*@internal*/
5016     ts.sysLog = ts.noop; // eslint-disable-line prefer-const
5017     /*@internal*/
5018     function setSysLog(logger) {
5019         ts.sysLog = logger;
5020     }
5021     ts.setSysLog = setSysLog;
5022     /**
5023      * Watch the directory recursively using host provided method to watch child directories
5024      * that means if this is recursive watcher, watch the children directories as well
5025      * (eg on OS that dont support recursive watch using fs.watch use fs.watchFile)
5026      */
5027     /*@internal*/
5028     function createDirectoryWatcherSupportingRecursive(host) {
5029         var cache = ts.createMap();
5030         var callbackCache = ts.createMultiMap();
5031         var cacheToUpdateChildWatches = ts.createMap();
5032         var timerToUpdateChildWatches;
5033         var filePathComparer = ts.getStringComparer(!host.useCaseSensitiveFileNames);
5034         var toCanonicalFilePath = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames);
5035         return function (dirName, callback, recursive, options) { return recursive ?
5036             createDirectoryWatcher(dirName, options, callback) :
5037             host.watchDirectory(dirName, callback, recursive, options); };
5038         /**
5039          * Create the directory watcher for the dirPath.
5040          */
5041         function createDirectoryWatcher(dirName, options, callback) {
5042             var dirPath = toCanonicalFilePath(dirName);
5043             var directoryWatcher = cache.get(dirPath);
5044             if (directoryWatcher) {
5045                 directoryWatcher.refCount++;
5046             }
5047             else {
5048                 directoryWatcher = {
5049                     watcher: host.watchDirectory(dirName, function (fileName) {
5050                         if (isIgnoredPath(fileName))
5051                             return;
5052                         if (options === null || options === void 0 ? void 0 : options.synchronousWatchDirectory) {
5053                             // Call the actual callback
5054                             invokeCallbacks(dirPath, fileName);
5055                             // Iterate through existing children and update the watches if needed
5056                             updateChildWatches(dirName, dirPath, options);
5057                         }
5058                         else {
5059                             nonSyncUpdateChildWatches(dirName, dirPath, fileName, options);
5060                         }
5061                     }, /*recursive*/ false, options),
5062                     refCount: 1,
5063                     childWatches: ts.emptyArray
5064                 };
5065                 cache.set(dirPath, directoryWatcher);
5066                 updateChildWatches(dirName, dirPath, options);
5067             }
5068             var callbackToAdd = callback && { dirName: dirName, callback: callback };
5069             if (callbackToAdd) {
5070                 callbackCache.add(dirPath, callbackToAdd);
5071             }
5072             return {
5073                 dirName: dirName,
5074                 close: function () {
5075                     var directoryWatcher = ts.Debug.checkDefined(cache.get(dirPath));
5076                     if (callbackToAdd)
5077                         callbackCache.remove(dirPath, callbackToAdd);
5078                     directoryWatcher.refCount--;
5079                     if (directoryWatcher.refCount)
5080                         return;
5081                     cache.delete(dirPath);
5082                     ts.closeFileWatcherOf(directoryWatcher);
5083                     directoryWatcher.childWatches.forEach(ts.closeFileWatcher);
5084                 }
5085             };
5086         }
5087         function invokeCallbacks(dirPath, fileNameOrInvokeMap) {
5088             var fileName;
5089             var invokeMap;
5090             if (ts.isString(fileNameOrInvokeMap)) {
5091                 fileName = fileNameOrInvokeMap;
5092             }
5093             else {
5094                 invokeMap = fileNameOrInvokeMap;
5095             }
5096             // Call the actual callback
5097             callbackCache.forEach(function (callbacks, rootDirName) {
5098                 if (invokeMap && invokeMap.has(rootDirName))
5099                     return;
5100                 if (rootDirName === dirPath || (ts.startsWith(dirPath, rootDirName) && dirPath[rootDirName.length] === ts.directorySeparator)) {
5101                     if (invokeMap) {
5102                         invokeMap.set(rootDirName, true);
5103                     }
5104                     else {
5105                         callbacks.forEach(function (_a) {
5106                             var callback = _a.callback;
5107                             return callback(fileName);
5108                         });
5109                     }
5110                 }
5111             });
5112         }
5113         function nonSyncUpdateChildWatches(dirName, dirPath, fileName, options) {
5114             // Iterate through existing children and update the watches if needed
5115             var parentWatcher = cache.get(dirPath);
5116             if (parentWatcher && host.directoryExists(dirName)) {
5117                 // Schedule the update and postpone invoke for callbacks
5118                 scheduleUpdateChildWatches(dirName, dirPath, options);
5119                 return;
5120             }
5121             // Call the actual callbacks and remove child watches
5122             invokeCallbacks(dirPath, fileName);
5123             removeChildWatches(parentWatcher);
5124         }
5125         function scheduleUpdateChildWatches(dirName, dirPath, options) {
5126             if (!cacheToUpdateChildWatches.has(dirPath)) {
5127                 cacheToUpdateChildWatches.set(dirPath, { dirName: dirName, options: options });
5128             }
5129             if (timerToUpdateChildWatches) {
5130                 host.clearTimeout(timerToUpdateChildWatches);
5131                 timerToUpdateChildWatches = undefined;
5132             }
5133             timerToUpdateChildWatches = host.setTimeout(onTimerToUpdateChildWatches, 1000);
5134         }
5135         function onTimerToUpdateChildWatches() {
5136             timerToUpdateChildWatches = undefined;
5137             ts.sysLog("sysLog:: onTimerToUpdateChildWatches:: " + cacheToUpdateChildWatches.size);
5138             var start = ts.timestamp();
5139             var invokeMap = ts.createMap();
5140             while (!timerToUpdateChildWatches && cacheToUpdateChildWatches.size) {
5141                 var _a = cacheToUpdateChildWatches.entries().next(), _b = _a.value, dirPath = _b[0], _c = _b[1], dirName = _c.dirName, options = _c.options, done = _a.done;
5142                 ts.Debug.assert(!done);
5143                 cacheToUpdateChildWatches.delete(dirPath);
5144                 // Because the child refresh is fresh, we would need to invalidate whole root directory being watched
5145                 // to ensure that all the changes are reflected at this time
5146                 invokeCallbacks(dirPath, invokeMap);
5147                 updateChildWatches(dirName, dirPath, options);
5148             }
5149             ts.sysLog("sysLog:: invokingWatchers:: " + (ts.timestamp() - start) + "ms:: " + cacheToUpdateChildWatches.size);
5150             callbackCache.forEach(function (callbacks, rootDirName) {
5151                 if (invokeMap.has(rootDirName)) {
5152                     callbacks.forEach(function (_a) {
5153                         var callback = _a.callback, dirName = _a.dirName;
5154                         return callback(dirName);
5155                     });
5156                 }
5157             });
5158             var elapsed = ts.timestamp() - start;
5159             ts.sysLog("sysLog:: Elapsed " + elapsed + "ms:: onTimerToUpdateChildWatches:: " + cacheToUpdateChildWatches.size + " " + timerToUpdateChildWatches);
5160         }
5161         function removeChildWatches(parentWatcher) {
5162             if (!parentWatcher)
5163                 return;
5164             var existingChildWatches = parentWatcher.childWatches;
5165             parentWatcher.childWatches = ts.emptyArray;
5166             for (var _i = 0, existingChildWatches_1 = existingChildWatches; _i < existingChildWatches_1.length; _i++) {
5167                 var childWatcher = existingChildWatches_1[_i];
5168                 childWatcher.close();
5169                 removeChildWatches(cache.get(toCanonicalFilePath(childWatcher.dirName)));
5170             }
5171         }
5172         function updateChildWatches(dirName, dirPath, options) {
5173             // Iterate through existing children and update the watches if needed
5174             var parentWatcher = cache.get(dirPath);
5175             if (parentWatcher) {
5176                 parentWatcher.childWatches = watchChildDirectories(dirName, parentWatcher.childWatches, options);
5177             }
5178         }
5179         /**
5180          * Watch the directories in the parentDir
5181          */
5182         function watchChildDirectories(parentDir, existingChildWatches, options) {
5183             var newChildWatches;
5184             ts.enumerateInsertsAndDeletes(host.directoryExists(parentDir) ? ts.mapDefined(host.getAccessibleSortedChildDirectories(parentDir), function (child) {
5185                 var childFullName = ts.getNormalizedAbsolutePath(child, parentDir);
5186                 // Filter our the symbolic link directories since those arent included in recursive watch
5187                 // which is same behaviour when recursive: true is passed to fs.watch
5188                 return !isIgnoredPath(childFullName) && filePathComparer(childFullName, ts.normalizePath(host.realpath(childFullName))) === 0 /* EqualTo */ ? childFullName : undefined;
5189             }) : ts.emptyArray, existingChildWatches, function (child, childWatcher) { return filePathComparer(child, childWatcher.dirName); }, createAndAddChildDirectoryWatcher, ts.closeFileWatcher, addChildDirectoryWatcher);
5190             return newChildWatches || ts.emptyArray;
5191             /**
5192              * Create new childDirectoryWatcher and add it to the new ChildDirectoryWatcher list
5193              */
5194             function createAndAddChildDirectoryWatcher(childName) {
5195                 var result = createDirectoryWatcher(childName, options);
5196                 addChildDirectoryWatcher(result);
5197             }
5198             /**
5199              * Add child directory watcher to the new ChildDirectoryWatcher list
5200              */
5201             function addChildDirectoryWatcher(childWatcher) {
5202                 (newChildWatches || (newChildWatches = [])).push(childWatcher);
5203             }
5204         }
5205         function isIgnoredPath(path) {
5206             return ts.some(ts.ignoredPaths, function (searchPath) { return isInPath(path, searchPath); });
5207         }
5208         function isInPath(path, searchPath) {
5209             if (ts.stringContains(path, searchPath))
5210                 return true;
5211             if (host.useCaseSensitiveFileNames)
5212                 return false;
5213             return ts.stringContains(toCanonicalFilePath(path), searchPath);
5214         }
5215     }
5216     ts.createDirectoryWatcherSupportingRecursive = createDirectoryWatcherSupportingRecursive;
5217     /*@internal*/
5218     var FileSystemEntryKind;
5219     (function (FileSystemEntryKind) {
5220         FileSystemEntryKind[FileSystemEntryKind["File"] = 0] = "File";
5221         FileSystemEntryKind[FileSystemEntryKind["Directory"] = 1] = "Directory";
5222     })(FileSystemEntryKind = ts.FileSystemEntryKind || (ts.FileSystemEntryKind = {}));
5223     /*@internal*/
5224     function createFileWatcherCallback(callback) {
5225         return function (_fileName, eventKind) { return callback(eventKind === FileWatcherEventKind.Changed ? "change" : "rename", ""); };
5226     }
5227     ts.createFileWatcherCallback = createFileWatcherCallback;
5228     function createFsWatchCallbackForFileWatcherCallback(fileName, callback, fileExists) {
5229         return function (eventName) {
5230             if (eventName === "rename") {
5231                 callback(fileName, fileExists(fileName) ? FileWatcherEventKind.Created : FileWatcherEventKind.Deleted);
5232             }
5233             else {
5234                 // Change
5235                 callback(fileName, FileWatcherEventKind.Changed);
5236             }
5237         };
5238     }
5239     function createFsWatchCallbackForDirectoryWatcherCallback(directoryName, callback) {
5240         return function (eventName, relativeFileName) {
5241             // In watchDirectory we only care about adding and removing files (when event name is
5242             // "rename"); changes made within files are handled by corresponding fileWatchers (when
5243             // event name is "change")
5244             if (eventName === "rename") {
5245                 // When deleting a file, the passed baseFileName is null
5246                 callback(!relativeFileName ? directoryName : ts.normalizePath(ts.combinePaths(directoryName, relativeFileName)));
5247             }
5248         };
5249     }
5250     /*@internal*/
5251     function createSystemWatchFunctions(_a) {
5252         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;
5253         var dynamicPollingWatchFile;
5254         var nonPollingWatchFile;
5255         var hostRecursiveDirectoryWatcher;
5256         return {
5257             watchFile: watchFile,
5258             watchDirectory: watchDirectory
5259         };
5260         function watchFile(fileName, callback, pollingInterval, options) {
5261             options = updateOptionsForWatchFile(options, useNonPollingWatchers);
5262             var watchFileKind = ts.Debug.checkDefined(options.watchFile);
5263             switch (watchFileKind) {
5264                 case ts.WatchFileKind.FixedPollingInterval:
5265                     return pollingWatchFile(fileName, callback, PollingInterval.Low, /*options*/ undefined);
5266                 case ts.WatchFileKind.PriorityPollingInterval:
5267                     return pollingWatchFile(fileName, callback, pollingInterval, /*options*/ undefined);
5268                 case ts.WatchFileKind.DynamicPriorityPolling:
5269                     return ensureDynamicPollingWatchFile()(fileName, callback, pollingInterval, /*options*/ undefined);
5270                 case ts.WatchFileKind.UseFsEvents:
5271                     return fsWatch(fileName, 0 /* File */, createFsWatchCallbackForFileWatcherCallback(fileName, callback, fileExists), 
5272                     /*recursive*/ false, pollingInterval, ts.getFallbackOptions(options));
5273                 case ts.WatchFileKind.UseFsEventsOnParentDirectory:
5274                     if (!nonPollingWatchFile) {
5275                         nonPollingWatchFile = createUseFsEventsOnParentDirectoryWatchFile(fsWatch, useCaseSensitiveFileNames);
5276                     }
5277                     return nonPollingWatchFile(fileName, callback, pollingInterval, ts.getFallbackOptions(options));
5278                 default:
5279                     ts.Debug.assertNever(watchFileKind);
5280             }
5281         }
5282         function ensureDynamicPollingWatchFile() {
5283             return dynamicPollingWatchFile ||
5284                 (dynamicPollingWatchFile = createDynamicPriorityPollingWatchFile({ getModifiedTime: getModifiedTime, setTimeout: setTimeout }));
5285         }
5286         function updateOptionsForWatchFile(options, useNonPollingWatchers) {
5287             if (options && options.watchFile !== undefined)
5288                 return options;
5289             switch (tscWatchFile) {
5290                 case "PriorityPollingInterval":
5291                     // Use polling interval based on priority when create watch using host.watchFile
5292                     return { watchFile: ts.WatchFileKind.PriorityPollingInterval };
5293                 case "DynamicPriorityPolling":
5294                     // Use polling interval but change the interval depending on file changes and their default polling interval
5295                     return { watchFile: ts.WatchFileKind.DynamicPriorityPolling };
5296                 case "UseFsEvents":
5297                     // Use notifications from FS to watch with falling back to fs.watchFile
5298                     return generateWatchFileOptions(ts.WatchFileKind.UseFsEvents, ts.PollingWatchKind.PriorityInterval, options);
5299                 case "UseFsEventsWithFallbackDynamicPolling":
5300                     // Use notifications from FS to watch with falling back to dynamic watch file
5301                     return generateWatchFileOptions(ts.WatchFileKind.UseFsEvents, ts.PollingWatchKind.DynamicPriority, options);
5302                 case "UseFsEventsOnParentDirectory":
5303                     useNonPollingWatchers = true;
5304                 // fall through
5305                 default:
5306                     return useNonPollingWatchers ?
5307                         // Use notifications from FS to watch with falling back to fs.watchFile
5308                         generateWatchFileOptions(ts.WatchFileKind.UseFsEventsOnParentDirectory, ts.PollingWatchKind.PriorityInterval, options) :
5309                         // Default to do not use fixed polling interval
5310                         { watchFile: ts.WatchFileKind.FixedPollingInterval };
5311             }
5312         }
5313         function generateWatchFileOptions(watchFile, fallbackPolling, options) {
5314             var defaultFallbackPolling = options === null || options === void 0 ? void 0 : options.fallbackPolling;
5315             return {
5316                 watchFile: watchFile,
5317                 fallbackPolling: defaultFallbackPolling === undefined ?
5318                     fallbackPolling :
5319                     defaultFallbackPolling
5320             };
5321         }
5322         function watchDirectory(directoryName, callback, recursive, options) {
5323             if (fsSupportsRecursiveFsWatch) {
5324                 return fsWatch(directoryName, 1 /* Directory */, createFsWatchCallbackForDirectoryWatcherCallback(directoryName, callback), recursive, PollingInterval.Medium, ts.getFallbackOptions(options));
5325             }
5326             if (!hostRecursiveDirectoryWatcher) {
5327                 hostRecursiveDirectoryWatcher = createDirectoryWatcherSupportingRecursive({
5328                     useCaseSensitiveFileNames: useCaseSensitiveFileNames,
5329                     directoryExists: directoryExists,
5330                     getAccessibleSortedChildDirectories: getAccessibleSortedChildDirectories,
5331                     watchDirectory: nonRecursiveWatchDirectory,
5332                     realpath: realpath,
5333                     setTimeout: setTimeout,
5334                     clearTimeout: clearTimeout
5335                 });
5336             }
5337             return hostRecursiveDirectoryWatcher(directoryName, callback, recursive, options);
5338         }
5339         function nonRecursiveWatchDirectory(directoryName, callback, recursive, options) {
5340             ts.Debug.assert(!recursive);
5341             options = updateOptionsForWatchDirectory(options);
5342             var watchDirectoryKind = ts.Debug.checkDefined(options.watchDirectory);
5343             switch (watchDirectoryKind) {
5344                 case ts.WatchDirectoryKind.FixedPollingInterval:
5345                     return pollingWatchFile(directoryName, function () { return callback(directoryName); }, PollingInterval.Medium, 
5346                     /*options*/ undefined);
5347                 case ts.WatchDirectoryKind.DynamicPriorityPolling:
5348                     return ensureDynamicPollingWatchFile()(directoryName, function () { return callback(directoryName); }, PollingInterval.Medium, 
5349                     /*options*/ undefined);
5350                 case ts.WatchDirectoryKind.UseFsEvents:
5351                     return fsWatch(directoryName, 1 /* Directory */, createFsWatchCallbackForDirectoryWatcherCallback(directoryName, callback), recursive, PollingInterval.Medium, ts.getFallbackOptions(options));
5352                 default:
5353                     ts.Debug.assertNever(watchDirectoryKind);
5354             }
5355         }
5356         function updateOptionsForWatchDirectory(options) {
5357             if (options && options.watchDirectory !== undefined)
5358                 return options;
5359             switch (tscWatchDirectory) {
5360                 case "RecursiveDirectoryUsingFsWatchFile":
5361                     // Use polling interval based on priority when create watch using host.watchFile
5362                     return { watchDirectory: ts.WatchDirectoryKind.FixedPollingInterval };
5363                 case "RecursiveDirectoryUsingDynamicPriorityPolling":
5364                     // Use polling interval but change the interval depending on file changes and their default polling interval
5365                     return { watchDirectory: ts.WatchDirectoryKind.DynamicPriorityPolling };
5366                 default:
5367                     var defaultFallbackPolling = options === null || options === void 0 ? void 0 : options.fallbackPolling;
5368                     return {
5369                         watchDirectory: ts.WatchDirectoryKind.UseFsEvents,
5370                         fallbackPolling: defaultFallbackPolling !== undefined ?
5371                             defaultFallbackPolling :
5372                             undefined
5373                     };
5374             }
5375         }
5376     }
5377     ts.createSystemWatchFunctions = createSystemWatchFunctions;
5378     /**
5379      * patch writefile to create folder before writing the file
5380      */
5381     /*@internal*/
5382     function patchWriteFileEnsuringDirectory(sys) {
5383         // patch writefile to create folder before writing the file
5384         var originalWriteFile = sys.writeFile;
5385         sys.writeFile = function (path, data, writeBom) {
5386             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); });
5387         };
5388     }
5389     ts.patchWriteFileEnsuringDirectory = patchWriteFileEnsuringDirectory;
5390     function getNodeMajorVersion() {
5391         if (typeof process === "undefined") {
5392             return undefined;
5393         }
5394         var version = process.version;
5395         if (!version) {
5396             return undefined;
5397         }
5398         var dot = version.indexOf(".");
5399         if (dot === -1) {
5400             return undefined;
5401         }
5402         return parseInt(version.substring(1, dot));
5403     }
5404     ts.getNodeMajorVersion = getNodeMajorVersion;
5405     // TODO: GH#18217 this is used as if it's certainly defined in many places.
5406     // eslint-disable-next-line prefer-const
5407     ts.sys = (function () {
5408         // NodeJS detects "\uFEFF" at the start of the string and *replaces* it with the actual
5409         // byte order mark from the specified encoding. Using any other byte order mark does
5410         // not actually work.
5411         var byteOrderMarkIndicator = "\uFEFF";
5412         function getNodeSystem() {
5413             var nativePattern = /^native |^\([^)]+\)$|^(internal[\\/]|[a-zA-Z0-9_\s]+(\.js)?$)/;
5414             var _fs = require("fs");
5415             var _path = require("path");
5416             var _os = require("os");
5417             // crypto can be absent on reduced node installations
5418             var _crypto;
5419             try {
5420                 _crypto = require("crypto");
5421             }
5422             catch (_a) {
5423                 _crypto = undefined;
5424             }
5425             var activeSession;
5426             var profilePath = "./profile.cpuprofile";
5427             var Buffer = require("buffer").Buffer;
5428             var nodeVersion = getNodeMajorVersion();
5429             var isNode4OrLater = nodeVersion >= 4;
5430             var isLinuxOrMacOs = process.platform === "linux" || process.platform === "darwin";
5431             var platform = _os.platform();
5432             var useCaseSensitiveFileNames = isFileSystemCaseSensitive();
5433             var fsSupportsRecursiveFsWatch = isNode4OrLater && (process.platform === "win32" || process.platform === "darwin");
5434             var _b = createSystemWatchFunctions({
5435                 pollingWatchFile: createSingleFileWatcherPerName(fsWatchFileWorker, useCaseSensitiveFileNames),
5436                 getModifiedTime: getModifiedTime,
5437                 setTimeout: setTimeout,
5438                 clearTimeout: clearTimeout,
5439                 fsWatch: fsWatch,
5440                 useCaseSensitiveFileNames: useCaseSensitiveFileNames,
5441                 fileExists: fileExists,
5442                 // Node 4.0 `fs.watch` function supports the "recursive" option on both OSX and Windows
5443                 // (ref: https://github.com/nodejs/node/pull/2649 and https://github.com/Microsoft/TypeScript/issues/4643)
5444                 fsSupportsRecursiveFsWatch: fsSupportsRecursiveFsWatch,
5445                 directoryExists: directoryExists,
5446                 getAccessibleSortedChildDirectories: function (path) { return getAccessibleFileSystemEntries(path).directories; },
5447                 realpath: realpath,
5448                 tscWatchFile: process.env.TSC_WATCHFILE,
5449                 useNonPollingWatchers: process.env.TSC_NONPOLLING_WATCHER,
5450                 tscWatchDirectory: process.env.TSC_WATCHDIRECTORY,
5451             }), watchFile = _b.watchFile, watchDirectory = _b.watchDirectory;
5452             var nodeSystem = {
5453                 args: process.argv.slice(2),
5454                 newLine: _os.EOL,
5455                 useCaseSensitiveFileNames: useCaseSensitiveFileNames,
5456                 write: function (s) {
5457                     process.stdout.write(s);
5458                 },
5459                 writeOutputIsTTY: function () {
5460                     return process.stdout.isTTY;
5461                 },
5462                 readFile: readFile,
5463                 writeFile: writeFile,
5464                 watchFile: watchFile,
5465                 watchDirectory: watchDirectory,
5466                 resolvePath: function (path) { return _path.resolve(path); },
5467                 fileExists: fileExists,
5468                 directoryExists: directoryExists,
5469                 createDirectory: function (directoryName) {
5470                     if (!nodeSystem.directoryExists(directoryName)) {
5471                         // Wrapped in a try-catch to prevent crashing if we are in a race
5472                         // with another copy of ourselves to create the same directory
5473                         try {
5474                             _fs.mkdirSync(directoryName);
5475                         }
5476                         catch (e) {
5477                             if (e.code !== "EEXIST") {
5478                                 // Failed for some other reason (access denied?); still throw
5479                                 throw e;
5480                             }
5481                         }
5482                     }
5483                 },
5484                 getExecutingFilePath: function () {
5485                     return __filename;
5486                 },
5487                 getCurrentDirectory: function () {
5488                     return process.cwd();
5489                 },
5490                 getDirectories: getDirectories,
5491                 getEnvironmentVariable: function (name) {
5492                     return process.env[name] || "";
5493                 },
5494                 readDirectory: readDirectory,
5495                 getModifiedTime: getModifiedTime,
5496                 setModifiedTime: setModifiedTime,
5497                 deleteFile: deleteFile,
5498                 createHash: _crypto ? createSHA256Hash : generateDjb2Hash,
5499                 createSHA256Hash: _crypto ? createSHA256Hash : undefined,
5500                 getMemoryUsage: function () {
5501                     if (global.gc) {
5502                         global.gc();
5503                     }
5504                     return process.memoryUsage().heapUsed;
5505                 },
5506                 getFileSize: function (path) {
5507                     try {
5508                         var stat = statSync(path);
5509                         if (stat === null || stat === void 0 ? void 0 : stat.isFile()) {
5510                             return stat.size;
5511                         }
5512                     }
5513                     catch ( /*ignore*/_a) { /*ignore*/ }
5514                     return 0;
5515                 },
5516                 exit: function (exitCode) {
5517                     disableCPUProfiler(function () { return process.exit(exitCode); });
5518                 },
5519                 enableCPUProfiler: enableCPUProfiler,
5520                 disableCPUProfiler: disableCPUProfiler,
5521                 realpath: realpath,
5522                 debugMode: !!process.env.NODE_INSPECTOR_IPC || ts.some(process.execArgv, function (arg) { return /^--(inspect|debug)(-brk)?(=\d+)?$/i.test(arg); }),
5523                 tryEnableSourceMapsForHost: function () {
5524                     try {
5525                         require("source-map-support").install();
5526                     }
5527                     catch (_a) {
5528                         // Could not enable source maps.
5529                     }
5530                 },
5531                 setTimeout: setTimeout,
5532                 clearTimeout: clearTimeout,
5533                 clearScreen: function () {
5534                     process.stdout.write("\x1Bc");
5535                 },
5536                 setBlocking: function () {
5537                     if (process.stdout && process.stdout._handle && process.stdout._handle.setBlocking) {
5538                         process.stdout._handle.setBlocking(true);
5539                     }
5540                 },
5541                 bufferFrom: bufferFrom,
5542                 base64decode: function (input) { return bufferFrom(input, "base64").toString("utf8"); },
5543                 base64encode: function (input) { return bufferFrom(input).toString("base64"); },
5544                 require: function (baseDir, moduleName) {
5545                     try {
5546                         var modulePath = ts.resolveJSModule(moduleName, baseDir, nodeSystem);
5547                         return { module: require(modulePath), modulePath: modulePath, error: undefined };
5548                     }
5549                     catch (error) {
5550                         return { module: undefined, modulePath: undefined, error: error };
5551                     }
5552                 }
5553             };
5554             return nodeSystem;
5555             /**
5556              * `throwIfNoEntry` was added so recently that it's not in the node types.
5557              * This helper encapsulates the mitigating usage of `any`.
5558              * See https://github.com/nodejs/node/pull/33716
5559              */
5560             function statSync(path) {
5561                 // throwIfNoEntry will be ignored by older versions of node
5562                 return _fs.statSync(path, { throwIfNoEntry: false });
5563             }
5564             /**
5565              * Uses the builtin inspector APIs to capture a CPU profile
5566              * See https://nodejs.org/api/inspector.html#inspector_example_usage for details
5567              */
5568             function enableCPUProfiler(path, cb) {
5569                 if (activeSession) {
5570                     cb();
5571                     return false;
5572                 }
5573                 var inspector = require("inspector");
5574                 if (!inspector || !inspector.Session) {
5575                     cb();
5576                     return false;
5577                 }
5578                 var session = new inspector.Session();
5579                 session.connect();
5580                 session.post("Profiler.enable", function () {
5581                     session.post("Profiler.start", function () {
5582                         activeSession = session;
5583                         profilePath = path;
5584                         cb();
5585                     });
5586                 });
5587                 return true;
5588             }
5589             /**
5590              * Strips non-TS paths from the profile, so users with private projects shouldn't
5591              * need to worry about leaking paths by submitting a cpu profile to us
5592              */
5593             function cleanupPaths(profile) {
5594                 var externalFileCounter = 0;
5595                 var remappedPaths = ts.createMap();
5596                 var normalizedDir = ts.normalizeSlashes(__dirname);
5597                 // Windows rooted dir names need an extra `/` prepended to be valid file:/// urls
5598                 var fileUrlRoot = "file://" + (ts.getRootLength(normalizedDir) === 1 ? "" : "/") + normalizedDir;
5599                 for (var _i = 0, _a = profile.nodes; _i < _a.length; _i++) {
5600                     var node = _a[_i];
5601                     if (node.callFrame.url) {
5602                         var url = ts.normalizeSlashes(node.callFrame.url);
5603                         if (ts.containsPath(fileUrlRoot, url, useCaseSensitiveFileNames)) {
5604                             node.callFrame.url = ts.getRelativePathToDirectoryOrUrl(fileUrlRoot, url, fileUrlRoot, ts.createGetCanonicalFileName(useCaseSensitiveFileNames), /*isAbsolutePathAnUrl*/ true);
5605                         }
5606                         else if (!nativePattern.test(url)) {
5607                             node.callFrame.url = (remappedPaths.has(url) ? remappedPaths : remappedPaths.set(url, "external" + externalFileCounter + ".js")).get(url);
5608                             externalFileCounter++;
5609                         }
5610                     }
5611                 }
5612                 return profile;
5613             }
5614             function disableCPUProfiler(cb) {
5615                 if (activeSession && activeSession !== "stopping") {
5616                     var s_1 = activeSession;
5617                     activeSession.post("Profiler.stop", function (err, _a) {
5618                         var _b;
5619                         var profile = _a.profile;
5620                         if (!err) {
5621                             try {
5622                                 if ((_b = statSync(profilePath)) === null || _b === void 0 ? void 0 : _b.isDirectory()) {
5623                                     profilePath = _path.join(profilePath, (new Date()).toISOString().replace(/:/g, "-") + "+P" + process.pid + ".cpuprofile");
5624                                 }
5625                             }
5626                             catch (_c) {
5627                                 // do nothing and ignore fallible fs operation
5628                             }
5629                             try {
5630                                 _fs.mkdirSync(_path.dirname(profilePath), { recursive: true });
5631                             }
5632                             catch (_d) {
5633                                 // do nothing and ignore fallible fs operation
5634                             }
5635                             _fs.writeFileSync(profilePath, JSON.stringify(cleanupPaths(profile)));
5636                         }
5637                         activeSession = undefined;
5638                         s_1.disconnect();
5639                         cb();
5640                     });
5641                     activeSession = "stopping";
5642                     return true;
5643                 }
5644                 else {
5645                     cb();
5646                     return false;
5647                 }
5648             }
5649             function bufferFrom(input, encoding) {
5650                 // See https://github.com/Microsoft/TypeScript/issues/25652
5651                 return Buffer.from && Buffer.from !== Int8Array.from
5652                     ? Buffer.from(input, encoding)
5653                     : new Buffer(input, encoding);
5654             }
5655             function isFileSystemCaseSensitive() {
5656                 // win32\win64 are case insensitive platforms
5657                 if (platform === "win32" || platform === "win64") {
5658                     return false;
5659                 }
5660                 // If this file exists under a different case, we must be case-insensitve.
5661                 return !fileExists(swapCase(__filename));
5662             }
5663             /** Convert all lowercase chars to uppercase, and vice-versa */
5664             function swapCase(s) {
5665                 return s.replace(/\w/g, function (ch) {
5666                     var up = ch.toUpperCase();
5667                     return ch === up ? ch.toLowerCase() : up;
5668                 });
5669             }
5670             function fsWatchFileWorker(fileName, callback, pollingInterval) {
5671                 _fs.watchFile(fileName, { persistent: true, interval: pollingInterval }, fileChanged);
5672                 var eventKind;
5673                 return {
5674                     close: function () { return _fs.unwatchFile(fileName, fileChanged); }
5675                 };
5676                 function fileChanged(curr, prev) {
5677                     // 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)
5678                     // In such case, prevTime returned is same as prev time of event when file was deleted as per node documentation
5679                     var isPreviouslyDeleted = +prev.mtime === 0 || eventKind === FileWatcherEventKind.Deleted;
5680                     if (+curr.mtime === 0) {
5681                         if (isPreviouslyDeleted) {
5682                             // Already deleted file, no need to callback again
5683                             return;
5684                         }
5685                         eventKind = FileWatcherEventKind.Deleted;
5686                     }
5687                     else if (isPreviouslyDeleted) {
5688                         eventKind = FileWatcherEventKind.Created;
5689                     }
5690                     // If there is no change in modified time, ignore the event
5691                     else if (+curr.mtime === +prev.mtime) {
5692                         return;
5693                     }
5694                     else {
5695                         // File changed
5696                         eventKind = FileWatcherEventKind.Changed;
5697                     }
5698                     callback(fileName, eventKind);
5699                 }
5700             }
5701             function fsWatch(fileOrDirectory, entryKind, callback, recursive, fallbackPollingInterval, fallbackOptions) {
5702                 var options;
5703                 var lastDirectoryPartWithDirectorySeparator;
5704                 var lastDirectoryPart;
5705                 if (isLinuxOrMacOs) {
5706                     lastDirectoryPartWithDirectorySeparator = fileOrDirectory.substr(fileOrDirectory.lastIndexOf(ts.directorySeparator));
5707                     lastDirectoryPart = lastDirectoryPartWithDirectorySeparator.slice(ts.directorySeparator.length);
5708                 }
5709                 /** Watcher for the file system entry depending on whether it is missing or present */
5710                 var watcher = !fileSystemEntryExists(fileOrDirectory, entryKind) ?
5711                     watchMissingFileSystemEntry() :
5712                     watchPresentFileSystemEntry();
5713                 return {
5714                     close: function () {
5715                         // Close the watcher (either existing file system entry watcher or missing file system entry watcher)
5716                         watcher.close();
5717                         watcher = undefined;
5718                     }
5719                 };
5720                 /**
5721                  * Invoke the callback with rename and update the watcher if not closed
5722                  * @param createWatcher
5723                  */
5724                 function invokeCallbackAndUpdateWatcher(createWatcher) {
5725                     ts.sysLog("sysLog:: " + fileOrDirectory + ":: Changing watcher to " + (createWatcher === watchPresentFileSystemEntry ? "Present" : "Missing") + "FileSystemEntryWatcher");
5726                     // Call the callback for current directory
5727                     callback("rename", "");
5728                     // If watcher is not closed, update it
5729                     if (watcher) {
5730                         watcher.close();
5731                         watcher = createWatcher();
5732                     }
5733                 }
5734                 /**
5735                  * Watch the file or directory that is currently present
5736                  * and when the watched file or directory is deleted, switch to missing file system entry watcher
5737                  */
5738                 function watchPresentFileSystemEntry() {
5739                     // Node 4.0 `fs.watch` function supports the "recursive" option on both OSX and Windows
5740                     // (ref: https://github.com/nodejs/node/pull/2649 and https://github.com/Microsoft/TypeScript/issues/4643)
5741                     if (options === undefined) {
5742                         if (fsSupportsRecursiveFsWatch) {
5743                             options = { persistent: true, recursive: !!recursive };
5744                         }
5745                         else {
5746                             options = { persistent: true };
5747                         }
5748                     }
5749                     try {
5750                         var presentWatcher = _fs.watch(fileOrDirectory, options, isLinuxOrMacOs ?
5751                             callbackChangingToMissingFileSystemEntry :
5752                             callback);
5753                         // Watch the missing file or directory or error
5754                         presentWatcher.on("error", function () { return invokeCallbackAndUpdateWatcher(watchMissingFileSystemEntry); });
5755                         return presentWatcher;
5756                     }
5757                     catch (e) {
5758                         // Catch the exception and use polling instead
5759                         // 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
5760                         // so instead of throwing error, use fs.watchFile
5761                         return watchPresentFileSystemEntryWithFsWatchFile();
5762                     }
5763                 }
5764                 function callbackChangingToMissingFileSystemEntry(event, relativeName) {
5765                     // because relativeName is not guaranteed to be correct we need to check on each rename with few combinations
5766                     // Eg on ubuntu while watching app/node_modules the relativeName is "node_modules" which is neither relative nor full path
5767                     return event === "rename" &&
5768                         (!relativeName ||
5769                             relativeName === lastDirectoryPart ||
5770                             relativeName.lastIndexOf(lastDirectoryPartWithDirectorySeparator) === relativeName.length - lastDirectoryPartWithDirectorySeparator.length) &&
5771                         !fileSystemEntryExists(fileOrDirectory, entryKind) ?
5772                         invokeCallbackAndUpdateWatcher(watchMissingFileSystemEntry) :
5773                         callback(event, relativeName);
5774                 }
5775                 /**
5776                  * Watch the file or directory using fs.watchFile since fs.watch threw exception
5777                  * 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
5778                  */
5779                 function watchPresentFileSystemEntryWithFsWatchFile() {
5780                     ts.sysLog("sysLog:: " + fileOrDirectory + ":: Changing to fsWatchFile");
5781                     return watchFile(fileOrDirectory, createFileWatcherCallback(callback), fallbackPollingInterval, fallbackOptions);
5782                 }
5783                 /**
5784                  * Watch the file or directory that is missing
5785                  * and switch to existing file or directory when the missing filesystem entry is created
5786                  */
5787                 function watchMissingFileSystemEntry() {
5788                     return watchFile(fileOrDirectory, function (_fileName, eventKind) {
5789                         if (eventKind === FileWatcherEventKind.Created && fileSystemEntryExists(fileOrDirectory, entryKind)) {
5790                             // Call the callback for current file or directory
5791                             // For now it could be callback for the inner directory creation,
5792                             // but just return current directory, better than current no-op
5793                             invokeCallbackAndUpdateWatcher(watchPresentFileSystemEntry);
5794                         }
5795                     }, fallbackPollingInterval, fallbackOptions);
5796                 }
5797             }
5798             function readFileWorker(fileName, _encoding) {
5799                 var buffer;
5800                 try {
5801                     buffer = _fs.readFileSync(fileName);
5802                 }
5803                 catch (e) {
5804                     return undefined;
5805                 }
5806                 var len = buffer.length;
5807                 if (len >= 2 && buffer[0] === 0xFE && buffer[1] === 0xFF) {
5808                     // Big endian UTF-16 byte order mark detected. Since big endian is not supported by node.js,
5809                     // flip all byte pairs and treat as little endian.
5810                     len &= ~1; // Round down to a multiple of 2
5811                     for (var i = 0; i < len; i += 2) {
5812                         var temp = buffer[i];
5813                         buffer[i] = buffer[i + 1];
5814                         buffer[i + 1] = temp;
5815                     }
5816                     return buffer.toString("utf16le", 2);
5817                 }
5818                 if (len >= 2 && buffer[0] === 0xFF && buffer[1] === 0xFE) {
5819                     // Little endian UTF-16 byte order mark detected
5820                     return buffer.toString("utf16le", 2);
5821                 }
5822                 if (len >= 3 && buffer[0] === 0xEF && buffer[1] === 0xBB && buffer[2] === 0xBF) {
5823                     // UTF-8 byte order mark detected
5824                     return buffer.toString("utf8", 3);
5825                 }
5826                 // Default is UTF-8 with no byte order mark
5827                 return buffer.toString("utf8");
5828             }
5829             function readFile(fileName, _encoding) {
5830                 ts.perfLogger.logStartReadFile(fileName);
5831                 var file = readFileWorker(fileName, _encoding);
5832                 ts.perfLogger.logStopReadFile();
5833                 return file;
5834             }
5835             function writeFile(fileName, data, writeByteOrderMark) {
5836                 ts.perfLogger.logEvent("WriteFile: " + fileName);
5837                 // If a BOM is required, emit one
5838                 if (writeByteOrderMark) {
5839                     data = byteOrderMarkIndicator + data;
5840                 }
5841                 var fd;
5842                 try {
5843                     fd = _fs.openSync(fileName, "w");
5844                     _fs.writeSync(fd, data, /*position*/ undefined, "utf8");
5845                 }
5846                 finally {
5847                     if (fd !== undefined) {
5848                         _fs.closeSync(fd);
5849                     }
5850                 }
5851             }
5852             function getAccessibleFileSystemEntries(path) {
5853                 ts.perfLogger.logEvent("ReadDir: " + (path || "."));
5854                 try {
5855                     var entries = _fs.readdirSync(path || ".", { withFileTypes: true });
5856                     var files = [];
5857                     var directories = [];
5858                     for (var _i = 0, entries_2 = entries; _i < entries_2.length; _i++) {
5859                         var dirent = entries_2[_i];
5860                         // withFileTypes is not supported before Node 10.10.
5861                         var entry = typeof dirent === "string" ? dirent : dirent.name;
5862                         // This is necessary because on some file system node fails to exclude
5863                         // "." and "..". See https://github.com/nodejs/node/issues/4002
5864                         if (entry === "." || entry === "..") {
5865                             continue;
5866                         }
5867                         var stat = void 0;
5868                         if (typeof dirent === "string" || dirent.isSymbolicLink()) {
5869                             var name = ts.combinePaths(path, entry);
5870                             try {
5871                                 stat = statSync(name);
5872                                 if (!stat) {
5873                                     continue;
5874                                 }
5875                             }
5876                             catch (e) {
5877                                 continue;
5878                             }
5879                         }
5880                         else {
5881                             stat = dirent;
5882                         }
5883                         if (stat.isFile()) {
5884                             files.push(entry);
5885                         }
5886                         else if (stat.isDirectory()) {
5887                             directories.push(entry);
5888                         }
5889                     }
5890                     files.sort();
5891                     directories.sort();
5892                     return { files: files, directories: directories };
5893                 }
5894                 catch (e) {
5895                     return ts.emptyFileSystemEntries;
5896                 }
5897             }
5898             function readDirectory(path, extensions, excludes, includes, depth) {
5899                 return ts.matchFiles(path, extensions, excludes, includes, useCaseSensitiveFileNames, process.cwd(), depth, getAccessibleFileSystemEntries, realpath);
5900             }
5901             function fileSystemEntryExists(path, entryKind) {
5902                 try {
5903                     var stat = statSync(path);
5904                     if (!stat) {
5905                         return false;
5906                     }
5907                     switch (entryKind) {
5908                         case 0 /* File */: return stat.isFile();
5909                         case 1 /* Directory */: return stat.isDirectory();
5910                         default: return false;
5911                     }
5912                 }
5913                 catch (e) {
5914                     return false;
5915                 }
5916             }
5917             function fileExists(path) {
5918                 return fileSystemEntryExists(path, 0 /* File */);
5919             }
5920             function directoryExists(path) {
5921                 return fileSystemEntryExists(path, 1 /* Directory */);
5922             }
5923             function getDirectories(path) {
5924                 return getAccessibleFileSystemEntries(path).directories.slice();
5925             }
5926             function realpath(path) {
5927                 try {
5928                     return _fs.realpathSync(path);
5929                 }
5930                 catch (_a) {
5931                     return path;
5932                 }
5933             }
5934             function getModifiedTime(path) {
5935                 var _a;
5936                 try {
5937                     return (_a = statSync(path)) === null || _a === void 0 ? void 0 : _a.mtime;
5938                 }
5939                 catch (e) {
5940                     return undefined;
5941                 }
5942             }
5943             function setModifiedTime(path, time) {
5944                 try {
5945                     _fs.utimesSync(path, time, time);
5946                 }
5947                 catch (e) {
5948                     return;
5949                 }
5950             }
5951             function deleteFile(path) {
5952                 try {
5953                     return _fs.unlinkSync(path);
5954                 }
5955                 catch (e) {
5956                     return;
5957                 }
5958             }
5959             function createSHA256Hash(data) {
5960                 var hash = _crypto.createHash("sha256");
5961                 hash.update(data);
5962                 return hash.digest("hex");
5963             }
5964         }
5965         var sys;
5966         if (typeof process !== "undefined" && process.nextTick && !process.browser && typeof require !== "undefined") {
5967             // process and process.nextTick checks if current environment is node-like
5968             // process.browser check excludes webpack and browserify
5969             sys = getNodeSystem();
5970         }
5971         if (sys) {
5972             // patch writefile to create folder before writing the file
5973             patchWriteFileEnsuringDirectory(sys);
5974         }
5975         return sys;
5976     })();
5977     if (ts.sys && ts.sys.getEnvironmentVariable) {
5978         setCustomPollingValues(ts.sys);
5979         ts.Debug.setAssertionLevel(/^development$/i.test(ts.sys.getEnvironmentVariable("NODE_ENV"))
5980             ? 1 /* Normal */
5981             : 0 /* None */);
5982     }
5983     if (ts.sys && ts.sys.debugMode) {
5984         ts.Debug.isDebugging = true;
5985     }
5986 })(ts || (ts = {}));
5987 /* @internal */
5988 var ts;
5989 (function (ts) {
5990     /**
5991      * Internally, we represent paths as strings with '/' as the directory separator.
5992      * When we make system calls (eg: LanguageServiceHost.getDirectory()),
5993      * we expect the host to correctly handle paths in our specified format.
5994      */
5995     ts.directorySeparator = "/";
5996     var altDirectorySeparator = "\\";
5997     var urlSchemeSeparator = "://";
5998     var backslashRegExp = /\\/g;
5999     //// Path Tests
6000     /**
6001      * Determines whether a charCode corresponds to `/` or `\`.
6002      */
6003     function isAnyDirectorySeparator(charCode) {
6004         return charCode === 47 /* slash */ || charCode === 92 /* backslash */;
6005     }
6006     ts.isAnyDirectorySeparator = isAnyDirectorySeparator;
6007     /**
6008      * Determines whether a path starts with a URL scheme (e.g. starts with `http://`, `ftp://`, `file://`, etc.).
6009      */
6010     function isUrl(path) {
6011         return getEncodedRootLength(path) < 0;
6012     }
6013     ts.isUrl = isUrl;
6014     /**
6015      * Determines whether a path is an absolute disk path (e.g. starts with `/`, or a dos path
6016      * like `c:`, `c:\` or `c:/`).
6017      */
6018     function isRootedDiskPath(path) {
6019         return getEncodedRootLength(path) > 0;
6020     }
6021     ts.isRootedDiskPath = isRootedDiskPath;
6022     /**
6023      * Determines whether a path consists only of a path root.
6024      */
6025     function isDiskPathRoot(path) {
6026         var rootLength = getEncodedRootLength(path);
6027         return rootLength > 0 && rootLength === path.length;
6028     }
6029     ts.isDiskPathRoot = isDiskPathRoot;
6030     /**
6031      * Determines whether a path starts with an absolute path component (i.e. `/`, `c:/`, `file://`, etc.).
6032      *
6033      * ```ts
6034      * // POSIX
6035      * pathIsAbsolute("/path/to/file.ext") === true
6036      * // DOS
6037      * pathIsAbsolute("c:/path/to/file.ext") === true
6038      * // URL
6039      * pathIsAbsolute("file:///path/to/file.ext") === true
6040      * // Non-absolute
6041      * pathIsAbsolute("path/to/file.ext") === false
6042      * pathIsAbsolute("./path/to/file.ext") === false
6043      * ```
6044      */
6045     function pathIsAbsolute(path) {
6046         return getEncodedRootLength(path) !== 0;
6047     }
6048     ts.pathIsAbsolute = pathIsAbsolute;
6049     /**
6050      * Determines whether a path starts with a relative path component (i.e. `.` or `..`).
6051      */
6052     function pathIsRelative(path) {
6053         return /^\.\.?($|[\\/])/.test(path);
6054     }
6055     ts.pathIsRelative = pathIsRelative;
6056     function hasExtension(fileName) {
6057         return ts.stringContains(getBaseFileName(fileName), ".");
6058     }
6059     ts.hasExtension = hasExtension;
6060     function fileExtensionIs(path, extension) {
6061         return path.length > extension.length && ts.endsWith(path, extension);
6062     }
6063     ts.fileExtensionIs = fileExtensionIs;
6064     function fileExtensionIsOneOf(path, extensions) {
6065         for (var _i = 0, extensions_1 = extensions; _i < extensions_1.length; _i++) {
6066             var extension = extensions_1[_i];
6067             if (fileExtensionIs(path, extension)) {
6068                 return true;
6069             }
6070         }
6071         return false;
6072     }
6073     ts.fileExtensionIsOneOf = fileExtensionIsOneOf;
6074     /**
6075      * Determines whether a path has a trailing separator (`/` or `\\`).
6076      */
6077     function hasTrailingDirectorySeparator(path) {
6078         return path.length > 0 && isAnyDirectorySeparator(path.charCodeAt(path.length - 1));
6079     }
6080     ts.hasTrailingDirectorySeparator = hasTrailingDirectorySeparator;
6081     //// Path Parsing
6082     function isVolumeCharacter(charCode) {
6083         return (charCode >= 97 /* a */ && charCode <= 122 /* z */) ||
6084             (charCode >= 65 /* A */ && charCode <= 90 /* Z */);
6085     }
6086     function getFileUrlVolumeSeparatorEnd(url, start) {
6087         var ch0 = url.charCodeAt(start);
6088         if (ch0 === 58 /* colon */)
6089             return start + 1;
6090         if (ch0 === 37 /* percent */ && url.charCodeAt(start + 1) === 51 /* _3 */) {
6091             var ch2 = url.charCodeAt(start + 2);
6092             if (ch2 === 97 /* a */ || ch2 === 65 /* A */)
6093                 return start + 3;
6094         }
6095         return -1;
6096     }
6097     /**
6098      * Returns length of the root part of a path or URL (i.e. length of "/", "x:/", "//server/share/, file:///user/files").
6099      * If the root is part of a URL, the twos-complement of the root length is returned.
6100      */
6101     function getEncodedRootLength(path) {
6102         if (!path)
6103             return 0;
6104         var ch0 = path.charCodeAt(0);
6105         // POSIX or UNC
6106         if (ch0 === 47 /* slash */ || ch0 === 92 /* backslash */) {
6107             if (path.charCodeAt(1) !== ch0)
6108                 return 1; // POSIX: "/" (or non-normalized "\")
6109             var p1 = path.indexOf(ch0 === 47 /* slash */ ? ts.directorySeparator : altDirectorySeparator, 2);
6110             if (p1 < 0)
6111                 return path.length; // UNC: "//server" or "\\server"
6112             return p1 + 1; // UNC: "//server/" or "\\server\"
6113         }
6114         // DOS
6115         if (isVolumeCharacter(ch0) && path.charCodeAt(1) === 58 /* colon */) {
6116             var ch2 = path.charCodeAt(2);
6117             if (ch2 === 47 /* slash */ || ch2 === 92 /* backslash */)
6118                 return 3; // DOS: "c:/" or "c:\"
6119             if (path.length === 2)
6120                 return 2; // DOS: "c:" (but not "c:d")
6121         }
6122         // URL
6123         var schemeEnd = path.indexOf(urlSchemeSeparator);
6124         if (schemeEnd !== -1) {
6125             var authorityStart = schemeEnd + urlSchemeSeparator.length;
6126             var authorityEnd = path.indexOf(ts.directorySeparator, authorityStart);
6127             if (authorityEnd !== -1) { // URL: "file:///", "file://server/", "file://server/path"
6128                 // For local "file" URLs, include the leading DOS volume (if present).
6129                 // Per https://www.ietf.org/rfc/rfc1738.txt, a host of "" or "localhost" is a
6130                 // special case interpreted as "the machine from which the URL is being interpreted".
6131                 var scheme = path.slice(0, schemeEnd);
6132                 var authority = path.slice(authorityStart, authorityEnd);
6133                 if (scheme === "file" && (authority === "" || authority === "localhost") &&
6134                     isVolumeCharacter(path.charCodeAt(authorityEnd + 1))) {
6135                     var volumeSeparatorEnd = getFileUrlVolumeSeparatorEnd(path, authorityEnd + 2);
6136                     if (volumeSeparatorEnd !== -1) {
6137                         if (path.charCodeAt(volumeSeparatorEnd) === 47 /* slash */) {
6138                             // URL: "file:///c:/", "file://localhost/c:/", "file:///c%3a/", "file://localhost/c%3a/"
6139                             return ~(volumeSeparatorEnd + 1);
6140                         }
6141                         if (volumeSeparatorEnd === path.length) {
6142                             // URL: "file:///c:", "file://localhost/c:", "file:///c$3a", "file://localhost/c%3a"
6143                             // but not "file:///c:d" or "file:///c%3ad"
6144                             return ~volumeSeparatorEnd;
6145                         }
6146                     }
6147                 }
6148                 return ~(authorityEnd + 1); // URL: "file://server/", "http://server/"
6149             }
6150             return ~path.length; // URL: "file://server", "http://server"
6151         }
6152         // relative
6153         return 0;
6154     }
6155     /**
6156      * Returns length of the root part of a path or URL (i.e. length of "/", "x:/", "//server/share/, file:///user/files").
6157      *
6158      * For example:
6159      * ```ts
6160      * getRootLength("a") === 0                   // ""
6161      * getRootLength("/") === 1                   // "/"
6162      * getRootLength("c:") === 2                  // "c:"
6163      * getRootLength("c:d") === 0                 // ""
6164      * getRootLength("c:/") === 3                 // "c:/"
6165      * getRootLength("c:\\") === 3                // "c:\\"
6166      * getRootLength("//server") === 7            // "//server"
6167      * getRootLength("//server/share") === 8      // "//server/"
6168      * getRootLength("\\\\server") === 7          // "\\\\server"
6169      * getRootLength("\\\\server\\share") === 8   // "\\\\server\\"
6170      * getRootLength("file:///path") === 8        // "file:///"
6171      * getRootLength("file:///c:") === 10         // "file:///c:"
6172      * getRootLength("file:///c:d") === 8         // "file:///"
6173      * getRootLength("file:///c:/path") === 11    // "file:///c:/"
6174      * getRootLength("file://server") === 13      // "file://server"
6175      * getRootLength("file://server/path") === 14 // "file://server/"
6176      * getRootLength("http://server") === 13      // "http://server"
6177      * getRootLength("http://server/path") === 14 // "http://server/"
6178      * ```
6179      */
6180     function getRootLength(path) {
6181         var rootLength = getEncodedRootLength(path);
6182         return rootLength < 0 ? ~rootLength : rootLength;
6183     }
6184     ts.getRootLength = getRootLength;
6185     function getDirectoryPath(path) {
6186         path = normalizeSlashes(path);
6187         // If the path provided is itself the root, then return it.
6188         var rootLength = getRootLength(path);
6189         if (rootLength === path.length)
6190             return path;
6191         // return the leading portion of the path up to the last (non-terminal) directory separator
6192         // but not including any trailing directory separator.
6193         path = removeTrailingDirectorySeparator(path);
6194         return path.slice(0, Math.max(rootLength, path.lastIndexOf(ts.directorySeparator)));
6195     }
6196     ts.getDirectoryPath = getDirectoryPath;
6197     function getBaseFileName(path, extensions, ignoreCase) {
6198         path = normalizeSlashes(path);
6199         // if the path provided is itself the root, then it has not file name.
6200         var rootLength = getRootLength(path);
6201         if (rootLength === path.length)
6202             return "";
6203         // return the trailing portion of the path starting after the last (non-terminal) directory
6204         // separator but not including any trailing directory separator.
6205         path = removeTrailingDirectorySeparator(path);
6206         var name = path.slice(Math.max(getRootLength(path), path.lastIndexOf(ts.directorySeparator) + 1));
6207         var extension = extensions !== undefined && ignoreCase !== undefined ? getAnyExtensionFromPath(name, extensions, ignoreCase) : undefined;
6208         return extension ? name.slice(0, name.length - extension.length) : name;
6209     }
6210     ts.getBaseFileName = getBaseFileName;
6211     function tryGetExtensionFromPath(path, extension, stringEqualityComparer) {
6212         if (!ts.startsWith(extension, "."))
6213             extension = "." + extension;
6214         if (path.length >= extension.length && path.charCodeAt(path.length - extension.length) === 46 /* dot */) {
6215             var pathExtension = path.slice(path.length - extension.length);
6216             if (stringEqualityComparer(pathExtension, extension)) {
6217                 return pathExtension;
6218             }
6219         }
6220     }
6221     function getAnyExtensionFromPathWorker(path, extensions, stringEqualityComparer) {
6222         if (typeof extensions === "string") {
6223             return tryGetExtensionFromPath(path, extensions, stringEqualityComparer) || "";
6224         }
6225         for (var _i = 0, extensions_2 = extensions; _i < extensions_2.length; _i++) {
6226             var extension = extensions_2[_i];
6227             var result = tryGetExtensionFromPath(path, extension, stringEqualityComparer);
6228             if (result)
6229                 return result;
6230         }
6231         return "";
6232     }
6233     function getAnyExtensionFromPath(path, extensions, ignoreCase) {
6234         // Retrieves any string from the final "." onwards from a base file name.
6235         // Unlike extensionFromPath, which throws an exception on unrecognized extensions.
6236         if (extensions) {
6237             return getAnyExtensionFromPathWorker(removeTrailingDirectorySeparator(path), extensions, ignoreCase ? ts.equateStringsCaseInsensitive : ts.equateStringsCaseSensitive);
6238         }
6239         var baseFileName = getBaseFileName(path);
6240         var extensionIndex = baseFileName.lastIndexOf(".");
6241         if (extensionIndex >= 0) {
6242             return baseFileName.substring(extensionIndex);
6243         }
6244         return "";
6245     }
6246     ts.getAnyExtensionFromPath = getAnyExtensionFromPath;
6247     function pathComponents(path, rootLength) {
6248         var root = path.substring(0, rootLength);
6249         var rest = path.substring(rootLength).split(ts.directorySeparator);
6250         if (rest.length && !ts.lastOrUndefined(rest))
6251             rest.pop();
6252         return __spreadArrays([root], rest);
6253     }
6254     /**
6255      * Parse a path into an array containing a root component (at index 0) and zero or more path
6256      * components (at indices > 0). The result is not normalized.
6257      * If the path is relative, the root component is `""`.
6258      * If the path is absolute, the root component includes the first path separator (`/`).
6259      *
6260      * ```ts
6261      * // POSIX
6262      * getPathComponents("/path/to/file.ext") === ["/", "path", "to", "file.ext"]
6263      * getPathComponents("/path/to/") === ["/", "path", "to"]
6264      * getPathComponents("/") === ["/"]
6265      * // DOS
6266      * getPathComponents("c:/path/to/file.ext") === ["c:/", "path", "to", "file.ext"]
6267      * getPathComponents("c:/path/to/") === ["c:/", "path", "to"]
6268      * getPathComponents("c:/") === ["c:/"]
6269      * getPathComponents("c:") === ["c:"]
6270      * // URL
6271      * getPathComponents("http://typescriptlang.org/path/to/file.ext") === ["http://typescriptlang.org/", "path", "to", "file.ext"]
6272      * getPathComponents("http://typescriptlang.org/path/to/") === ["http://typescriptlang.org/", "path", "to"]
6273      * getPathComponents("http://typescriptlang.org/") === ["http://typescriptlang.org/"]
6274      * getPathComponents("http://typescriptlang.org") === ["http://typescriptlang.org"]
6275      * getPathComponents("file://server/path/to/file.ext") === ["file://server/", "path", "to", "file.ext"]
6276      * getPathComponents("file://server/path/to/") === ["file://server/", "path", "to"]
6277      * getPathComponents("file://server/") === ["file://server/"]
6278      * getPathComponents("file://server") === ["file://server"]
6279      * getPathComponents("file:///path/to/file.ext") === ["file:///", "path", "to", "file.ext"]
6280      * getPathComponents("file:///path/to/") === ["file:///", "path", "to"]
6281      * getPathComponents("file:///") === ["file:///"]
6282      * getPathComponents("file://") === ["file://"]
6283      */
6284     function getPathComponents(path, currentDirectory) {
6285         if (currentDirectory === void 0) { currentDirectory = ""; }
6286         path = combinePaths(currentDirectory, path);
6287         return pathComponents(path, getRootLength(path));
6288     }
6289     ts.getPathComponents = getPathComponents;
6290     //// Path Formatting
6291     /**
6292      * Formats a parsed path consisting of a root component (at index 0) and zero or more path
6293      * segments (at indices > 0).
6294      *
6295      * ```ts
6296      * getPathFromPathComponents(["/", "path", "to", "file.ext"]) === "/path/to/file.ext"
6297      * ```
6298      */
6299     function getPathFromPathComponents(pathComponents) {
6300         if (pathComponents.length === 0)
6301             return "";
6302         var root = pathComponents[0] && ensureTrailingDirectorySeparator(pathComponents[0]);
6303         return root + pathComponents.slice(1).join(ts.directorySeparator);
6304     }
6305     ts.getPathFromPathComponents = getPathFromPathComponents;
6306     //// Path Normalization
6307     /**
6308      * Normalize path separators, converting `\` into `/`.
6309      */
6310     function normalizeSlashes(path) {
6311         return path.replace(backslashRegExp, ts.directorySeparator);
6312     }
6313     ts.normalizeSlashes = normalizeSlashes;
6314     /**
6315      * Reduce an array of path components to a more simplified path by navigating any
6316      * `"."` or `".."` entries in the path.
6317      */
6318     function reducePathComponents(components) {
6319         if (!ts.some(components))
6320             return [];
6321         var reduced = [components[0]];
6322         for (var i = 1; i < components.length; i++) {
6323             var component = components[i];
6324             if (!component)
6325                 continue;
6326             if (component === ".")
6327                 continue;
6328             if (component === "..") {
6329                 if (reduced.length > 1) {
6330                     if (reduced[reduced.length - 1] !== "..") {
6331                         reduced.pop();
6332                         continue;
6333                     }
6334                 }
6335                 else if (reduced[0])
6336                     continue;
6337             }
6338             reduced.push(component);
6339         }
6340         return reduced;
6341     }
6342     ts.reducePathComponents = reducePathComponents;
6343     /**
6344      * Combines paths. If a path is absolute, it replaces any previous path. Relative paths are not simplified.
6345      *
6346      * ```ts
6347      * // Non-rooted
6348      * combinePaths("path", "to", "file.ext") === "path/to/file.ext"
6349      * combinePaths("path", "dir", "..", "to", "file.ext") === "path/dir/../to/file.ext"
6350      * // POSIX
6351      * combinePaths("/path", "to", "file.ext") === "/path/to/file.ext"
6352      * combinePaths("/path", "/to", "file.ext") === "/to/file.ext"
6353      * // DOS
6354      * combinePaths("c:/path", "to", "file.ext") === "c:/path/to/file.ext"
6355      * combinePaths("c:/path", "c:/to", "file.ext") === "c:/to/file.ext"
6356      * // URL
6357      * combinePaths("file:///path", "to", "file.ext") === "file:///path/to/file.ext"
6358      * combinePaths("file:///path", "file:///to", "file.ext") === "file:///to/file.ext"
6359      * ```
6360      */
6361     function combinePaths(path) {
6362         var paths = [];
6363         for (var _i = 1; _i < arguments.length; _i++) {
6364             paths[_i - 1] = arguments[_i];
6365         }
6366         if (path)
6367             path = normalizeSlashes(path);
6368         for (var _a = 0, paths_1 = paths; _a < paths_1.length; _a++) {
6369             var relativePath = paths_1[_a];
6370             if (!relativePath)
6371                 continue;
6372             relativePath = normalizeSlashes(relativePath);
6373             if (!path || getRootLength(relativePath) !== 0) {
6374                 path = relativePath;
6375             }
6376             else {
6377                 path = ensureTrailingDirectorySeparator(path) + relativePath;
6378             }
6379         }
6380         return path;
6381     }
6382     ts.combinePaths = combinePaths;
6383     /**
6384      * Combines and resolves paths. If a path is absolute, it replaces any previous path. Any
6385      * `.` and `..` path components are resolved. Trailing directory separators are preserved.
6386      *
6387      * ```ts
6388      * resolvePath("/path", "to", "file.ext") === "path/to/file.ext"
6389      * resolvePath("/path", "to", "file.ext/") === "path/to/file.ext/"
6390      * resolvePath("/path", "dir", "..", "to", "file.ext") === "path/to/file.ext"
6391      * ```
6392      */
6393     function resolvePath(path) {
6394         var paths = [];
6395         for (var _i = 1; _i < arguments.length; _i++) {
6396             paths[_i - 1] = arguments[_i];
6397         }
6398         return normalizePath(ts.some(paths) ? combinePaths.apply(void 0, __spreadArrays([path], paths)) : normalizeSlashes(path));
6399     }
6400     ts.resolvePath = resolvePath;
6401     /**
6402      * Parse a path into an array containing a root component (at index 0) and zero or more path
6403      * components (at indices > 0). The result is normalized.
6404      * If the path is relative, the root component is `""`.
6405      * If the path is absolute, the root component includes the first path separator (`/`).
6406      *
6407      * ```ts
6408      * getNormalizedPathComponents("to/dir/../file.ext", "/path/") === ["/", "path", "to", "file.ext"]
6409      * ```
6410      */
6411     function getNormalizedPathComponents(path, currentDirectory) {
6412         return reducePathComponents(getPathComponents(path, currentDirectory));
6413     }
6414     ts.getNormalizedPathComponents = getNormalizedPathComponents;
6415     function getNormalizedAbsolutePath(fileName, currentDirectory) {
6416         return getPathFromPathComponents(getNormalizedPathComponents(fileName, currentDirectory));
6417     }
6418     ts.getNormalizedAbsolutePath = getNormalizedAbsolutePath;
6419     function normalizePath(path) {
6420         path = normalizeSlashes(path);
6421         var normalized = getPathFromPathComponents(reducePathComponents(getPathComponents(path)));
6422         return normalized && hasTrailingDirectorySeparator(path) ? ensureTrailingDirectorySeparator(normalized) : normalized;
6423     }
6424     ts.normalizePath = normalizePath;
6425     function getPathWithoutRoot(pathComponents) {
6426         if (pathComponents.length === 0)
6427             return "";
6428         return pathComponents.slice(1).join(ts.directorySeparator);
6429     }
6430     function getNormalizedAbsolutePathWithoutRoot(fileName, currentDirectory) {
6431         return getPathWithoutRoot(getNormalizedPathComponents(fileName, currentDirectory));
6432     }
6433     ts.getNormalizedAbsolutePathWithoutRoot = getNormalizedAbsolutePathWithoutRoot;
6434     function toPath(fileName, basePath, getCanonicalFileName) {
6435         var nonCanonicalizedPath = isRootedDiskPath(fileName)
6436             ? normalizePath(fileName)
6437             : getNormalizedAbsolutePath(fileName, basePath);
6438         return getCanonicalFileName(nonCanonicalizedPath);
6439     }
6440     ts.toPath = toPath;
6441     function normalizePathAndParts(path) {
6442         path = normalizeSlashes(path);
6443         var _a = reducePathComponents(getPathComponents(path)), root = _a[0], parts = _a.slice(1);
6444         if (parts.length) {
6445             var joinedParts = root + parts.join(ts.directorySeparator);
6446             return { path: hasTrailingDirectorySeparator(path) ? ensureTrailingDirectorySeparator(joinedParts) : joinedParts, parts: parts };
6447         }
6448         else {
6449             return { path: root, parts: parts };
6450         }
6451     }
6452     ts.normalizePathAndParts = normalizePathAndParts;
6453     function removeTrailingDirectorySeparator(path) {
6454         if (hasTrailingDirectorySeparator(path)) {
6455             return path.substr(0, path.length - 1);
6456         }
6457         return path;
6458     }
6459     ts.removeTrailingDirectorySeparator = removeTrailingDirectorySeparator;
6460     function ensureTrailingDirectorySeparator(path) {
6461         if (!hasTrailingDirectorySeparator(path)) {
6462             return path + ts.directorySeparator;
6463         }
6464         return path;
6465     }
6466     ts.ensureTrailingDirectorySeparator = ensureTrailingDirectorySeparator;
6467     /**
6468      * Ensures a path is either absolute (prefixed with `/` or `c:`) or dot-relative (prefixed
6469      * with `./` or `../`) so as not to be confused with an unprefixed module name.
6470      *
6471      * ```ts
6472      * ensurePathIsNonModuleName("/path/to/file.ext") === "/path/to/file.ext"
6473      * ensurePathIsNonModuleName("./path/to/file.ext") === "./path/to/file.ext"
6474      * ensurePathIsNonModuleName("../path/to/file.ext") === "../path/to/file.ext"
6475      * ensurePathIsNonModuleName("path/to/file.ext") === "./path/to/file.ext"
6476      * ```
6477      */
6478     function ensurePathIsNonModuleName(path) {
6479         return !pathIsAbsolute(path) && !pathIsRelative(path) ? "./" + path : path;
6480     }
6481     ts.ensurePathIsNonModuleName = ensurePathIsNonModuleName;
6482     function changeAnyExtension(path, ext, extensions, ignoreCase) {
6483         var pathext = extensions !== undefined && ignoreCase !== undefined ? getAnyExtensionFromPath(path, extensions, ignoreCase) : getAnyExtensionFromPath(path);
6484         return pathext ? path.slice(0, path.length - pathext.length) + (ts.startsWith(ext, ".") ? ext : "." + ext) : path;
6485     }
6486     ts.changeAnyExtension = changeAnyExtension;
6487     //// Path Comparisons
6488     // check path for these segments: '', '.'. '..'
6489     var relativePathSegmentRegExp = /(^|\/)\.{0,2}($|\/)/;
6490     function comparePathsWorker(a, b, componentComparer) {
6491         if (a === b)
6492             return 0 /* EqualTo */;
6493         if (a === undefined)
6494             return -1 /* LessThan */;
6495         if (b === undefined)
6496             return 1 /* GreaterThan */;
6497         // NOTE: Performance optimization - shortcut if the root segments differ as there would be no
6498         //       need to perform path reduction.
6499         var aRoot = a.substring(0, getRootLength(a));
6500         var bRoot = b.substring(0, getRootLength(b));
6501         var result = ts.compareStringsCaseInsensitive(aRoot, bRoot);
6502         if (result !== 0 /* EqualTo */) {
6503             return result;
6504         }
6505         // NOTE: Performance optimization - shortcut if there are no relative path segments in
6506         //       the non-root portion of the path
6507         var aRest = a.substring(aRoot.length);
6508         var bRest = b.substring(bRoot.length);
6509         if (!relativePathSegmentRegExp.test(aRest) && !relativePathSegmentRegExp.test(bRest)) {
6510             return componentComparer(aRest, bRest);
6511         }
6512         // The path contains a relative path segment. Normalize the paths and perform a slower component
6513         // by component comparison.
6514         var aComponents = reducePathComponents(getPathComponents(a));
6515         var bComponents = reducePathComponents(getPathComponents(b));
6516         var sharedLength = Math.min(aComponents.length, bComponents.length);
6517         for (var i = 1; i < sharedLength; i++) {
6518             var result_1 = componentComparer(aComponents[i], bComponents[i]);
6519             if (result_1 !== 0 /* EqualTo */) {
6520                 return result_1;
6521             }
6522         }
6523         return ts.compareValues(aComponents.length, bComponents.length);
6524     }
6525     /**
6526      * Performs a case-sensitive comparison of two paths. Path roots are always compared case-insensitively.
6527      */
6528     function comparePathsCaseSensitive(a, b) {
6529         return comparePathsWorker(a, b, ts.compareStringsCaseSensitive);
6530     }
6531     ts.comparePathsCaseSensitive = comparePathsCaseSensitive;
6532     /**
6533      * Performs a case-insensitive comparison of two paths.
6534      */
6535     function comparePathsCaseInsensitive(a, b) {
6536         return comparePathsWorker(a, b, ts.compareStringsCaseInsensitive);
6537     }
6538     ts.comparePathsCaseInsensitive = comparePathsCaseInsensitive;
6539     function comparePaths(a, b, currentDirectory, ignoreCase) {
6540         if (typeof currentDirectory === "string") {
6541             a = combinePaths(currentDirectory, a);
6542             b = combinePaths(currentDirectory, b);
6543         }
6544         else if (typeof currentDirectory === "boolean") {
6545             ignoreCase = currentDirectory;
6546         }
6547         return comparePathsWorker(a, b, ts.getStringComparer(ignoreCase));
6548     }
6549     ts.comparePaths = comparePaths;
6550     function containsPath(parent, child, currentDirectory, ignoreCase) {
6551         if (typeof currentDirectory === "string") {
6552             parent = combinePaths(currentDirectory, parent);
6553             child = combinePaths(currentDirectory, child);
6554         }
6555         else if (typeof currentDirectory === "boolean") {
6556             ignoreCase = currentDirectory;
6557         }
6558         if (parent === undefined || child === undefined)
6559             return false;
6560         if (parent === child)
6561             return true;
6562         var parentComponents = reducePathComponents(getPathComponents(parent));
6563         var childComponents = reducePathComponents(getPathComponents(child));
6564         if (childComponents.length < parentComponents.length) {
6565             return false;
6566         }
6567         var componentEqualityComparer = ignoreCase ? ts.equateStringsCaseInsensitive : ts.equateStringsCaseSensitive;
6568         for (var i = 0; i < parentComponents.length; i++) {
6569             var equalityComparer = i === 0 ? ts.equateStringsCaseInsensitive : componentEqualityComparer;
6570             if (!equalityComparer(parentComponents[i], childComponents[i])) {
6571                 return false;
6572             }
6573         }
6574         return true;
6575     }
6576     ts.containsPath = containsPath;
6577     /**
6578      * Determines whether `fileName` starts with the specified `directoryName` using the provided path canonicalization callback.
6579      * Comparison is case-sensitive between the canonical paths.
6580      *
6581      * @deprecated Use `containsPath` if possible.
6582      */
6583     function startsWithDirectory(fileName, directoryName, getCanonicalFileName) {
6584         var canonicalFileName = getCanonicalFileName(fileName);
6585         var canonicalDirectoryName = getCanonicalFileName(directoryName);
6586         return ts.startsWith(canonicalFileName, canonicalDirectoryName + "/") || ts.startsWith(canonicalFileName, canonicalDirectoryName + "\\");
6587     }
6588     ts.startsWithDirectory = startsWithDirectory;
6589     //// Relative Paths
6590     function getPathComponentsRelativeTo(from, to, stringEqualityComparer, getCanonicalFileName) {
6591         var fromComponents = reducePathComponents(getPathComponents(from));
6592         var toComponents = reducePathComponents(getPathComponents(to));
6593         var start;
6594         for (start = 0; start < fromComponents.length && start < toComponents.length; start++) {
6595             var fromComponent = getCanonicalFileName(fromComponents[start]);
6596             var toComponent = getCanonicalFileName(toComponents[start]);
6597             var comparer = start === 0 ? ts.equateStringsCaseInsensitive : stringEqualityComparer;
6598             if (!comparer(fromComponent, toComponent))
6599                 break;
6600         }
6601         if (start === 0) {
6602             return toComponents;
6603         }
6604         var components = toComponents.slice(start);
6605         var relative = [];
6606         for (; start < fromComponents.length; start++) {
6607             relative.push("..");
6608         }
6609         return __spreadArrays([""], relative, components);
6610     }
6611     ts.getPathComponentsRelativeTo = getPathComponentsRelativeTo;
6612     function getRelativePathFromDirectory(fromDirectory, to, getCanonicalFileNameOrIgnoreCase) {
6613         ts.Debug.assert((getRootLength(fromDirectory) > 0) === (getRootLength(to) > 0), "Paths must either both be absolute or both be relative");
6614         var getCanonicalFileName = typeof getCanonicalFileNameOrIgnoreCase === "function" ? getCanonicalFileNameOrIgnoreCase : ts.identity;
6615         var ignoreCase = typeof getCanonicalFileNameOrIgnoreCase === "boolean" ? getCanonicalFileNameOrIgnoreCase : false;
6616         var pathComponents = getPathComponentsRelativeTo(fromDirectory, to, ignoreCase ? ts.equateStringsCaseInsensitive : ts.equateStringsCaseSensitive, getCanonicalFileName);
6617         return getPathFromPathComponents(pathComponents);
6618     }
6619     ts.getRelativePathFromDirectory = getRelativePathFromDirectory;
6620     function convertToRelativePath(absoluteOrRelativePath, basePath, getCanonicalFileName) {
6621         return !isRootedDiskPath(absoluteOrRelativePath)
6622             ? absoluteOrRelativePath
6623             : getRelativePathToDirectoryOrUrl(basePath, absoluteOrRelativePath, basePath, getCanonicalFileName, /*isAbsolutePathAnUrl*/ false);
6624     }
6625     ts.convertToRelativePath = convertToRelativePath;
6626     function getRelativePathFromFile(from, to, getCanonicalFileName) {
6627         return ensurePathIsNonModuleName(getRelativePathFromDirectory(getDirectoryPath(from), to, getCanonicalFileName));
6628     }
6629     ts.getRelativePathFromFile = getRelativePathFromFile;
6630     function getRelativePathToDirectoryOrUrl(directoryPathOrUrl, relativeOrAbsolutePath, currentDirectory, getCanonicalFileName, isAbsolutePathAnUrl) {
6631         var pathComponents = getPathComponentsRelativeTo(resolvePath(currentDirectory, directoryPathOrUrl), resolvePath(currentDirectory, relativeOrAbsolutePath), ts.equateStringsCaseSensitive, getCanonicalFileName);
6632         var firstComponent = pathComponents[0];
6633         if (isAbsolutePathAnUrl && isRootedDiskPath(firstComponent)) {
6634             var prefix = firstComponent.charAt(0) === ts.directorySeparator ? "file://" : "file:///";
6635             pathComponents[0] = prefix + firstComponent;
6636         }
6637         return getPathFromPathComponents(pathComponents);
6638     }
6639     ts.getRelativePathToDirectoryOrUrl = getRelativePathToDirectoryOrUrl;
6640     function forEachAncestorDirectory(directory, callback) {
6641         while (true) {
6642             var result = callback(directory);
6643             if (result !== undefined) {
6644                 return result;
6645             }
6646             var parentPath = getDirectoryPath(directory);
6647             if (parentPath === directory) {
6648                 return undefined;
6649             }
6650             directory = parentPath;
6651         }
6652     }
6653     ts.forEachAncestorDirectory = forEachAncestorDirectory;
6654     function isNodeModulesDirectory(dirPath) {
6655         return ts.endsWith(dirPath, "/node_modules");
6656     }
6657     ts.isNodeModulesDirectory = isNodeModulesDirectory;
6658 })(ts || (ts = {}));
6659 // <auto-generated />
6660 // generated from './diagnosticInformationMap.generated.ts' by 'src/compiler'
6661 /* @internal */
6662 var ts;
6663 (function (ts) {
6664     function diag(code, category, key, message, reportsUnnecessary, elidedInCompatabilityPyramid) {
6665         return { code: code, category: category, key: key, message: message, reportsUnnecessary: reportsUnnecessary, elidedInCompatabilityPyramid: elidedInCompatabilityPyramid };
6666     }
6667     ts.Diagnostics = {
6668         Unterminated_string_literal: diag(1002, ts.DiagnosticCategory.Error, "Unterminated_string_literal_1002", "Unterminated string literal."),
6669         Identifier_expected: diag(1003, ts.DiagnosticCategory.Error, "Identifier_expected_1003", "Identifier expected."),
6670         _0_expected: diag(1005, ts.DiagnosticCategory.Error, "_0_expected_1005", "'{0}' expected."),
6671         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."),
6672         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."),
6673         Trailing_comma_not_allowed: diag(1009, ts.DiagnosticCategory.Error, "Trailing_comma_not_allowed_1009", "Trailing comma not allowed."),
6674         Asterisk_Slash_expected: diag(1010, ts.DiagnosticCategory.Error, "Asterisk_Slash_expected_1010", "'*/' expected."),
6675         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."),
6676         Unexpected_token: diag(1012, ts.DiagnosticCategory.Error, "Unexpected_token_1012", "Unexpected token."),
6677         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."),
6678         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."),
6679         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."),
6680         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."),
6681         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."),
6682         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."),
6683         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."),
6684         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."),
6685         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."),
6686         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."),
6687         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'."),
6688         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."),
6689         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."),
6690         Accessibility_modifier_already_seen: diag(1028, ts.DiagnosticCategory.Error, "Accessibility_modifier_already_seen_1028", "Accessibility modifier already seen."),
6691         _0_modifier_must_precede_1_modifier: diag(1029, ts.DiagnosticCategory.Error, "_0_modifier_must_precede_1_modifier_1029", "'{0}' modifier must precede '{1}' modifier."),
6692         _0_modifier_already_seen: diag(1030, ts.DiagnosticCategory.Error, "_0_modifier_already_seen_1030", "'{0}' modifier already seen."),
6693         _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."),
6694         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."),
6695         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."),
6696         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."),
6697         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."),
6698         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."),
6699         _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."),
6700         _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."),
6701         _0_modifier_cannot_be_used_here: diag(1042, ts.DiagnosticCategory.Error, "_0_modifier_cannot_be_used_here_1042", "'{0}' modifier cannot be used here."),
6702         _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."),
6703         _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."),
6704         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."),
6705         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."),
6706         A_rest_parameter_cannot_be_optional: diag(1047, ts.DiagnosticCategory.Error, "A_rest_parameter_cannot_be_optional_1047", "A rest parameter cannot be optional."),
6707         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."),
6708         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."),
6709         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."),
6710         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."),
6711         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."),
6712         A_get_accessor_cannot_have_parameters: diag(1054, ts.DiagnosticCategory.Error, "A_get_accessor_cannot_have_parameters_1054", "A 'get' accessor cannot have parameters."),
6713         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."),
6714         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."),
6715         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."),
6716         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."),
6717         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."),
6718         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."),
6719         Enum_member_must_have_initializer: diag(1061, ts.DiagnosticCategory.Error, "Enum_member_must_have_initializer_1061", "Enum member must have initializer."),
6720         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."),
6721         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."),
6722         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."),
6723         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."),
6724         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."),
6725         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."),
6726         _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."),
6727         _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."),
6728         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."),
6729         Invalid_reference_directive_syntax: diag(1084, ts.DiagnosticCategory.Error, "Invalid_reference_directive_syntax_1084", "Invalid 'reference' directive syntax."),
6730         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}'."),
6731         _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."),
6732         _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."),
6733         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."),
6734         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."),
6735         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."),
6736         An_accessor_cannot_have_type_parameters: diag(1094, ts.DiagnosticCategory.Error, "An_accessor_cannot_have_type_parameters_1094", "An accessor cannot have type parameters."),
6737         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."),
6738         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."),
6739         _0_list_cannot_be_empty: diag(1097, ts.DiagnosticCategory.Error, "_0_list_cannot_be_empty_1097", "'{0}' list cannot be empty."),
6740         Type_parameter_list_cannot_be_empty: diag(1098, ts.DiagnosticCategory.Error, "Type_parameter_list_cannot_be_empty_1098", "Type parameter list cannot be empty."),
6741         Type_argument_list_cannot_be_empty: diag(1099, ts.DiagnosticCategory.Error, "Type_argument_list_cannot_be_empty_1099", "Type argument list cannot be empty."),
6742         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."),
6743         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."),
6744         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."),
6745         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."),
6746         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."),
6747         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."),
6748         Jump_target_cannot_cross_function_boundary: diag(1107, ts.DiagnosticCategory.Error, "Jump_target_cannot_cross_function_boundary_1107", "Jump target cannot cross function boundary."),
6749         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."),
6750         Expression_expected: diag(1109, ts.DiagnosticCategory.Error, "Expression_expected_1109", "Expression expected."),
6751         Type_expected: diag(1110, ts.DiagnosticCategory.Error, "Type_expected_1110", "Type expected."),
6752         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."),
6753         Duplicate_label_0: diag(1114, ts.DiagnosticCategory.Error, "Duplicate_label_0_1114", "Duplicate label '{0}'."),
6754         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."),
6755         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."),
6756         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."),
6757         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."),
6758         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."),
6759         An_export_assignment_cannot_have_modifiers: diag(1120, ts.DiagnosticCategory.Error, "An_export_assignment_cannot_have_modifiers_1120", "An export assignment cannot have modifiers."),
6760         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."),
6761         Variable_declaration_list_cannot_be_empty: diag(1123, ts.DiagnosticCategory.Error, "Variable_declaration_list_cannot_be_empty_1123", "Variable declaration list cannot be empty."),
6762         Digit_expected: diag(1124, ts.DiagnosticCategory.Error, "Digit_expected_1124", "Digit expected."),
6763         Hexadecimal_digit_expected: diag(1125, ts.DiagnosticCategory.Error, "Hexadecimal_digit_expected_1125", "Hexadecimal digit expected."),
6764         Unexpected_end_of_text: diag(1126, ts.DiagnosticCategory.Error, "Unexpected_end_of_text_1126", "Unexpected end of text."),
6765         Invalid_character: diag(1127, ts.DiagnosticCategory.Error, "Invalid_character_1127", "Invalid character."),
6766         Declaration_or_statement_expected: diag(1128, ts.DiagnosticCategory.Error, "Declaration_or_statement_expected_1128", "Declaration or statement expected."),
6767         Statement_expected: diag(1129, ts.DiagnosticCategory.Error, "Statement_expected_1129", "Statement expected."),
6768         case_or_default_expected: diag(1130, ts.DiagnosticCategory.Error, "case_or_default_expected_1130", "'case' or 'default' expected."),
6769         Property_or_signature_expected: diag(1131, ts.DiagnosticCategory.Error, "Property_or_signature_expected_1131", "Property or signature expected."),
6770         Enum_member_expected: diag(1132, ts.DiagnosticCategory.Error, "Enum_member_expected_1132", "Enum member expected."),
6771         Variable_declaration_expected: diag(1134, ts.DiagnosticCategory.Error, "Variable_declaration_expected_1134", "Variable declaration expected."),
6772         Argument_expression_expected: diag(1135, ts.DiagnosticCategory.Error, "Argument_expression_expected_1135", "Argument expression expected."),
6773         Property_assignment_expected: diag(1136, ts.DiagnosticCategory.Error, "Property_assignment_expected_1136", "Property assignment expected."),
6774         Expression_or_comma_expected: diag(1137, ts.DiagnosticCategory.Error, "Expression_or_comma_expected_1137", "Expression or comma expected."),
6775         Parameter_declaration_expected: diag(1138, ts.DiagnosticCategory.Error, "Parameter_declaration_expected_1138", "Parameter declaration expected."),
6776         Type_parameter_declaration_expected: diag(1139, ts.DiagnosticCategory.Error, "Type_parameter_declaration_expected_1139", "Type parameter declaration expected."),
6777         Type_argument_expected: diag(1140, ts.DiagnosticCategory.Error, "Type_argument_expected_1140", "Type argument expected."),
6778         String_literal_expected: diag(1141, ts.DiagnosticCategory.Error, "String_literal_expected_1141", "String literal expected."),
6779         Line_break_not_permitted_here: diag(1142, ts.DiagnosticCategory.Error, "Line_break_not_permitted_here_1142", "Line break not permitted here."),
6780         or_expected: diag(1144, ts.DiagnosticCategory.Error, "or_expected_1144", "'{' or ';' expected."),
6781         Declaration_expected: diag(1146, ts.DiagnosticCategory.Error, "Declaration_expected_1146", "Declaration expected."),
6782         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."),
6783         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'."),
6784         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."),
6785         const_declarations_must_be_initialized: diag(1155, ts.DiagnosticCategory.Error, "const_declarations_must_be_initialized_1155", "'const' declarations must be initialized."),
6786         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."),
6787         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."),
6788         Unterminated_template_literal: diag(1160, ts.DiagnosticCategory.Error, "Unterminated_template_literal_1160", "Unterminated template literal."),
6789         Unterminated_regular_expression_literal: diag(1161, ts.DiagnosticCategory.Error, "Unterminated_regular_expression_literal_1161", "Unterminated regular expression literal."),
6790         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."),
6791         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."),
6792         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."),
6793         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."),
6794         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."),
6795         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."),
6796         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."),
6797         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."),
6798         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."),
6799         extends_clause_already_seen: diag(1172, ts.DiagnosticCategory.Error, "extends_clause_already_seen_1172", "'extends' clause already seen."),
6800         extends_clause_must_precede_implements_clause: diag(1173, ts.DiagnosticCategory.Error, "extends_clause_must_precede_implements_clause_1173", "'extends' clause must precede 'implements' clause."),
6801         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."),
6802         implements_clause_already_seen: diag(1175, ts.DiagnosticCategory.Error, "implements_clause_already_seen_1175", "'implements' clause already seen."),
6803         Interface_declaration_cannot_have_implements_clause: diag(1176, ts.DiagnosticCategory.Error, "Interface_declaration_cannot_have_implements_clause_1176", "Interface declaration cannot have 'implements' clause."),
6804         Binary_digit_expected: diag(1177, ts.DiagnosticCategory.Error, "Binary_digit_expected_1177", "Binary digit expected."),
6805         Octal_digit_expected: diag(1178, ts.DiagnosticCategory.Error, "Octal_digit_expected_1178", "Octal digit expected."),
6806         Unexpected_token_expected: diag(1179, ts.DiagnosticCategory.Error, "Unexpected_token_expected_1179", "Unexpected token. '{' expected."),
6807         Property_destructuring_pattern_expected: diag(1180, ts.DiagnosticCategory.Error, "Property_destructuring_pattern_expected_1180", "Property destructuring pattern expected."),
6808         Array_element_destructuring_pattern_expected: diag(1181, ts.DiagnosticCategory.Error, "Array_element_destructuring_pattern_expected_1181", "Array element destructuring pattern expected."),
6809         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."),
6810         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."),
6811         Modifiers_cannot_appear_here: diag(1184, ts.DiagnosticCategory.Error, "Modifiers_cannot_appear_here_1184", "Modifiers cannot appear here."),
6812         Merge_conflict_marker_encountered: diag(1185, ts.DiagnosticCategory.Error, "Merge_conflict_marker_encountered_1185", "Merge conflict marker encountered."),
6813         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."),
6814         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."),
6815         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."),
6816         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."),
6817         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."),
6818         An_import_declaration_cannot_have_modifiers: diag(1191, ts.DiagnosticCategory.Error, "An_import_declaration_cannot_have_modifiers_1191", "An import declaration cannot have modifiers."),
6819         Module_0_has_no_default_export: diag(1192, ts.DiagnosticCategory.Error, "Module_0_has_no_default_export_1192", "Module '{0}' has no default export."),
6820         An_export_declaration_cannot_have_modifiers: diag(1193, ts.DiagnosticCategory.Error, "An_export_declaration_cannot_have_modifiers_1193", "An export declaration cannot have modifiers."),
6821         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."),
6822         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."),
6823         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."),
6824         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."),
6825         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."),
6826         Unterminated_Unicode_escape_sequence: diag(1199, ts.DiagnosticCategory.Error, "Unterminated_Unicode_escape_sequence_1199", "Unterminated Unicode escape sequence."),
6827         Line_terminator_not_permitted_before_arrow: diag(1200, ts.DiagnosticCategory.Error, "Line_terminator_not_permitted_before_arrow_1200", "Line terminator not permitted before arrow."),
6828         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."),
6829         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."),
6830         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'."),
6831         Decorators_are_not_valid_here: diag(1206, ts.DiagnosticCategory.Error, "Decorators_are_not_valid_here_1206", "Decorators are not valid here."),
6832         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."),
6833         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."),
6834         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."),
6835         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."),
6836         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."),
6837         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."),
6838         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."),
6839         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."),
6840         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."),
6841         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'."),
6842         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."),
6843         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."),
6844         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."),
6845         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."),
6846         _0_tag_already_specified: diag(1223, ts.DiagnosticCategory.Error, "_0_tag_already_specified_1223", "'{0}' tag already specified."),
6847         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."),
6848         Cannot_find_parameter_0: diag(1225, ts.DiagnosticCategory.Error, "Cannot_find_parameter_0_1225", "Cannot find parameter '{0}'."),
6849         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}'."),
6850         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}'."),
6851         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."),
6852         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."),
6853         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."),
6854         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."),
6855         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."),
6856         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."),
6857         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."),
6858         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."),
6859         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'."),
6860         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'."),
6861         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."),
6862         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."),
6863         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."),
6864         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."),
6865         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."),
6866         _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."),
6867         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."),
6868         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."),
6869         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."),
6870         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."),
6871         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."),
6872         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."),
6873         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'."),
6874         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."),
6875         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."),
6876         _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."),
6877         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."),
6878         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."),
6879         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."),
6880         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."),
6881         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."),
6882         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"),
6883         Keywords_cannot_contain_escape_characters: diag(1260, ts.DiagnosticCategory.Error, "Keywords_cannot_contain_escape_characters_1260", "Keywords cannot contain escape characters."),
6884         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."),
6885         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."),
6886         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."),
6887         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."),
6888         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."),
6889         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."),
6890         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."),
6891         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."),
6892         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."),
6893         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."),
6894         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."),
6895         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."),
6896         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."),
6897         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."),
6898         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'."),
6899         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."),
6900         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."),
6901         Dynamic_import_cannot_have_type_arguments: diag(1326, ts.DiagnosticCategory.Error, "Dynamic_import_cannot_have_type_arguments_1326", "Dynamic import cannot have type arguments"),
6902         String_literal_with_double_quotes_expected: diag(1327, ts.DiagnosticCategory.Error, "String_literal_with_double_quotes_expected_1327", "String literal with double quotes expected."),
6903         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."),
6904         _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}()'?"),
6905         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'."),
6906         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'."),
6907         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'."),
6908         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."),
6909         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."),
6910         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."),
6911         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."),
6912         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."),
6913         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."),
6914         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."),
6915         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}')'?"),
6916         Type_arguments_cannot_be_used_here: diag(1342, ts.DiagnosticCategory.Error, "Type_arguments_cannot_be_used_here_1342", "Type arguments cannot be used here."),
6917         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'."),
6918         A_label_is_not_allowed_here: diag(1344, ts.DiagnosticCategory.Error, "A_label_is_not_allowed_here_1344", "'A label is not allowed here."),
6919         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"),
6920         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."),
6921         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."),
6922         Non_simple_parameter_declared_here: diag(1348, ts.DiagnosticCategory.Error, "Non_simple_parameter_declared_here_1348", "Non-simple parameter declared here."),
6923         use_strict_directive_used_here: diag(1349, ts.DiagnosticCategory.Error, "use_strict_directive_used_here_1349", "'use strict' directive used here."),
6924         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."),
6925         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."),
6926         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."),
6927         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."),
6928         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."),
6929         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."),
6930         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'?"),
6931         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 '}'."),
6932         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."),
6933         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."),
6934         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?"),
6935         _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'."),
6936         _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'."),
6937         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."),
6938         Convert_to_type_only_export: diag(1364, ts.DiagnosticCategory.Message, "Convert_to_type_only_export_1364", "Convert to type-only export"),
6939         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"),
6940         Split_into_two_separate_import_declarations: diag(1366, ts.DiagnosticCategory.Message, "Split_into_two_separate_import_declarations_1366", "Split into two separate import declarations"),
6941         Split_all_invalid_type_only_imports: diag(1367, ts.DiagnosticCategory.Message, "Split_all_invalid_type_only_imports_1367", "Split all invalid type-only imports"),
6942         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"),
6943         Did_you_mean_0: diag(1369, ts.DiagnosticCategory.Message, "Did_you_mean_0_1369", "Did you mean '{0}'?"),
6944         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'."),
6945         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'."),
6946         Convert_to_type_only_import: diag(1373, ts.DiagnosticCategory.Message, "Convert_to_type_only_import_1373", "Convert to type-only import"),
6947         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"),
6948         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."),
6949         _0_was_imported_here: diag(1376, ts.DiagnosticCategory.Message, "_0_was_imported_here_1376", "'{0}' was imported here."),
6950         _0_was_exported_here: diag(1377, ts.DiagnosticCategory.Message, "_0_was_exported_here_1377", "'{0}' was exported here."),
6951         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."),
6952         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'."),
6953         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'."),
6954         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;`?"),
6955         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;`?"),
6956         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'."),
6957         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."),
6958         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."),
6959         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."),
6960         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),
6961         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),
6962         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),
6963         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),
6964         Duplicate_identifier_0: diag(2300, ts.DiagnosticCategory.Error, "Duplicate_identifier_0_2300", "Duplicate identifier '{0}'."),
6965         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."),
6966         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."),
6967         Circular_definition_of_import_alias_0: diag(2303, ts.DiagnosticCategory.Error, "Circular_definition_of_import_alias_0_2303", "Circular definition of import alias '{0}'."),
6968         Cannot_find_name_0: diag(2304, ts.DiagnosticCategory.Error, "Cannot_find_name_0_2304", "Cannot find name '{0}'."),
6969         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}'."),
6970         File_0_is_not_a_module: diag(2306, ts.DiagnosticCategory.Error, "File_0_is_not_a_module_2306", "File '{0}' is not a module."),
6971         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."),
6972         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."),
6973         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."),
6974         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."),
6975         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."),
6976         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."),
6977         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."),
6978         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)."),
6979         Type_0_is_not_generic: diag(2315, ts.DiagnosticCategory.Error, "Type_0_is_not_generic_2315", "Type '{0}' is not generic."),
6980         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."),
6981         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)."),
6982         Cannot_find_global_type_0: diag(2318, ts.DiagnosticCategory.Error, "Cannot_find_global_type_0_2318", "Cannot find global type '{0}'."),
6983         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."),
6984         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}'."),
6985         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}'."),
6986         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}'."),
6987         Cannot_redeclare_exported_variable_0: diag(2323, ts.DiagnosticCategory.Error, "Cannot_redeclare_exported_variable_0_2323", "Cannot redeclare exported variable '{0}'."),
6988         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}'."),
6989         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}'."),
6990         Types_of_property_0_are_incompatible: diag(2326, ts.DiagnosticCategory.Error, "Types_of_property_0_are_incompatible_2326", "Types of property '{0}' are incompatible."),
6991         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}'."),
6992         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."),
6993         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}'."),
6994         Index_signatures_are_incompatible: diag(2330, ts.DiagnosticCategory.Error, "Index_signatures_are_incompatible_2330", "Index signatures are incompatible."),
6995         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."),
6996         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."),
6997         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."),
6998         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."),
6999         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."),
7000         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."),
7001         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."),
7002         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."),
7003         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}'."),
7004         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."),
7005         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}'."),
7006         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'."),
7007         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}'."),
7008         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}'."),
7009         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}'."),
7010         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."),
7011         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."),
7012         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'?"),
7013         This_expression_is_not_callable: diag(2349, ts.DiagnosticCategory.Error, "This_expression_is_not_callable_2349", "This expression is not callable."),
7014         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."),
7015         This_expression_is_not_constructable: diag(2351, ts.DiagnosticCategory.Error, "This_expression_is_not_constructable_2351", "This expression is not constructable."),
7016         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."),
7017         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}'."),
7018         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."),
7019         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."),
7020         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."),
7021         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."),
7022         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."),
7023         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."),
7024         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'."),
7025         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."),
7026         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."),
7027         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."),
7028         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."),
7029         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}'."),
7030         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'."),
7031         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."),
7032         Type_parameter_name_cannot_be_0: diag(2368, ts.DiagnosticCategory.Error, "Type_parameter_name_cannot_be_0_2368", "Type parameter name cannot be '{0}'."),
7033         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."),
7034         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."),
7035         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."),
7036         Parameter_0_cannot_reference_itself: diag(2372, ts.DiagnosticCategory.Error, "Parameter_0_cannot_reference_itself_2372", "Parameter '{0}' cannot reference itself."),
7037         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."),
7038         Duplicate_string_index_signature: diag(2374, ts.DiagnosticCategory.Error, "Duplicate_string_index_signature_2374", "Duplicate string index signature."),
7039         Duplicate_number_index_signature: diag(2375, ts.DiagnosticCategory.Error, "Duplicate_number_index_signature_2375", "Duplicate number index signature."),
7040         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."),
7041         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."),
7042         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."),
7043         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."),
7044         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."),
7045         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."),
7046         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."),
7047         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."),
7048         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."),
7049         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."),
7050         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."),
7051         Function_overload_must_be_static: diag(2387, ts.DiagnosticCategory.Error, "Function_overload_must_be_static_2387", "Function overload must be static."),
7052         Function_overload_must_not_be_static: diag(2388, ts.DiagnosticCategory.Error, "Function_overload_must_not_be_static_2388", "Function overload must not be static."),
7053         Function_implementation_name_must_be_0: diag(2389, ts.DiagnosticCategory.Error, "Function_implementation_name_must_be_0_2389", "Function implementation name must be '{0}'."),
7054         Constructor_implementation_is_missing: diag(2390, ts.DiagnosticCategory.Error, "Constructor_implementation_is_missing_2390", "Constructor implementation is missing."),
7055         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."),
7056         Multiple_constructor_implementations_are_not_allowed: diag(2392, ts.DiagnosticCategory.Error, "Multiple_constructor_implementations_are_not_allowed_2392", "Multiple constructor implementations are not allowed."),
7057         Duplicate_function_implementation: diag(2393, ts.DiagnosticCategory.Error, "Duplicate_function_implementation_2393", "Duplicate function implementation."),
7058         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."),
7059         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."),
7060         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."),
7061         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}'."),
7062         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."),
7063         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."),
7064         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."),
7065         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."),
7066         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."),
7067         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}'."),
7068         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."),
7069         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'."),
7070         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."),
7071         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}'."),
7072         Setters_cannot_return_a_value: diag(2408, ts.DiagnosticCategory.Error, "Setters_cannot_return_a_value_2408", "Setters cannot return a value."),
7073         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."),
7074         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'."),
7075         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}'."),
7076         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}'."),
7077         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}'."),
7078         Class_name_cannot_be_0: diag(2414, ts.DiagnosticCategory.Error, "Class_name_cannot_be_0_2414", "Class name cannot be '{0}'."),
7079         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}'."),
7080         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}'."),
7081         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}'."),
7082         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}'."),
7083         Class_0_incorrectly_implements_interface_1: diag(2420, ts.DiagnosticCategory.Error, "Class_0_incorrectly_implements_interface_1_2420", "Class '{0}' incorrectly implements interface '{1}'."),
7084         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."),
7085         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."),
7086         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."),
7087         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."),
7088         Interface_name_cannot_be_0: diag(2427, ts.DiagnosticCategory.Error, "Interface_name_cannot_be_0_2427", "Interface name cannot be '{0}'."),
7089         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."),
7090         Interface_0_incorrectly_extends_interface_1: diag(2430, ts.DiagnosticCategory.Error, "Interface_0_incorrectly_extends_interface_1_2430", "Interface '{0}' incorrectly extends interface '{1}'."),
7091         Enum_name_cannot_be_0: diag(2431, ts.DiagnosticCategory.Error, "Enum_name_cannot_be_0_2431", "Enum name cannot be '{0}'."),
7092         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."),
7093         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."),
7094         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."),
7095         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."),
7096         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."),
7097         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."),
7098         Import_name_cannot_be_0: diag(2438, ts.DiagnosticCategory.Error, "Import_name_cannot_be_0_2438", "Import name cannot be '{0}'."),
7099         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."),
7100         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}'."),
7101         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."),
7102         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}'."),
7103         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}'."),
7104         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}'."),
7105         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."),
7106         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}'."),
7107         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."),
7108         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."),
7109         Class_0_used_before_its_declaration: diag(2449, ts.DiagnosticCategory.Error, "Class_0_used_before_its_declaration_2449", "Class '{0}' used before its declaration."),
7110         Enum_0_used_before_its_declaration: diag(2450, ts.DiagnosticCategory.Error, "Enum_0_used_before_its_declaration_2450", "Enum '{0}' used before its declaration."),
7111         Cannot_redeclare_block_scoped_variable_0: diag(2451, ts.DiagnosticCategory.Error, "Cannot_redeclare_block_scoped_variable_0_2451", "Cannot redeclare block-scoped variable '{0}'."),
7112         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."),
7113         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."),
7114         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."),
7115         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}'."),
7116         Type_alias_0_circularly_references_itself: diag(2456, ts.DiagnosticCategory.Error, "Type_alias_0_circularly_references_itself_2456", "Type alias '{0}' circularly references itself."),
7117         Type_alias_name_cannot_be_0: diag(2457, ts.DiagnosticCategory.Error, "Type_alias_name_cannot_be_0_2457", "Type alias name cannot be '{0}'."),
7118         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."),
7119         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."),
7120         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}'."),
7121         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."),
7122         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."),
7123         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."),
7124         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'."),
7125         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."),
7126         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."),
7127         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."),
7128         Cannot_find_global_value_0: diag(2468, ts.DiagnosticCategory.Error, "Cannot_find_global_value_0_2468", "Cannot find global value '{0}'."),
7129         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'."),
7130         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."),
7131         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'."),
7132         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."),
7133         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."),
7134         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."),
7135         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."),
7136         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."),
7137         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."),
7138         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'."),
7139         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}'."),
7140         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."),
7141         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}'."),
7142         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."),
7143         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}'."),
7144         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."),
7145         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."),
7146         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."),
7147         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."),
7148         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."),
7149         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."),
7150         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}'."),
7151         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."),
7152         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."),
7153         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."),
7154         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."),
7155         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 *'."),
7156         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."),
7157         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."),
7158         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."),
7159         _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."),
7160         Cannot_find_namespace_0: diag(2503, ts.DiagnosticCategory.Error, "Cannot_find_namespace_0_2503", "Cannot find namespace '{0}'."),
7161         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."),
7162         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."),
7163         _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."),
7164         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."),
7165         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."),
7166         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."),
7167         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."),
7168         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."),
7169         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."),
7170         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."),
7171         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."),
7172         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}'."),
7173         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."),
7174         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."),
7175         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."),
7176         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."),
7177         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."),
7178         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."),
7179         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."),
7180         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."),
7181         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."),
7182         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."),
7183         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."),
7184         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."),
7185         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."),
7186         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."),
7187         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."),
7188         Object_is_possibly_null: diag(2531, ts.DiagnosticCategory.Error, "Object_is_possibly_null_2531", "Object is possibly 'null'."),
7189         Object_is_possibly_undefined: diag(2532, ts.DiagnosticCategory.Error, "Object_is_possibly_undefined_2532", "Object is possibly 'undefined'."),
7190         Object_is_possibly_null_or_undefined: diag(2533, ts.DiagnosticCategory.Error, "Object_is_possibly_null_or_undefined_2533", "Object is possibly 'null' or 'undefined'."),
7191         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."),
7192         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."),
7193         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}'."),
7194         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}'."),
7195         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."),
7196         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."),
7197         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."),
7198         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."),
7199         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."),
7200         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."),
7201         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."),
7202         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[]'."),
7203         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."),
7204         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."),
7205         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."),
7206         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}'?"),
7207         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}'?"),
7208         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."),
7209         Expected_0_arguments_but_got_1: diag(2554, ts.DiagnosticCategory.Error, "Expected_0_arguments_but_got_1_2554", "Expected {0} arguments, but got {1}."),
7210         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}."),
7211         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."),
7212         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."),
7213         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}."),
7214         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}'."),
7215         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?"),
7216         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}'?"),
7217         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."),
7218         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."),
7219         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."),
7220         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."),
7221         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."),
7222         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."),
7223         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."),
7224         Object_is_of_type_unknown: diag(2571, ts.DiagnosticCategory.Error, "Object_is_of_type_unknown_2571", "Object is of type 'unknown'."),
7225         Rest_signatures_are_incompatible: diag(2572, ts.DiagnosticCategory.Error, "Rest_signatures_are_incompatible_2572", "Rest signatures are incompatible."),
7226         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."),
7227         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."),
7228         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."),
7229         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}'"),
7230         Return_type_annotation_circularly_references_itself: diag(2577, ts.DiagnosticCategory.Error, "Return_type_annotation_circularly_references_itself_2577", "Return type annotation circularly references itself."),
7231         Unused_ts_expect_error_directive: diag(2578, ts.DiagnosticCategory.Error, "Unused_ts_expect_error_directive_2578", "Unused '@ts-expect-error' directive."),
7232         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`."),
7233         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`."),
7234         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`."),
7235         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."),
7236         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'."),
7237         _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."),
7238         Enum_type_0_circularly_references_itself: diag(2586, ts.DiagnosticCategory.Error, "Enum_type_0_circularly_references_itself_2586", "Enum type '{0}' circularly references itself."),
7239         JSDoc_type_0_circularly_references_itself: diag(2587, ts.DiagnosticCategory.Error, "JSDoc_type_0_circularly_references_itself_2587", "JSDoc type '{0}' circularly references itself."),
7240         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."),
7241         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."),
7242         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."),
7243         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."),
7244         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."),
7245         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."),
7246         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."),
7247         _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."),
7248         _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."),
7249         _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."),
7250         _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."),
7251         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."),
7252         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."),
7253         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."),
7254         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}'."),
7255         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."),
7256         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."),
7257         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."),
7258         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."),
7259         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."),
7260         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."),
7261         _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."),
7262         _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."),
7263         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."),
7264         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?"),
7265         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?"),
7266         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}'."),
7267         _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."),
7268         _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."),
7269         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."),
7270         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."),
7271         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."),
7272         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}'."),
7273         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."),
7274         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."),
7275         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."),
7276         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}'."),
7277         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."),
7278         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."),
7279         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."),
7280         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}'?"),
7281         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}'?"),
7282         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."),
7283         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."),
7284         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."),
7285         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."),
7286         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."),
7287         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."),
7288         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."),
7289         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."),
7290         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."),
7291         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."),
7292         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."),
7293         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."),
7294         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."),
7295         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."),
7296         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}'."),
7297         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'."),
7298         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."),
7299         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."),
7300         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."),
7301         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."),
7302         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}'."),
7303         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."),
7304         _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."),
7305         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."),
7306         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}'."),
7307         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'?"),
7308         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."),
7309         _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."),
7310         _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."),
7311         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}'."),
7312         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),
7313         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?"),
7314         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."),
7315         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."),
7316         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}'."),
7317         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."),
7318         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."),
7319         _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."),
7320         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."),
7321         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."),
7322         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."),
7323         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."),
7324         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."),
7325         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."),
7326         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."),
7327         _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."),
7328         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."),
7329         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."),
7330         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}\"]'?"),
7331         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."),
7332         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."),
7333         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."),
7334         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}'."),
7335         Duplicate_property_0: diag(2718, ts.DiagnosticCategory.Error, "Duplicate_property_0_2718", "Duplicate property '{0}'."),
7336         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."),
7337         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?"),
7338         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'."),
7339         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'."),
7340         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'."),
7341         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}'?"),
7342         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}."),
7343         Cannot_find_lib_definition_for_0: diag(2726, ts.DiagnosticCategory.Error, "Cannot_find_lib_definition_for_0_2726", "Cannot find lib definition for '{0}'."),
7344         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}'?"),
7345         _0_is_declared_here: diag(2728, ts.DiagnosticCategory.Message, "_0_is_declared_here_2728", "'{0}' is declared here."),
7346         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."),
7347         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."),
7348         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(...)'."),
7349         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"),
7350         Property_0_was_also_declared_here: diag(2733, ts.DiagnosticCategory.Error, "Property_0_was_also_declared_here_2733", "Property '{0}' was also declared here."),
7351         Are_you_missing_a_semicolon: diag(2734, ts.DiagnosticCategory.Error, "Are_you_missing_a_semicolon_2734", "Are you missing a semicolon?"),
7352         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}'?"),
7353         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}'."),
7354         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."),
7355         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."),
7356         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}"),
7357         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."),
7358         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}'."),
7359         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."),
7360         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."),
7361         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."),
7362         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."),
7363         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."),
7364         _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}'."),
7365         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."),
7366         _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}'?"),
7367         The_implementation_signature_is_declared_here: diag(2750, ts.DiagnosticCategory.Error, "The_implementation_signature_is_declared_here_2750", "The implementation signature is declared here."),
7368         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."),
7369         The_first_export_default_is_here: diag(2752, ts.DiagnosticCategory.Error, "The_first_export_default_is_here_2752", "The first export default is here."),
7370         Another_export_default_is_here: diag(2753, ts.DiagnosticCategory.Error, "Another_export_default_is_here_2753", "Another export default is here."),
7371         super_may_not_use_type_arguments: diag(2754, ts.DiagnosticCategory.Error, "super_may_not_use_type_arguments_2754", "'super' may not use type arguments."),
7372         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."),
7373         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."),
7374         Type_0_has_no_call_signatures: diag(2757, ts.DiagnosticCategory.Error, "Type_0_has_no_call_signatures_2757", "Type '{0}' has no call signatures."),
7375         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."),
7376         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."),
7377         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."),
7378         Type_0_has_no_construct_signatures: diag(2761, ts.DiagnosticCategory.Error, "Type_0_has_no_construct_signatures_2761", "Type '{0}' has no construct signatures."),
7379         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."),
7380         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}'."),
7381         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}'."),
7382         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}'."),
7383         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}'."),
7384         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."),
7385         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."),
7386         No_overload_matches_this_call: diag(2769, ts.DiagnosticCategory.Error, "No_overload_matches_this_call_2769", "No overload matches this call."),
7387         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."),
7388         The_last_overload_is_declared_here: diag(2771, ts.DiagnosticCategory.Error, "The_last_overload_is_declared_here_2771", "The last overload is declared here."),
7389         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."),
7390         Did_you_forget_to_use_await: diag(2773, ts.DiagnosticCategory.Error, "Did_you_forget_to_use_await_2773", "Did you forget to use 'await'?"),
7391         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?"),
7392         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."),
7393         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."),
7394         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."),
7395         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."),
7396         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."),
7397         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."),
7398         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."),
7399         _0_needs_an_explicit_type_annotation: diag(2782, ts.DiagnosticCategory.Message, "_0_needs_an_explicit_type_annotation_2782", "'{0}' needs an explicit type annotation."),
7400         _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."),
7401         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."),
7402         This_spread_always_overwrites_this_property: diag(2785, ts.DiagnosticCategory.Error, "This_spread_always_overwrites_this_property_2785", "This spread always overwrites this property."),
7403         _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."),
7404         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."),
7405         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."),
7406         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."),
7407         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}'."),
7408         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}'."),
7409         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}'."),
7410         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}'."),
7411         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}'."),
7412         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}'."),
7413         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}'."),
7414         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}'."),
7415         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}'."),
7416         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}'."),
7417         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}'."),
7418         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}'."),
7419         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."),
7420         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}'."),
7421         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}'."),
7422         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."),
7423         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}'."),
7424         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}'."),
7425         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."),
7426         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}'."),
7427         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}'."),
7428         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}'."),
7429         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}'."),
7430         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}'."),
7431         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}'."),
7432         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}'."),
7433         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}'."),
7434         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."),
7435         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}'."),
7436         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}'."),
7437         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."),
7438         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}'."),
7439         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}'."),
7440         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}'."),
7441         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}'."),
7442         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}'."),
7443         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}'."),
7444         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}'."),
7445         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}'."),
7446         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."),
7447         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}'."),
7448         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}'."),
7449         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."),
7450         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}'."),
7451         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}'."),
7452         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}'."),
7453         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}'."),
7454         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."),
7455         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}'."),
7456         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}'."),
7457         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."),
7458         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}'."),
7459         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}'."),
7460         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}'."),
7461         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}'."),
7462         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}'."),
7463         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}'."),
7464         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."),
7465         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}'."),
7466         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}'."),
7467         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."),
7468         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}'."),
7469         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}'."),
7470         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}'."),
7471         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}'."),
7472         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."),
7473         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}'."),
7474         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}'."),
7475         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}'."),
7476         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}'."),
7477         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}'."),
7478         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."),
7479         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}'."),
7480         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}'."),
7481         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."),
7482         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."),
7483         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}'."),
7484         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}'."),
7485         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."),
7486         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}'."),
7487         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}'."),
7488         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}'."),
7489         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}'."),
7490         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}'."),
7491         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}'."),
7492         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."),
7493         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}'."),
7494         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}'."),
7495         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."),
7496         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."),
7497         Tuple_type_arguments_circularly_reference_themselves: diag(4110, ts.DiagnosticCategory.Error, "Tuple_type_arguments_circularly_reference_themselves_4110", "Tuple type arguments circularly reference themselves."),
7498         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."),
7499         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."),
7500         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}'."),
7501         Cannot_read_file_0_Colon_1: diag(5012, ts.DiagnosticCategory.Error, "Cannot_read_file_0_Colon_1_5012", "Cannot read file '{0}': {1}."),
7502         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}."),
7503         Unknown_compiler_option_0: diag(5023, ts.DiagnosticCategory.Error, "Unknown_compiler_option_0_5023", "Unknown compiler option '{0}'."),
7504         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}."),
7505         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}'?"),
7506         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}."),
7507         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."),
7508         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."),
7509         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'."),
7510         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."),
7511         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}'."),
7512         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}'."),
7513         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}'."),
7514         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."),
7515         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."),
7516         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}'."),
7517         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}'."),
7518         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."),
7519         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."),
7520         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."),
7521         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."),
7522         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."),
7523         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}'."),
7524         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}'."),
7525         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."),
7526         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."),
7527         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."),
7528         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}'."),
7529         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."),
7530         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'."),
7531         Unknown_build_option_0: diag(5072, ts.DiagnosticCategory.Error, "Unknown_build_option_0_5072", "Unknown build option '{0}'."),
7532         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}."),
7533         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."),
7534         _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}'."),
7535         _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."),
7536         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}'?"),
7537         Unknown_watch_option_0: diag(5078, ts.DiagnosticCategory.Error, "Unknown_watch_option_0_5078", "Unknown watch option '{0}'."),
7538         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}'?"),
7539         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}."),
7540         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}."),
7541         _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}'."),
7542         Cannot_read_file_0: diag(5083, ts.DiagnosticCategory.Error, "Cannot_read_file_0_5083", "Cannot read file '{0}'."),
7543         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."),
7544         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."),
7545         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."),
7546         Generates_corresponding_d_ts_file: diag(6002, ts.DiagnosticCategory.Message, "Generates_corresponding_d_ts_file_6002", "Generates corresponding '.d.ts' file."),
7547         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."),
7548         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."),
7549         Watch_input_files: diag(6005, ts.DiagnosticCategory.Message, "Watch_input_files_6005", "Watch input files."),
7550         Redirect_output_structure_to_the_directory: diag(6006, ts.DiagnosticCategory.Message, "Redirect_output_structure_to_the_directory_6006", "Redirect output structure to the directory."),
7551         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."),
7552         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."),
7553         Do_not_emit_comments_to_output: diag(6009, ts.DiagnosticCategory.Message, "Do_not_emit_comments_to_output_6009", "Do not emit comments to output."),
7554         Do_not_emit_outputs: diag(6010, ts.DiagnosticCategory.Message, "Do_not_emit_outputs_6010", "Do not emit outputs."),
7555         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."),
7556         Skip_type_checking_of_declaration_files: diag(6012, ts.DiagnosticCategory.Message, "Skip_type_checking_of_declaration_files_6012", "Skip type checking of declaration files."),
7557         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."),
7558         Only_emit_d_ts_declaration_files: diag(6014, ts.DiagnosticCategory.Message, "Only_emit_d_ts_declaration_files_6014", "Only emit '.d.ts' declaration files."),
7559         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'."),
7560         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'."),
7561         Print_this_message: diag(6017, ts.DiagnosticCategory.Message, "Print_this_message_6017", "Print this message."),
7562         Print_the_compiler_s_version: diag(6019, ts.DiagnosticCategory.Message, "Print_the_compiler_s_version_6019", "Print the compiler's version."),
7563         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'."),
7564         Syntax_Colon_0: diag(6023, ts.DiagnosticCategory.Message, "Syntax_Colon_0_6023", "Syntax: {0}"),
7565         options: diag(6024, ts.DiagnosticCategory.Message, "options_6024", "options"),
7566         file: diag(6025, ts.DiagnosticCategory.Message, "file_6025", "file"),
7567         Examples_Colon_0: diag(6026, ts.DiagnosticCategory.Message, "Examples_Colon_0_6026", "Examples: {0}"),
7568         Options_Colon: diag(6027, ts.DiagnosticCategory.Message, "Options_Colon_6027", "Options:"),
7569         Version_0: diag(6029, ts.DiagnosticCategory.Message, "Version_0_6029", "Version {0}"),
7570         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."),
7571         Starting_compilation_in_watch_mode: diag(6031, ts.DiagnosticCategory.Message, "Starting_compilation_in_watch_mode_6031", "Starting compilation in watch mode..."),
7572         File_change_detected_Starting_incremental_compilation: diag(6032, ts.DiagnosticCategory.Message, "File_change_detected_Starting_incremental_compilation_6032", "File change detected. Starting incremental compilation..."),
7573         KIND: diag(6034, ts.DiagnosticCategory.Message, "KIND_6034", "KIND"),
7574         FILE: diag(6035, ts.DiagnosticCategory.Message, "FILE_6035", "FILE"),
7575         VERSION: diag(6036, ts.DiagnosticCategory.Message, "VERSION_6036", "VERSION"),
7576         LOCATION: diag(6037, ts.DiagnosticCategory.Message, "LOCATION_6037", "LOCATION"),
7577         DIRECTORY: diag(6038, ts.DiagnosticCategory.Message, "DIRECTORY_6038", "DIRECTORY"),
7578         STRATEGY: diag(6039, ts.DiagnosticCategory.Message, "STRATEGY_6039", "STRATEGY"),
7579         FILE_OR_DIRECTORY: diag(6040, ts.DiagnosticCategory.Message, "FILE_OR_DIRECTORY_6040", "FILE OR DIRECTORY"),
7580         Generates_corresponding_map_file: diag(6043, ts.DiagnosticCategory.Message, "Generates_corresponding_map_file_6043", "Generates corresponding '.map' file."),
7581         Compiler_option_0_expects_an_argument: diag(6044, ts.DiagnosticCategory.Error, "Compiler_option_0_expects_an_argument_6044", "Compiler option '{0}' expects an argument."),
7582         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}'."),
7583         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}."),
7584         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}'."),
7585         Unsupported_locale_0: diag(6049, ts.DiagnosticCategory.Error, "Unsupported_locale_0_6049", "Unsupported locale '{0}'."),
7586         Unable_to_open_file_0: diag(6050, ts.DiagnosticCategory.Error, "Unable_to_open_file_0_6050", "Unable to open file '{0}'."),
7587         Corrupted_locale_file_0: diag(6051, ts.DiagnosticCategory.Error, "Corrupted_locale_file_0_6051", "Corrupted locale file {0}."),
7588         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."),
7589         File_0_not_found: diag(6053, ts.DiagnosticCategory.Error, "File_0_not_found_6053", "File '{0}' not found."),
7590         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}."),
7591         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."),
7592         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."),
7593         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."),
7594         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."),
7595         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)."),
7596         NEWLINE: diag(6061, ts.DiagnosticCategory.Message, "NEWLINE_6061", "NEWLINE"),
7597         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."),
7598         Enables_experimental_support_for_ES7_decorators: diag(6065, ts.DiagnosticCategory.Message, "Enables_experimental_support_for_ES7_decorators_6065", "Enables experimental support for ES7 decorators."),
7599         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."),
7600         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."),
7601         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)."),
7602         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."),
7603         Successfully_created_a_tsconfig_json_file: diag(6071, ts.DiagnosticCategory.Message, "Successfully_created_a_tsconfig_json_file_6071", "Successfully created a tsconfig.json file."),
7604         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."),
7605         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)."),
7606         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."),
7607         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."),
7608         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."),
7609         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."),
7610         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."),
7611         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."),
7612         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'."),
7613         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."),
7614         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}."),
7615         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."),
7616         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"),
7617         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."),
7618         Resolving_module_0_from_1: diag(6086, ts.DiagnosticCategory.Message, "Resolving_module_0_from_1_6086", "======== Resolving module '{0}' from '{1}'. ========"),
7619         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}'."),
7620         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}'."),
7621         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}'. ========"),
7622         Module_name_0_was_not_resolved: diag(6090, ts.DiagnosticCategory.Message, "Module_name_0_was_not_resolved_6090", "======== Module name '{0}' was not resolved. ========"),
7623         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}'."),
7624         Module_name_0_matched_pattern_1: diag(6092, ts.DiagnosticCategory.Message, "Module_name_0_matched_pattern_1_6092", "Module name '{0}', matched pattern '{1}'."),
7625         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}'."),
7626         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}'."),
7627         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}'."),
7628         File_0_does_not_exist: diag(6096, ts.DiagnosticCategory.Message, "File_0_does_not_exist_6096", "File '{0}' does not exist."),
7629         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."),
7630         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}'."),
7631         Found_package_json_at_0: diag(6099, ts.DiagnosticCategory.Message, "Found_package_json_at_0_6099", "Found 'package.json' at '{0}'."),
7632         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."),
7633         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}'."),
7634         Allow_javascript_files_to_be_compiled: diag(6102, ts.DiagnosticCategory.Message, "Allow_javascript_files_to_be_compiled_6102", "Allow javascript files to be compiled."),
7635         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."),
7636         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}'."),
7637         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}'."),
7638         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}'."),
7639         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}'."),
7640         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}'."),
7641         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}'."),
7642         Trying_other_entries_in_rootDirs: diag(6110, ts.DiagnosticCategory.Message, "Trying_other_entries_in_rootDirs_6110", "Trying other entries in 'rootDirs'."),
7643         Module_resolution_using_rootDirs_has_failed: diag(6111, ts.DiagnosticCategory.Message, "Module_resolution_using_rootDirs_has_failed_6111", "Module resolution using 'rootDirs' has failed."),
7644         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."),
7645         Enable_strict_null_checks: diag(6113, ts.DiagnosticCategory.Message, "Enable_strict_null_checks_6113", "Enable strict null checks."),
7646         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'?"),
7647         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."),
7648         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}'. ========"),
7649         Resolving_using_primary_search_paths: diag(6117, ts.DiagnosticCategory.Message, "Resolving_using_primary_search_paths_6117", "Resolving using primary search paths..."),
7650         Resolving_from_node_modules_folder: diag(6118, ts.DiagnosticCategory.Message, "Resolving_from_node_modules_folder_6118", "Resolving from node_modules folder..."),
7651         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}. ========"),
7652         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. ========"),
7653         Resolving_with_primary_search_path_0: diag(6121, ts.DiagnosticCategory.Message, "Resolving_with_primary_search_path_0_6121", "Resolving with primary search path '{0}'."),
7654         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."),
7655         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. ========"),
7656         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."),
7657         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}'."),
7658         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."),
7659         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}'. ========"),
7660         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. ========"),
7661         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}'."),
7662         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'."),
7663         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."),
7664         _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),
7665         Report_errors_on_unused_locals: diag(6134, ts.DiagnosticCategory.Message, "Report_errors_on_unused_locals_6134", "Report errors on unused locals."),
7666         Report_errors_on_unused_parameters: diag(6135, ts.DiagnosticCategory.Message, "Report_errors_on_unused_parameters_6135", "Report errors on unused parameters."),
7667         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."),
7668         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}'."),
7669         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),
7670         Import_emit_helpers_from_tslib: diag(6139, ts.DiagnosticCategory.Message, "Import_emit_helpers_from_tslib_6139", "Import emit helpers from 'tslib'."),
7671         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}'."),
7672         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."),
7673         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."),
7674         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}'."),
7675         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."),
7676         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'."),
7677         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}'."),
7678         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."),
7679         Show_diagnostic_information: diag(6149, ts.DiagnosticCategory.Message, "Show_diagnostic_information_6149", "Show diagnostic information."),
7680         Show_verbose_diagnostic_information: diag(6150, ts.DiagnosticCategory.Message, "Show_verbose_diagnostic_information_6150", "Show verbose diagnostic information."),
7681         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."),
7682         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."),
7683         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')."),
7684         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."),
7685         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."),
7686         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')"),
7687         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."),
7688         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)."),
7689         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."),
7690         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."),
7691         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."),
7692         Disable_size_limitations_on_JavaScript_projects: diag(6162, ts.DiagnosticCategory.Message, "Disable_size_limitations_on_JavaScript_projects_6162", "Disable size limitations on JavaScript projects."),
7693         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."),
7694         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."),
7695         Do_not_truncate_error_messages: diag(6165, ts.DiagnosticCategory.Message, "Do_not_truncate_error_messages_6165", "Do not truncate error messages."),
7696         Output_directory_for_generated_declaration_files: diag(6166, ts.DiagnosticCategory.Message, "Output_directory_for_generated_declaration_files_6166", "Output directory for generated declaration files."),
7697         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'."),
7698         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."),
7699         Show_all_compiler_options: diag(6169, ts.DiagnosticCategory.Message, "Show_all_compiler_options_6169", "Show all compiler options."),
7700         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"),
7701         Command_line_Options: diag(6171, ts.DiagnosticCategory.Message, "Command_line_Options_6171", "Command-line Options"),
7702         Basic_Options: diag(6172, ts.DiagnosticCategory.Message, "Basic_Options_6172", "Basic Options"),
7703         Strict_Type_Checking_Options: diag(6173, ts.DiagnosticCategory.Message, "Strict_Type_Checking_Options_6173", "Strict Type-Checking Options"),
7704         Module_Resolution_Options: diag(6174, ts.DiagnosticCategory.Message, "Module_Resolution_Options_6174", "Module Resolution Options"),
7705         Source_Map_Options: diag(6175, ts.DiagnosticCategory.Message, "Source_Map_Options_6175", "Source Map Options"),
7706         Additional_Checks: diag(6176, ts.DiagnosticCategory.Message, "Additional_Checks_6176", "Additional Checks"),
7707         Experimental_Options: diag(6177, ts.DiagnosticCategory.Message, "Experimental_Options_6177", "Experimental Options"),
7708         Advanced_Options: diag(6178, ts.DiagnosticCategory.Message, "Advanced_Options_6178", "Advanced Options"),
7709         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'."),
7710         Enable_all_strict_type_checking_options: diag(6180, ts.DiagnosticCategory.Message, "Enable_all_strict_type_checking_options_6180", "Enable all strict type-checking options."),
7711         List_of_language_service_plugins: diag(6181, ts.DiagnosticCategory.Message, "List_of_language_service_plugins_6181", "List of language service plugins."),
7712         Scoped_package_detected_looking_in_0: diag(6182, ts.DiagnosticCategory.Message, "Scoped_package_detected_looking_in_0_6182", "Scoped package detected, looking in '{0}'"),
7713         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."),
7714         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."),
7715         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."),
7716         Enable_strict_checking_of_function_types: diag(6186, ts.DiagnosticCategory.Message, "Enable_strict_checking_of_function_types_6186", "Enable strict checking of function types."),
7717         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."),
7718         Numeric_separators_are_not_allowed_here: diag(6188, ts.DiagnosticCategory.Error, "Numeric_separators_are_not_allowed_here_6188", "Numeric separators are not allowed here."),
7719         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."),
7720         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."),
7721         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),
7722         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."),
7723         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."),
7724         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)."),
7725         _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),
7726         Include_modules_imported_with_json_extension: diag(6197, ts.DiagnosticCategory.Message, "Include_modules_imported_with_json_extension_6197", "Include modules imported with '.json' extension"),
7727         All_destructured_elements_are_unused: diag(6198, ts.DiagnosticCategory.Error, "All_destructured_elements_are_unused_6198", "All destructured elements are unused.", /*reportsUnnecessary*/ true),
7728         All_variables_are_unused: diag(6199, ts.DiagnosticCategory.Error, "All_variables_are_unused_6199", "All variables are unused.", /*reportsUnnecessary*/ true),
7729         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}"),
7730         Conflicts_are_in_this_file: diag(6201, ts.DiagnosticCategory.Message, "Conflicts_are_in_this_file_6201", "Conflicts are in this file."),
7731         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}"),
7732         _0_was_also_declared_here: diag(6203, ts.DiagnosticCategory.Message, "_0_was_also_declared_here_6203", "'{0}' was also declared here."),
7733         and_here: diag(6204, ts.DiagnosticCategory.Message, "and_here_6204", "and here."),
7734         All_type_parameters_are_unused: diag(6205, ts.DiagnosticCategory.Error, "All_type_parameters_are_unused_6205", "All type parameters are unused"),
7735         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."),
7736         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}'."),
7737         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}'."),
7738         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."),
7739         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."),
7740         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."),
7741         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?"),
7742         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?"),
7743         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."),
7744         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}'."),
7745         Found_1_error: diag(6216, ts.DiagnosticCategory.Message, "Found_1_error_6216", "Found 1 error."),
7746         Found_0_errors: diag(6217, ts.DiagnosticCategory.Message, "Found_0_errors_6217", "Found {0} errors."),
7747         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}'. ========"),
7748         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}. ========"),
7749         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."),
7750         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."),
7751         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."),
7752         Generates_a_CPU_profile: diag(6223, ts.DiagnosticCategory.Message, "Generates_a_CPU_profile_6223", "Generates a CPU profile."),
7753         Disable_solution_searching_for_this_project: diag(6224, ts.DiagnosticCategory.Message, "Disable_solution_searching_for_this_project_6224", "Disable solution searching for this project."),
7754         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'."),
7755         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'."),
7756         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'."),
7757         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."),
7758         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}'."),
7759         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."),
7760         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}."),
7761         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."),
7762         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."),
7763         Projects_to_reference: diag(6300, ts.DiagnosticCategory.Message, "Projects_to_reference_6300", "Projects to reference"),
7764         Enable_project_compilation: diag(6302, ts.DiagnosticCategory.Message, "Enable_project_compilation_6302", "Enable project compilation"),
7765         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."),
7766         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}'."),
7767         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."),
7768         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."),
7769         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"),
7770         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"),
7771         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}'"),
7772         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}'"),
7773         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"),
7774         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"),
7775         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"),
7776         Projects_in_this_build_Colon_0: diag(6355, ts.DiagnosticCategory.Message, "Projects_in_this_build_Colon_0_6355", "Projects in this build: {0}"),
7777         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}"),
7778         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}'"),
7779         Building_project_0: diag(6358, ts.DiagnosticCategory.Message, "Building_project_0_6358", "Building project '{0}'..."),
7780         Updating_output_timestamps_of_project_0: diag(6359, ts.DiagnosticCategory.Message, "Updating_output_timestamps_of_project_0_6359", "Updating output timestamps of project '{0}'..."),
7781         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"),
7782         Project_0_is_up_to_date: diag(6361, ts.DiagnosticCategory.Message, "Project_0_is_up_to_date_6361", "Project '{0}' is up to date"),
7783         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"),
7784         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"),
7785         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"),
7786         Delete_the_outputs_of_all_projects: diag(6365, ts.DiagnosticCategory.Message, "Delete_the_outputs_of_all_projects_6365", "Delete the outputs of all projects"),
7787         Enable_verbose_logging: diag(6366, ts.DiagnosticCategory.Message, "Enable_verbose_logging_6366", "Enable verbose logging"),
7788         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')"),
7789         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"),
7790         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."),
7791         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."),
7792         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}'..."),
7793         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"),
7794         Updating_output_of_project_0: diag(6373, ts.DiagnosticCategory.Message, "Updating_output_of_project_0_6373", "Updating output of project '{0}'..."),
7795         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}'"),
7796         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}'"),
7797         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}'"),
7798         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}'"),
7799         Enable_incremental_compilation: diag(6378, ts.DiagnosticCategory.Message, "Enable_incremental_compilation_6378", "Enable incremental compilation"),
7800         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."),
7801         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"),
7802         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}'"),
7803         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"),
7804         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"),
7805         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."),
7806         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}'"),
7807         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."),
7808         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."),
7809         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."),
7810         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?"),
7811         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."),
7812         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."),
7813         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."),
7814         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."),
7815         _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."),
7816         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."),
7817         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."),
7818         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."),
7819         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'."),
7820         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."),
7821         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."),
7822         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."),
7823         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."),
7824         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."),
7825         _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."),
7826         _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."),
7827         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."),
7828         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."),
7829         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."),
7830         Unreachable_code_detected: diag(7027, ts.DiagnosticCategory.Error, "Unreachable_code_detected_7027", "Unreachable code detected.", /*reportsUnnecessary*/ true),
7831         Unused_label: diag(7028, ts.DiagnosticCategory.Error, "Unused_label_7028", "Unused label.", /*reportsUnnecessary*/ true),
7832         Fallthrough_case_in_switch: diag(7029, ts.DiagnosticCategory.Error, "Fallthrough_case_in_switch_7029", "Fallthrough case in switch."),
7833         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."),
7834         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."),
7835         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."),
7836         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."),
7837         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."),
7838         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}';`"),
7839         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}'."),
7840         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'."),
7841         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."),
7842         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."),
7843         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}`"),
7844         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'."),
7845         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."),
7846         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."),
7847         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."),
7848         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."),
7849         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."),
7850         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."),
7851         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."),
7852         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."),
7853         _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."),
7854         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}'?"),
7855         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}'?"),
7856         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}'."),
7857         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}'."),
7858         _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."),
7859         You_cannot_rename_this_element: diag(8000, ts.DiagnosticCategory.Error, "You_cannot_rename_this_element_8000", "You cannot rename this element."),
7860         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."),
7861         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."),
7862         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."),
7863         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."),
7864         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."),
7865         _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."),
7866         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."),
7867         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."),
7868         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."),
7869         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."),
7870         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."),
7871         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."),
7872         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."),
7873         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}'."),
7874         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}'."),
7875         Report_errors_in_js_files: diag(8019, ts.DiagnosticCategory.Message, "Report_errors_in_js_files_8019", "Report errors in .js files."),
7876         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."),
7877         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."),
7878         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."),
7879         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."),
7880         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."),
7881         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."),
7882         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."),
7883         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."),
7884         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."),
7885         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."),
7886         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."),
7887         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."),
7888         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}'."),
7889         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."),
7890         class_expressions_are_not_currently_supported: diag(9003, ts.DiagnosticCategory.Error, "class_expressions_are_not_currently_supported_9003", "'class' expressions are not currently supported."),
7891         Language_service_is_disabled: diag(9004, ts.DiagnosticCategory.Error, "Language_service_is_disabled_9004", "Language service is disabled."),
7892         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."),
7893         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."),
7894         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'."),
7895         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."),
7896         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}'."),
7897         JSX_attribute_expected: diag(17003, ts.DiagnosticCategory.Error, "JSX_attribute_expected_17003", "JSX attribute expected."),
7898         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."),
7899         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'."),
7900         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."),
7901         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."),
7902         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."),
7903         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."),
7904         Unknown_type_acquisition_option_0: diag(17010, ts.DiagnosticCategory.Error, "Unknown_type_acquisition_option_0_17010", "Unknown type acquisition option '{0}'."),
7905         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."),
7906         _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}'?"),
7907         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."),
7908         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."),
7909         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."),
7910         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"),
7911         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"),
7912         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}'?"),
7913         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}"),
7914         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."),
7915         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."),
7916         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}'."),
7917         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."),
7918         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."),
7919         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."),
7920         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."),
7921         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."),
7922         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."),
7923         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."),
7924         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."),
7925         Add_missing_super_call: diag(90001, ts.DiagnosticCategory.Message, "Add_missing_super_call_90001", "Add missing 'super()' call"),
7926         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"),
7927         Change_extends_to_implements: diag(90003, ts.DiagnosticCategory.Message, "Change_extends_to_implements_90003", "Change 'extends' to 'implements'"),
7928         Remove_unused_declaration_for_Colon_0: diag(90004, ts.DiagnosticCategory.Message, "Remove_unused_declaration_for_Colon_0_90004", "Remove unused declaration for: '{0}'"),
7929         Remove_import_from_0: diag(90005, ts.DiagnosticCategory.Message, "Remove_import_from_0_90005", "Remove import from '{0}'"),
7930         Implement_interface_0: diag(90006, ts.DiagnosticCategory.Message, "Implement_interface_0_90006", "Implement interface '{0}'"),
7931         Implement_inherited_abstract_class: diag(90007, ts.DiagnosticCategory.Message, "Implement_inherited_abstract_class_90007", "Implement inherited abstract class"),
7932         Add_0_to_unresolved_variable: diag(90008, ts.DiagnosticCategory.Message, "Add_0_to_unresolved_variable_90008", "Add '{0}.' to unresolved variable"),
7933         Remove_destructuring: diag(90009, ts.DiagnosticCategory.Message, "Remove_destructuring_90009", "Remove destructuring"),
7934         Remove_variable_statement: diag(90010, ts.DiagnosticCategory.Message, "Remove_variable_statement_90010", "Remove variable statement"),
7935         Remove_template_tag: diag(90011, ts.DiagnosticCategory.Message, "Remove_template_tag_90011", "Remove template tag"),
7936         Remove_type_parameters: diag(90012, ts.DiagnosticCategory.Message, "Remove_type_parameters_90012", "Remove type parameters"),
7937         Import_0_from_module_1: diag(90013, ts.DiagnosticCategory.Message, "Import_0_from_module_1_90013", "Import '{0}' from module \"{1}\""),
7938         Change_0_to_1: diag(90014, ts.DiagnosticCategory.Message, "Change_0_to_1_90014", "Change '{0}' to '{1}'"),
7939         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}\""),
7940         Declare_property_0: diag(90016, ts.DiagnosticCategory.Message, "Declare_property_0_90016", "Declare property '{0}'"),
7941         Add_index_signature_for_property_0: diag(90017, ts.DiagnosticCategory.Message, "Add_index_signature_for_property_0_90017", "Add index signature for property '{0}'"),
7942         Disable_checking_for_this_file: diag(90018, ts.DiagnosticCategory.Message, "Disable_checking_for_this_file_90018", "Disable checking for this file"),
7943         Ignore_this_error_message: diag(90019, ts.DiagnosticCategory.Message, "Ignore_this_error_message_90019", "Ignore this error message"),
7944         Initialize_property_0_in_the_constructor: diag(90020, ts.DiagnosticCategory.Message, "Initialize_property_0_in_the_constructor_90020", "Initialize property '{0}' in the constructor"),
7945         Initialize_static_property_0: diag(90021, ts.DiagnosticCategory.Message, "Initialize_static_property_0_90021", "Initialize static property '{0}'"),
7946         Change_spelling_to_0: diag(90022, ts.DiagnosticCategory.Message, "Change_spelling_to_0_90022", "Change spelling to '{0}'"),
7947         Declare_method_0: diag(90023, ts.DiagnosticCategory.Message, "Declare_method_0_90023", "Declare method '{0}'"),
7948         Declare_static_method_0: diag(90024, ts.DiagnosticCategory.Message, "Declare_static_method_0_90024", "Declare static method '{0}'"),
7949         Prefix_0_with_an_underscore: diag(90025, ts.DiagnosticCategory.Message, "Prefix_0_with_an_underscore_90025", "Prefix '{0}' with an underscore"),
7950         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}'"),
7951         Declare_static_property_0: diag(90027, ts.DiagnosticCategory.Message, "Declare_static_property_0_90027", "Declare static property '{0}'"),
7952         Call_decorator_expression: diag(90028, ts.DiagnosticCategory.Message, "Call_decorator_expression_90028", "Call decorator expression"),
7953         Add_async_modifier_to_containing_function: diag(90029, ts.DiagnosticCategory.Message, "Add_async_modifier_to_containing_function_90029", "Add async modifier to containing function"),
7954         Replace_infer_0_with_unknown: diag(90030, ts.DiagnosticCategory.Message, "Replace_infer_0_with_unknown_90030", "Replace 'infer {0}' with 'unknown'"),
7955         Replace_all_unused_infer_with_unknown: diag(90031, ts.DiagnosticCategory.Message, "Replace_all_unused_infer_with_unknown_90031", "Replace all unused 'infer' with 'unknown'"),
7956         Import_default_0_from_module_1: diag(90032, ts.DiagnosticCategory.Message, "Import_default_0_from_module_1_90032", "Import default '{0}' from module \"{1}\""),
7957         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}\""),
7958         Add_parameter_name: diag(90034, ts.DiagnosticCategory.Message, "Add_parameter_name_90034", "Add parameter name"),
7959         Declare_private_property_0: diag(90035, ts.DiagnosticCategory.Message, "Declare_private_property_0_90035", "Declare private property '{0}'"),
7960         Declare_a_private_field_named_0: diag(90053, ts.DiagnosticCategory.Message, "Declare_a_private_field_named_0_90053", "Declare a private field named '{0}'."),
7961         Convert_function_to_an_ES2015_class: diag(95001, ts.DiagnosticCategory.Message, "Convert_function_to_an_ES2015_class_95001", "Convert function to an ES2015 class"),
7962         Convert_function_0_to_class: diag(95002, ts.DiagnosticCategory.Message, "Convert_function_0_to_class_95002", "Convert function '{0}' to class"),
7963         Extract_to_0_in_1: diag(95004, ts.DiagnosticCategory.Message, "Extract_to_0_in_1_95004", "Extract to {0} in {1}"),
7964         Extract_function: diag(95005, ts.DiagnosticCategory.Message, "Extract_function_95005", "Extract function"),
7965         Extract_constant: diag(95006, ts.DiagnosticCategory.Message, "Extract_constant_95006", "Extract constant"),
7966         Extract_to_0_in_enclosing_scope: diag(95007, ts.DiagnosticCategory.Message, "Extract_to_0_in_enclosing_scope_95007", "Extract to {0} in enclosing scope"),
7967         Extract_to_0_in_1_scope: diag(95008, ts.DiagnosticCategory.Message, "Extract_to_0_in_1_scope_95008", "Extract to {0} in {1} scope"),
7968         Annotate_with_type_from_JSDoc: diag(95009, ts.DiagnosticCategory.Message, "Annotate_with_type_from_JSDoc_95009", "Annotate with type from JSDoc"),
7969         Annotate_with_types_from_JSDoc: diag(95010, ts.DiagnosticCategory.Message, "Annotate_with_types_from_JSDoc_95010", "Annotate with types from JSDoc"),
7970         Infer_type_of_0_from_usage: diag(95011, ts.DiagnosticCategory.Message, "Infer_type_of_0_from_usage_95011", "Infer type of '{0}' from usage"),
7971         Infer_parameter_types_from_usage: diag(95012, ts.DiagnosticCategory.Message, "Infer_parameter_types_from_usage_95012", "Infer parameter types from usage"),
7972         Convert_to_default_import: diag(95013, ts.DiagnosticCategory.Message, "Convert_to_default_import_95013", "Convert to default import"),
7973         Install_0: diag(95014, ts.DiagnosticCategory.Message, "Install_0_95014", "Install '{0}'"),
7974         Replace_import_with_0: diag(95015, ts.DiagnosticCategory.Message, "Replace_import_with_0_95015", "Replace import with '{0}'."),
7975         Use_synthetic_default_member: diag(95016, ts.DiagnosticCategory.Message, "Use_synthetic_default_member_95016", "Use synthetic 'default' member."),
7976         Convert_to_ES6_module: diag(95017, ts.DiagnosticCategory.Message, "Convert_to_ES6_module_95017", "Convert to ES6 module"),
7977         Add_undefined_type_to_property_0: diag(95018, ts.DiagnosticCategory.Message, "Add_undefined_type_to_property_0_95018", "Add 'undefined' type to property '{0}'"),
7978         Add_initializer_to_property_0: diag(95019, ts.DiagnosticCategory.Message, "Add_initializer_to_property_0_95019", "Add initializer to property '{0}'"),
7979         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}'"),
7980         Add_all_missing_members: diag(95022, ts.DiagnosticCategory.Message, "Add_all_missing_members_95022", "Add all missing members"),
7981         Infer_all_types_from_usage: diag(95023, ts.DiagnosticCategory.Message, "Infer_all_types_from_usage_95023", "Infer all types from usage"),
7982         Delete_all_unused_declarations: diag(95024, ts.DiagnosticCategory.Message, "Delete_all_unused_declarations_95024", "Delete all unused declarations"),
7983         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"),
7984         Fix_all_detected_spelling_errors: diag(95026, ts.DiagnosticCategory.Message, "Fix_all_detected_spelling_errors_95026", "Fix all detected spelling errors"),
7985         Add_initializers_to_all_uninitialized_properties: diag(95027, ts.DiagnosticCategory.Message, "Add_initializers_to_all_uninitialized_properties_95027", "Add initializers to all uninitialized properties"),
7986         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"),
7987         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"),
7988         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"),
7989         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)"),
7990         Implement_all_unimplemented_interfaces: diag(95032, ts.DiagnosticCategory.Message, "Implement_all_unimplemented_interfaces_95032", "Implement all unimplemented interfaces"),
7991         Install_all_missing_types_packages: diag(95033, ts.DiagnosticCategory.Message, "Install_all_missing_types_packages_95033", "Install all missing types packages"),
7992         Rewrite_all_as_indexed_access_types: diag(95034, ts.DiagnosticCategory.Message, "Rewrite_all_as_indexed_access_types_95034", "Rewrite all as indexed access types"),
7993         Convert_all_to_default_imports: diag(95035, ts.DiagnosticCategory.Message, "Convert_all_to_default_imports_95035", "Convert all to default imports"),
7994         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"),
7995         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"),
7996         Change_all_extended_interfaces_to_implements: diag(95038, ts.DiagnosticCategory.Message, "Change_all_extended_interfaces_to_implements_95038", "Change all extended interfaces to 'implements'"),
7997         Add_all_missing_super_calls: diag(95039, ts.DiagnosticCategory.Message, "Add_all_missing_super_calls_95039", "Add all missing super calls"),
7998         Implement_all_inherited_abstract_classes: diag(95040, ts.DiagnosticCategory.Message, "Implement_all_inherited_abstract_classes_95040", "Implement all inherited abstract classes"),
7999         Add_all_missing_async_modifiers: diag(95041, ts.DiagnosticCategory.Message, "Add_all_missing_async_modifiers_95041", "Add all missing 'async' modifiers"),
8000         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"),
8001         Annotate_everything_with_types_from_JSDoc: diag(95043, ts.DiagnosticCategory.Message, "Annotate_everything_with_types_from_JSDoc_95043", "Annotate everything with types from JSDoc"),
8002         Add_to_all_uncalled_decorators: diag(95044, ts.DiagnosticCategory.Message, "Add_to_all_uncalled_decorators_95044", "Add '()' to all uncalled decorators"),
8003         Convert_all_constructor_functions_to_classes: diag(95045, ts.DiagnosticCategory.Message, "Convert_all_constructor_functions_to_classes_95045", "Convert all constructor functions to classes"),
8004         Generate_get_and_set_accessors: diag(95046, ts.DiagnosticCategory.Message, "Generate_get_and_set_accessors_95046", "Generate 'get' and 'set' accessors"),
8005         Convert_require_to_import: diag(95047, ts.DiagnosticCategory.Message, "Convert_require_to_import_95047", "Convert 'require' to 'import'"),
8006         Convert_all_require_to_import: diag(95048, ts.DiagnosticCategory.Message, "Convert_all_require_to_import_95048", "Convert all 'require' to 'import'"),
8007         Move_to_a_new_file: diag(95049, ts.DiagnosticCategory.Message, "Move_to_a_new_file_95049", "Move to a new file"),
8008         Remove_unreachable_code: diag(95050, ts.DiagnosticCategory.Message, "Remove_unreachable_code_95050", "Remove unreachable code"),
8009         Remove_all_unreachable_code: diag(95051, ts.DiagnosticCategory.Message, "Remove_all_unreachable_code_95051", "Remove all unreachable code"),
8010         Add_missing_typeof: diag(95052, ts.DiagnosticCategory.Message, "Add_missing_typeof_95052", "Add missing 'typeof'"),
8011         Remove_unused_label: diag(95053, ts.DiagnosticCategory.Message, "Remove_unused_label_95053", "Remove unused label"),
8012         Remove_all_unused_labels: diag(95054, ts.DiagnosticCategory.Message, "Remove_all_unused_labels_95054", "Remove all unused labels"),
8013         Convert_0_to_mapped_object_type: diag(95055, ts.DiagnosticCategory.Message, "Convert_0_to_mapped_object_type_95055", "Convert '{0}' to mapped object type"),
8014         Convert_namespace_import_to_named_imports: diag(95056, ts.DiagnosticCategory.Message, "Convert_namespace_import_to_named_imports_95056", "Convert namespace import to named imports"),
8015         Convert_named_imports_to_namespace_import: diag(95057, ts.DiagnosticCategory.Message, "Convert_named_imports_to_namespace_import_95057", "Convert named imports to namespace import"),
8016         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"),
8017         Add_braces_to_arrow_function: diag(95059, ts.DiagnosticCategory.Message, "Add_braces_to_arrow_function_95059", "Add braces to arrow function"),
8018         Remove_braces_from_arrow_function: diag(95060, ts.DiagnosticCategory.Message, "Remove_braces_from_arrow_function_95060", "Remove braces from arrow function"),
8019         Convert_default_export_to_named_export: diag(95061, ts.DiagnosticCategory.Message, "Convert_default_export_to_named_export_95061", "Convert default export to named export"),
8020         Convert_named_export_to_default_export: diag(95062, ts.DiagnosticCategory.Message, "Convert_named_export_to_default_export_95062", "Convert named export to default export"),
8021         Add_missing_enum_member_0: diag(95063, ts.DiagnosticCategory.Message, "Add_missing_enum_member_0_95063", "Add missing enum member '{0}'"),
8022         Add_all_missing_imports: diag(95064, ts.DiagnosticCategory.Message, "Add_all_missing_imports_95064", "Add all missing imports"),
8023         Convert_to_async_function: diag(95065, ts.DiagnosticCategory.Message, "Convert_to_async_function_95065", "Convert to async function"),
8024         Convert_all_to_async_functions: diag(95066, ts.DiagnosticCategory.Message, "Convert_all_to_async_functions_95066", "Convert all to async functions"),
8025         Add_missing_call_parentheses: diag(95067, ts.DiagnosticCategory.Message, "Add_missing_call_parentheses_95067", "Add missing call parentheses"),
8026         Add_all_missing_call_parentheses: diag(95068, ts.DiagnosticCategory.Message, "Add_all_missing_call_parentheses_95068", "Add all missing call parentheses"),
8027         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"),
8028         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"),
8029         Add_missing_new_operator_to_call: diag(95071, ts.DiagnosticCategory.Message, "Add_missing_new_operator_to_call_95071", "Add missing 'new' operator to call"),
8030         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"),
8031         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"),
8032         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"),
8033         Convert_parameters_to_destructured_object: diag(95075, ts.DiagnosticCategory.Message, "Convert_parameters_to_destructured_object_95075", "Convert parameters to destructured object"),
8034         Allow_accessing_UMD_globals_from_modules: diag(95076, ts.DiagnosticCategory.Message, "Allow_accessing_UMD_globals_from_modules_95076", "Allow accessing UMD globals from modules."),
8035         Extract_type: diag(95077, ts.DiagnosticCategory.Message, "Extract_type_95077", "Extract type"),
8036         Extract_to_type_alias: diag(95078, ts.DiagnosticCategory.Message, "Extract_to_type_alias_95078", "Extract to type alias"),
8037         Extract_to_typedef: diag(95079, ts.DiagnosticCategory.Message, "Extract_to_typedef_95079", "Extract to typedef"),
8038         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"),
8039         Add_const_to_unresolved_variable: diag(95081, ts.DiagnosticCategory.Message, "Add_const_to_unresolved_variable_95081", "Add 'const' to unresolved variable"),
8040         Add_const_to_all_unresolved_variables: diag(95082, ts.DiagnosticCategory.Message, "Add_const_to_all_unresolved_variables_95082", "Add 'const' to all unresolved variables"),
8041         Add_await: diag(95083, ts.DiagnosticCategory.Message, "Add_await_95083", "Add 'await'"),
8042         Add_await_to_initializer_for_0: diag(95084, ts.DiagnosticCategory.Message, "Add_await_to_initializer_for_0_95084", "Add 'await' to initializer for '{0}'"),
8043         Fix_all_expressions_possibly_missing_await: diag(95085, ts.DiagnosticCategory.Message, "Fix_all_expressions_possibly_missing_await_95085", "Fix all expressions possibly missing 'await'"),
8044         Remove_unnecessary_await: diag(95086, ts.DiagnosticCategory.Message, "Remove_unnecessary_await_95086", "Remove unnecessary 'await'"),
8045         Remove_all_unnecessary_uses_of_await: diag(95087, ts.DiagnosticCategory.Message, "Remove_all_unnecessary_uses_of_await_95087", "Remove all unnecessary uses of 'await'"),
8046         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"),
8047         Add_await_to_initializers: diag(95089, ts.DiagnosticCategory.Message, "Add_await_to_initializers_95089", "Add 'await' to initializers"),
8048         Extract_to_interface: diag(95090, ts.DiagnosticCategory.Message, "Extract_to_interface_95090", "Extract to interface"),
8049         Convert_to_a_bigint_numeric_literal: diag(95091, ts.DiagnosticCategory.Message, "Convert_to_a_bigint_numeric_literal_95091", "Convert to a bigint numeric literal"),
8050         Convert_all_to_bigint_numeric_literals: diag(95092, ts.DiagnosticCategory.Message, "Convert_all_to_bigint_numeric_literals_95092", "Convert all to bigint numeric literals"),
8051         Convert_const_to_let: diag(95093, ts.DiagnosticCategory.Message, "Convert_const_to_let_95093", "Convert 'const' to 'let'"),
8052         Prefix_with_declare: diag(95094, ts.DiagnosticCategory.Message, "Prefix_with_declare_95094", "Prefix with 'declare'"),
8053         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'"),
8054         Convert_to_template_string: diag(95096, ts.DiagnosticCategory.Message, "Convert_to_template_string_95096", "Convert to template string"),
8055         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"),
8056         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}'"),
8057         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}'"),
8058         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"),
8059         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"),
8060         Add_class_tag: diag(95102, ts.DiagnosticCategory.Message, "Add_class_tag_95102", "Add '@class' tag"),
8061         Add_this_tag: diag(95103, ts.DiagnosticCategory.Message, "Add_this_tag_95103", "Add '@this' tag"),
8062         Add_this_parameter: diag(95104, ts.DiagnosticCategory.Message, "Add_this_parameter_95104", "Add 'this' parameter."),
8063         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"),
8064         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"),
8065         Fix_all_implicit_this_errors: diag(95107, ts.DiagnosticCategory.Message, "Fix_all_implicit_this_errors_95107", "Fix all implicit-'this' errors"),
8066         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"),
8067         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"),
8068         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"),
8069         Add_a_return_statement: diag(95111, ts.DiagnosticCategory.Message, "Add_a_return_statement_95111", "Add a return statement"),
8070         Remove_block_body_braces: diag(95112, ts.DiagnosticCategory.Message, "Remove_block_body_braces_95112", "Remove block body braces"),
8071         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"),
8072         Add_all_missing_return_statement: diag(95114, ts.DiagnosticCategory.Message, "Add_all_missing_return_statement_95114", "Add all missing return statement"),
8073         Remove_all_incorrect_body_block_braces: diag(95115, ts.DiagnosticCategory.Message, "Remove_all_incorrect_body_block_braces_95115", "Remove all incorrect body block braces"),
8074         Wrap_all_object_literal_with_parentheses: diag(95116, ts.DiagnosticCategory.Message, "Wrap_all_object_literal_with_parentheses_95116", "Wrap all object literal with parentheses"),
8075         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."),
8076         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'."),
8077         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?"),
8078         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"),
8079         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."),
8080         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."),
8081         constructor_is_a_reserved_word: diag(18012, ts.DiagnosticCategory.Error, "constructor_is_a_reserved_word_18012", "'#constructor' is a reserved word."),
8082         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."),
8083         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."),
8084         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}'."),
8085         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."),
8086         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"),
8087         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"),
8088         _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"),
8089         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."),
8090         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."),
8091         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."),
8092         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."),
8093         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."),
8094         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."),
8095         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."),
8096         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."),
8097         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."),
8098         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."),
8099         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."),
8100     };
8101 })(ts || (ts = {}));
8102 var ts;
8103 (function (ts) {
8104     var _a;
8105     /* @internal */
8106     function tokenIsIdentifierOrKeyword(token) {
8107         return token >= 75 /* Identifier */;
8108     }
8109     ts.tokenIsIdentifierOrKeyword = tokenIsIdentifierOrKeyword;
8110     /* @internal */
8111     function tokenIsIdentifierOrKeywordOrGreaterThan(token) {
8112         return token === 31 /* GreaterThanToken */ || tokenIsIdentifierOrKeyword(token);
8113     }
8114     ts.tokenIsIdentifierOrKeywordOrGreaterThan = tokenIsIdentifierOrKeywordOrGreaterThan;
8115     var textToKeywordObj = (_a = {
8116             abstract: 122 /* AbstractKeyword */,
8117             any: 125 /* AnyKeyword */,
8118             as: 123 /* AsKeyword */,
8119             asserts: 124 /* AssertsKeyword */,
8120             bigint: 151 /* BigIntKeyword */,
8121             boolean: 128 /* BooleanKeyword */,
8122             break: 77 /* BreakKeyword */,
8123             case: 78 /* CaseKeyword */,
8124             catch: 79 /* CatchKeyword */,
8125             class: 80 /* ClassKeyword */,
8126             continue: 82 /* ContinueKeyword */,
8127             const: 81 /* ConstKeyword */
8128         },
8129         _a["" + "constructor"] = 129 /* ConstructorKeyword */,
8130         _a.debugger = 83 /* DebuggerKeyword */,
8131         _a.declare = 130 /* DeclareKeyword */,
8132         _a.default = 84 /* DefaultKeyword */,
8133         _a.delete = 85 /* DeleteKeyword */,
8134         _a.do = 86 /* DoKeyword */,
8135         _a.else = 87 /* ElseKeyword */,
8136         _a.enum = 88 /* EnumKeyword */,
8137         _a.export = 89 /* ExportKeyword */,
8138         _a.extends = 90 /* ExtendsKeyword */,
8139         _a.false = 91 /* FalseKeyword */,
8140         _a.finally = 92 /* FinallyKeyword */,
8141         _a.for = 93 /* ForKeyword */,
8142         _a.from = 149 /* FromKeyword */,
8143         _a.function = 94 /* FunctionKeyword */,
8144         _a.get = 131 /* GetKeyword */,
8145         _a.if = 95 /* IfKeyword */,
8146         _a.implements = 113 /* ImplementsKeyword */,
8147         _a.import = 96 /* ImportKeyword */,
8148         _a.in = 97 /* InKeyword */,
8149         _a.infer = 132 /* InferKeyword */,
8150         _a.instanceof = 98 /* InstanceOfKeyword */,
8151         _a.interface = 114 /* InterfaceKeyword */,
8152         _a.is = 133 /* IsKeyword */,
8153         _a.keyof = 134 /* KeyOfKeyword */,
8154         _a.let = 115 /* LetKeyword */,
8155         _a.module = 135 /* ModuleKeyword */,
8156         _a.namespace = 136 /* NamespaceKeyword */,
8157         _a.never = 137 /* NeverKeyword */,
8158         _a.new = 99 /* NewKeyword */,
8159         _a.null = 100 /* NullKeyword */,
8160         _a.number = 140 /* NumberKeyword */,
8161         _a.object = 141 /* ObjectKeyword */,
8162         _a.package = 116 /* PackageKeyword */,
8163         _a.private = 117 /* PrivateKeyword */,
8164         _a.protected = 118 /* ProtectedKeyword */,
8165         _a.public = 119 /* PublicKeyword */,
8166         _a.readonly = 138 /* ReadonlyKeyword */,
8167         _a.require = 139 /* RequireKeyword */,
8168         _a.global = 150 /* GlobalKeyword */,
8169         _a.return = 101 /* ReturnKeyword */,
8170         _a.set = 142 /* SetKeyword */,
8171         _a.static = 120 /* StaticKeyword */,
8172         _a.string = 143 /* StringKeyword */,
8173         _a.super = 102 /* SuperKeyword */,
8174         _a.switch = 103 /* SwitchKeyword */,
8175         _a.symbol = 144 /* SymbolKeyword */,
8176         _a.this = 104 /* ThisKeyword */,
8177         _a.throw = 105 /* ThrowKeyword */,
8178         _a.true = 106 /* TrueKeyword */,
8179         _a.try = 107 /* TryKeyword */,
8180         _a.type = 145 /* TypeKeyword */,
8181         _a.typeof = 108 /* TypeOfKeyword */,
8182         _a.undefined = 146 /* UndefinedKeyword */,
8183         _a.unique = 147 /* UniqueKeyword */,
8184         _a.unknown = 148 /* UnknownKeyword */,
8185         _a.var = 109 /* VarKeyword */,
8186         _a.void = 110 /* VoidKeyword */,
8187         _a.while = 111 /* WhileKeyword */,
8188         _a.with = 112 /* WithKeyword */,
8189         _a.yield = 121 /* YieldKeyword */,
8190         _a.async = 126 /* AsyncKeyword */,
8191         _a.await = 127 /* AwaitKeyword */,
8192         _a.of = 152 /* OfKeyword */,
8193         _a);
8194     var textToKeyword = ts.createMapFromTemplate(textToKeywordObj);
8195     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 */ }));
8196     /*
8197         As per ECMAScript Language Specification 3th Edition, Section 7.6: Identifiers
8198         IdentifierStart ::
8199             Can contain Unicode 3.0.0 categories:
8200             Uppercase letter (Lu),
8201             Lowercase letter (Ll),
8202             Titlecase letter (Lt),
8203             Modifier letter (Lm),
8204             Other letter (Lo), or
8205             Letter number (Nl).
8206         IdentifierPart :: =
8207             Can contain IdentifierStart + Unicode 3.0.0 categories:
8208             Non-spacing mark (Mn),
8209             Combining spacing mark (Mc),
8210             Decimal number (Nd), or
8211             Connector punctuation (Pc).
8212
8213         Codepoint ranges for ES3 Identifiers are extracted from the Unicode 3.0.0 specification at:
8214         http://www.unicode.org/Public/3.0-Update/UnicodeData-3.0.0.txt
8215     */
8216     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,];
8217     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,];
8218     /*
8219         As per ECMAScript Language Specification 5th Edition, Section 7.6: ISyntaxToken Names and Identifiers
8220         IdentifierStart ::
8221             Can contain Unicode 6.2 categories:
8222             Uppercase letter (Lu),
8223             Lowercase letter (Ll),
8224             Titlecase letter (Lt),
8225             Modifier letter (Lm),
8226             Other letter (Lo), or
8227             Letter number (Nl).
8228         IdentifierPart ::
8229             Can contain IdentifierStart + Unicode 6.2 categories:
8230             Non-spacing mark (Mn),
8231             Combining spacing mark (Mc),
8232             Decimal number (Nd),
8233             Connector punctuation (Pc),
8234             <ZWNJ>, or
8235             <ZWJ>.
8236
8237         Codepoint ranges for ES5 Identifiers are extracted from the Unicode 6.2 specification at:
8238         http://www.unicode.org/Public/6.2.0/ucd/UnicodeData.txt
8239     */
8240     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,];
8241     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,];
8242     /**
8243      * Generated by scripts/regenerate-unicode-identifier-parts.js on node v12.4.0 with unicode 12.1
8244      * based on http://www.unicode.org/reports/tr31/ and https://www.ecma-international.org/ecma-262/6.0/#sec-names-and-keywords
8245      * unicodeESNextIdentifierStart corresponds to the ID_Start and Other_ID_Start property, and
8246      * unicodeESNextIdentifierPart corresponds to ID_Continue, Other_ID_Continue, plus ID_Start and Other_ID_Start
8247      */
8248     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];
8249     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];
8250     /**
8251      * Test for whether a single line comment's text contains a directive.
8252      */
8253     var commentDirectiveRegExSingleLine = /^\s*\/\/\/?\s*@(ts-expect-error|ts-ignore)/;
8254     /**
8255      * Test for whether a multi-line comment's last line contains a directive.
8256      */
8257     var commentDirectiveRegExMultiLine = /^\s*(?:\/|\*)*\s*@(ts-expect-error|ts-ignore)/;
8258     function lookupInUnicodeMap(code, map) {
8259         // Bail out quickly if it couldn't possibly be in the map.
8260         if (code < map[0]) {
8261             return false;
8262         }
8263         // Perform binary search in one of the Unicode range maps
8264         var lo = 0;
8265         var hi = map.length;
8266         var mid;
8267         while (lo + 1 < hi) {
8268             mid = lo + (hi - lo) / 2;
8269             // mid has to be even to catch a range's beginning
8270             mid -= mid % 2;
8271             if (map[mid] <= code && code <= map[mid + 1]) {
8272                 return true;
8273             }
8274             if (code < map[mid]) {
8275                 hi = mid;
8276             }
8277             else {
8278                 lo = mid + 2;
8279             }
8280         }
8281         return false;
8282     }
8283     /* @internal */ function isUnicodeIdentifierStart(code, languageVersion) {
8284         return languageVersion >= 2 /* ES2015 */ ?
8285             lookupInUnicodeMap(code, unicodeESNextIdentifierStart) :
8286             languageVersion === 1 /* ES5 */ ? lookupInUnicodeMap(code, unicodeES5IdentifierStart) :
8287                 lookupInUnicodeMap(code, unicodeES3IdentifierStart);
8288     }
8289     ts.isUnicodeIdentifierStart = isUnicodeIdentifierStart;
8290     function isUnicodeIdentifierPart(code, languageVersion) {
8291         return languageVersion >= 2 /* ES2015 */ ?
8292             lookupInUnicodeMap(code, unicodeESNextIdentifierPart) :
8293             languageVersion === 1 /* ES5 */ ? lookupInUnicodeMap(code, unicodeES5IdentifierPart) :
8294                 lookupInUnicodeMap(code, unicodeES3IdentifierPart);
8295     }
8296     function makeReverseMap(source) {
8297         var result = [];
8298         source.forEach(function (value, name) {
8299             result[value] = name;
8300         });
8301         return result;
8302     }
8303     var tokenStrings = makeReverseMap(textToToken);
8304     function tokenToString(t) {
8305         return tokenStrings[t];
8306     }
8307     ts.tokenToString = tokenToString;
8308     /* @internal */
8309     function stringToToken(s) {
8310         return textToToken.get(s);
8311     }
8312     ts.stringToToken = stringToToken;
8313     /* @internal */
8314     function computeLineStarts(text) {
8315         var result = new Array();
8316         var pos = 0;
8317         var lineStart = 0;
8318         while (pos < text.length) {
8319             var ch = text.charCodeAt(pos);
8320             pos++;
8321             switch (ch) {
8322                 case 13 /* carriageReturn */:
8323                     if (text.charCodeAt(pos) === 10 /* lineFeed */) {
8324                         pos++;
8325                     }
8326                 // falls through
8327                 case 10 /* lineFeed */:
8328                     result.push(lineStart);
8329                     lineStart = pos;
8330                     break;
8331                 default:
8332                     if (ch > 127 /* maxAsciiCharacter */ && isLineBreak(ch)) {
8333                         result.push(lineStart);
8334                         lineStart = pos;
8335                     }
8336                     break;
8337             }
8338         }
8339         result.push(lineStart);
8340         return result;
8341     }
8342     ts.computeLineStarts = computeLineStarts;
8343     function getPositionOfLineAndCharacter(sourceFile, line, character, allowEdits) {
8344         return sourceFile.getPositionOfLineAndCharacter ?
8345             sourceFile.getPositionOfLineAndCharacter(line, character, allowEdits) :
8346             computePositionOfLineAndCharacter(getLineStarts(sourceFile), line, character, sourceFile.text, allowEdits);
8347     }
8348     ts.getPositionOfLineAndCharacter = getPositionOfLineAndCharacter;
8349     /* @internal */
8350     function computePositionOfLineAndCharacter(lineStarts, line, character, debugText, allowEdits) {
8351         if (line < 0 || line >= lineStarts.length) {
8352             if (allowEdits) {
8353                 // Clamp line to nearest allowable value
8354                 line = line < 0 ? 0 : line >= lineStarts.length ? lineStarts.length - 1 : line;
8355             }
8356             else {
8357                 ts.Debug.fail("Bad line number. Line: " + line + ", lineStarts.length: " + lineStarts.length + " , line map is correct? " + (debugText !== undefined ? ts.arraysEqual(lineStarts, computeLineStarts(debugText)) : "unknown"));
8358             }
8359         }
8360         var res = lineStarts[line] + character;
8361         if (allowEdits) {
8362             // Clamp to nearest allowable values to allow the underlying to be edited without crashing (accuracy is lost, instead)
8363             // TODO: Somehow track edits between file as it was during the creation of sourcemap we have and the current file and
8364             // apply them to the computed position to improve accuracy
8365             return res > lineStarts[line + 1] ? lineStarts[line + 1] : typeof debugText === "string" && res > debugText.length ? debugText.length : res;
8366         }
8367         if (line < lineStarts.length - 1) {
8368             ts.Debug.assert(res < lineStarts[line + 1]);
8369         }
8370         else if (debugText !== undefined) {
8371             ts.Debug.assert(res <= debugText.length); // Allow single character overflow for trailing newline
8372         }
8373         return res;
8374     }
8375     ts.computePositionOfLineAndCharacter = computePositionOfLineAndCharacter;
8376     /* @internal */
8377     function getLineStarts(sourceFile) {
8378         return sourceFile.lineMap || (sourceFile.lineMap = computeLineStarts(sourceFile.text));
8379     }
8380     ts.getLineStarts = getLineStarts;
8381     /* @internal */
8382     function computeLineAndCharacterOfPosition(lineStarts, position) {
8383         var lineNumber = computeLineOfPosition(lineStarts, position);
8384         return {
8385             line: lineNumber,
8386             character: position - lineStarts[lineNumber]
8387         };
8388     }
8389     ts.computeLineAndCharacterOfPosition = computeLineAndCharacterOfPosition;
8390     /**
8391      * @internal
8392      * We assume the first line starts at position 0 and 'position' is non-negative.
8393      */
8394     function computeLineOfPosition(lineStarts, position, lowerBound) {
8395         var lineNumber = ts.binarySearch(lineStarts, position, ts.identity, ts.compareValues, lowerBound);
8396         if (lineNumber < 0) {
8397             // If the actual position was not found,
8398             // the binary search returns the 2's-complement of the next line start
8399             // e.g. if the line starts at [5, 10, 23, 80] and the position requested was 20
8400             // then the search will return -2.
8401             //
8402             // We want the index of the previous line start, so we subtract 1.
8403             // Review 2's-complement if this is confusing.
8404             lineNumber = ~lineNumber - 1;
8405             ts.Debug.assert(lineNumber !== -1, "position cannot precede the beginning of the file");
8406         }
8407         return lineNumber;
8408     }
8409     ts.computeLineOfPosition = computeLineOfPosition;
8410     /** @internal */
8411     function getLinesBetweenPositions(sourceFile, pos1, pos2) {
8412         if (pos1 === pos2)
8413             return 0;
8414         var lineStarts = getLineStarts(sourceFile);
8415         var lower = Math.min(pos1, pos2);
8416         var isNegative = lower === pos2;
8417         var upper = isNegative ? pos1 : pos2;
8418         var lowerLine = computeLineOfPosition(lineStarts, lower);
8419         var upperLine = computeLineOfPosition(lineStarts, upper, lowerLine);
8420         return isNegative ? lowerLine - upperLine : upperLine - lowerLine;
8421     }
8422     ts.getLinesBetweenPositions = getLinesBetweenPositions;
8423     function getLineAndCharacterOfPosition(sourceFile, position) {
8424         return computeLineAndCharacterOfPosition(getLineStarts(sourceFile), position);
8425     }
8426     ts.getLineAndCharacterOfPosition = getLineAndCharacterOfPosition;
8427     function isWhiteSpaceLike(ch) {
8428         return isWhiteSpaceSingleLine(ch) || isLineBreak(ch);
8429     }
8430     ts.isWhiteSpaceLike = isWhiteSpaceLike;
8431     /** Does not include line breaks. For that, see isWhiteSpaceLike. */
8432     function isWhiteSpaceSingleLine(ch) {
8433         // Note: nextLine is in the Zs space, and should be considered to be a whitespace.
8434         // It is explicitly not a line-break as it isn't in the exact set specified by EcmaScript.
8435         return ch === 32 /* space */ ||
8436             ch === 9 /* tab */ ||
8437             ch === 11 /* verticalTab */ ||
8438             ch === 12 /* formFeed */ ||
8439             ch === 160 /* nonBreakingSpace */ ||
8440             ch === 133 /* nextLine */ ||
8441             ch === 5760 /* ogham */ ||
8442             ch >= 8192 /* enQuad */ && ch <= 8203 /* zeroWidthSpace */ ||
8443             ch === 8239 /* narrowNoBreakSpace */ ||
8444             ch === 8287 /* mathematicalSpace */ ||
8445             ch === 12288 /* ideographicSpace */ ||
8446             ch === 65279 /* byteOrderMark */;
8447     }
8448     ts.isWhiteSpaceSingleLine = isWhiteSpaceSingleLine;
8449     function isLineBreak(ch) {
8450         // ES5 7.3:
8451         // The ECMAScript line terminator characters are listed in Table 3.
8452         //     Table 3: Line Terminator Characters
8453         //     Code Unit Value     Name                    Formal Name
8454         //     \u000A              Line Feed               <LF>
8455         //     \u000D              Carriage Return         <CR>
8456         //     \u2028              Line separator          <LS>
8457         //     \u2029              Paragraph separator     <PS>
8458         // Only the characters in Table 3 are treated as line terminators. Other new line or line
8459         // breaking characters are treated as white space but not as line terminators.
8460         return ch === 10 /* lineFeed */ ||
8461             ch === 13 /* carriageReturn */ ||
8462             ch === 8232 /* lineSeparator */ ||
8463             ch === 8233 /* paragraphSeparator */;
8464     }
8465     ts.isLineBreak = isLineBreak;
8466     function isDigit(ch) {
8467         return ch >= 48 /* _0 */ && ch <= 57 /* _9 */;
8468     }
8469     function isHexDigit(ch) {
8470         return isDigit(ch) || ch >= 65 /* A */ && ch <= 70 /* F */ || ch >= 97 /* a */ && ch <= 102 /* f */;
8471     }
8472     function isCodePoint(code) {
8473         return code <= 0x10FFFF;
8474     }
8475     /* @internal */
8476     function isOctalDigit(ch) {
8477         return ch >= 48 /* _0 */ && ch <= 55 /* _7 */;
8478     }
8479     ts.isOctalDigit = isOctalDigit;
8480     function couldStartTrivia(text, pos) {
8481         // Keep in sync with skipTrivia
8482         var ch = text.charCodeAt(pos);
8483         switch (ch) {
8484             case 13 /* carriageReturn */:
8485             case 10 /* lineFeed */:
8486             case 9 /* tab */:
8487             case 11 /* verticalTab */:
8488             case 12 /* formFeed */:
8489             case 32 /* space */:
8490             case 47 /* slash */:
8491             // starts of normal trivia
8492             // falls through
8493             case 60 /* lessThan */:
8494             case 124 /* bar */:
8495             case 61 /* equals */:
8496             case 62 /* greaterThan */:
8497                 // Starts of conflict marker trivia
8498                 return true;
8499             case 35 /* hash */:
8500                 // Only if its the beginning can we have #! trivia
8501                 return pos === 0;
8502             default:
8503                 return ch > 127 /* maxAsciiCharacter */;
8504         }
8505     }
8506     ts.couldStartTrivia = couldStartTrivia;
8507     /* @internal */
8508     function skipTrivia(text, pos, stopAfterLineBreak, stopAtComments) {
8509         if (stopAtComments === void 0) { stopAtComments = false; }
8510         if (ts.positionIsSynthesized(pos)) {
8511             return pos;
8512         }
8513         // Keep in sync with couldStartTrivia
8514         while (true) {
8515             var ch = text.charCodeAt(pos);
8516             switch (ch) {
8517                 case 13 /* carriageReturn */:
8518                     if (text.charCodeAt(pos + 1) === 10 /* lineFeed */) {
8519                         pos++;
8520                     }
8521                 // falls through
8522                 case 10 /* lineFeed */:
8523                     pos++;
8524                     if (stopAfterLineBreak) {
8525                         return pos;
8526                     }
8527                     continue;
8528                 case 9 /* tab */:
8529                 case 11 /* verticalTab */:
8530                 case 12 /* formFeed */:
8531                 case 32 /* space */:
8532                     pos++;
8533                     continue;
8534                 case 47 /* slash */:
8535                     if (stopAtComments) {
8536                         break;
8537                     }
8538                     if (text.charCodeAt(pos + 1) === 47 /* slash */) {
8539                         pos += 2;
8540                         while (pos < text.length) {
8541                             if (isLineBreak(text.charCodeAt(pos))) {
8542                                 break;
8543                             }
8544                             pos++;
8545                         }
8546                         continue;
8547                     }
8548                     if (text.charCodeAt(pos + 1) === 42 /* asterisk */) {
8549                         pos += 2;
8550                         while (pos < text.length) {
8551                             if (text.charCodeAt(pos) === 42 /* asterisk */ && text.charCodeAt(pos + 1) === 47 /* slash */) {
8552                                 pos += 2;
8553                                 break;
8554                             }
8555                             pos++;
8556                         }
8557                         continue;
8558                     }
8559                     break;
8560                 case 60 /* lessThan */:
8561                 case 124 /* bar */:
8562                 case 61 /* equals */:
8563                 case 62 /* greaterThan */:
8564                     if (isConflictMarkerTrivia(text, pos)) {
8565                         pos = scanConflictMarkerTrivia(text, pos);
8566                         continue;
8567                     }
8568                     break;
8569                 case 35 /* hash */:
8570                     if (pos === 0 && isShebangTrivia(text, pos)) {
8571                         pos = scanShebangTrivia(text, pos);
8572                         continue;
8573                     }
8574                     break;
8575                 default:
8576                     if (ch > 127 /* maxAsciiCharacter */ && (isWhiteSpaceLike(ch))) {
8577                         pos++;
8578                         continue;
8579                     }
8580                     break;
8581             }
8582             return pos;
8583         }
8584     }
8585     ts.skipTrivia = skipTrivia;
8586     // All conflict markers consist of the same character repeated seven times.  If it is
8587     // a <<<<<<< or >>>>>>> marker then it is also followed by a space.
8588     var mergeConflictMarkerLength = "<<<<<<<".length;
8589     function isConflictMarkerTrivia(text, pos) {
8590         ts.Debug.assert(pos >= 0);
8591         // Conflict markers must be at the start of a line.
8592         if (pos === 0 || isLineBreak(text.charCodeAt(pos - 1))) {
8593             var ch = text.charCodeAt(pos);
8594             if ((pos + mergeConflictMarkerLength) < text.length) {
8595                 for (var i = 0; i < mergeConflictMarkerLength; i++) {
8596                     if (text.charCodeAt(pos + i) !== ch) {
8597                         return false;
8598                     }
8599                 }
8600                 return ch === 61 /* equals */ ||
8601                     text.charCodeAt(pos + mergeConflictMarkerLength) === 32 /* space */;
8602             }
8603         }
8604         return false;
8605     }
8606     function scanConflictMarkerTrivia(text, pos, error) {
8607         if (error) {
8608             error(ts.Diagnostics.Merge_conflict_marker_encountered, pos, mergeConflictMarkerLength);
8609         }
8610         var ch = text.charCodeAt(pos);
8611         var len = text.length;
8612         if (ch === 60 /* lessThan */ || ch === 62 /* greaterThan */) {
8613             while (pos < len && !isLineBreak(text.charCodeAt(pos))) {
8614                 pos++;
8615             }
8616         }
8617         else {
8618             ts.Debug.assert(ch === 124 /* bar */ || ch === 61 /* equals */);
8619             // Consume everything from the start of a ||||||| or ======= marker to the start
8620             // of the next ======= or >>>>>>> marker.
8621             while (pos < len) {
8622                 var currentChar = text.charCodeAt(pos);
8623                 if ((currentChar === 61 /* equals */ || currentChar === 62 /* greaterThan */) && currentChar !== ch && isConflictMarkerTrivia(text, pos)) {
8624                     break;
8625                 }
8626                 pos++;
8627             }
8628         }
8629         return pos;
8630     }
8631     var shebangTriviaRegex = /^#!.*/;
8632     /*@internal*/
8633     function isShebangTrivia(text, pos) {
8634         // Shebangs check must only be done at the start of the file
8635         ts.Debug.assert(pos === 0);
8636         return shebangTriviaRegex.test(text);
8637     }
8638     ts.isShebangTrivia = isShebangTrivia;
8639     /*@internal*/
8640     function scanShebangTrivia(text, pos) {
8641         var shebang = shebangTriviaRegex.exec(text)[0];
8642         pos = pos + shebang.length;
8643         return pos;
8644     }
8645     ts.scanShebangTrivia = scanShebangTrivia;
8646     /**
8647      * Invokes a callback for each comment range following the provided position.
8648      *
8649      * Single-line comment ranges include the leading double-slash characters but not the ending
8650      * line break. Multi-line comment ranges include the leading slash-asterisk and trailing
8651      * asterisk-slash characters.
8652      *
8653      * @param reduce If true, accumulates the result of calling the callback in a fashion similar
8654      *      to reduceLeft. If false, iteration stops when the callback returns a truthy value.
8655      * @param text The source text to scan.
8656      * @param pos The position at which to start scanning.
8657      * @param trailing If false, whitespace is skipped until the first line break and comments
8658      *      between that location and the next token are returned. If true, comments occurring
8659      *      between the given position and the next line break are returned.
8660      * @param cb The callback to execute as each comment range is encountered.
8661      * @param state A state value to pass to each iteration of the callback.
8662      * @param initial An initial value to pass when accumulating results (when "reduce" is true).
8663      * @returns If "reduce" is true, the accumulated value. If "reduce" is false, the first truthy
8664      *      return value of the callback.
8665      */
8666     function iterateCommentRanges(reduce, text, pos, trailing, cb, state, initial) {
8667         var pendingPos;
8668         var pendingEnd;
8669         var pendingKind;
8670         var pendingHasTrailingNewLine;
8671         var hasPendingCommentRange = false;
8672         var collecting = trailing;
8673         var accumulator = initial;
8674         if (pos === 0) {
8675             collecting = true;
8676             var shebang = getShebang(text);
8677             if (shebang) {
8678                 pos = shebang.length;
8679             }
8680         }
8681         scan: while (pos >= 0 && pos < text.length) {
8682             var ch = text.charCodeAt(pos);
8683             switch (ch) {
8684                 case 13 /* carriageReturn */:
8685                     if (text.charCodeAt(pos + 1) === 10 /* lineFeed */) {
8686                         pos++;
8687                     }
8688                 // falls through
8689                 case 10 /* lineFeed */:
8690                     pos++;
8691                     if (trailing) {
8692                         break scan;
8693                     }
8694                     collecting = true;
8695                     if (hasPendingCommentRange) {
8696                         pendingHasTrailingNewLine = true;
8697                     }
8698                     continue;
8699                 case 9 /* tab */:
8700                 case 11 /* verticalTab */:
8701                 case 12 /* formFeed */:
8702                 case 32 /* space */:
8703                     pos++;
8704                     continue;
8705                 case 47 /* slash */:
8706                     var nextChar = text.charCodeAt(pos + 1);
8707                     var hasTrailingNewLine = false;
8708                     if (nextChar === 47 /* slash */ || nextChar === 42 /* asterisk */) {
8709                         var kind = nextChar === 47 /* slash */ ? 2 /* SingleLineCommentTrivia */ : 3 /* MultiLineCommentTrivia */;
8710                         var startPos = pos;
8711                         pos += 2;
8712                         if (nextChar === 47 /* slash */) {
8713                             while (pos < text.length) {
8714                                 if (isLineBreak(text.charCodeAt(pos))) {
8715                                     hasTrailingNewLine = true;
8716                                     break;
8717                                 }
8718                                 pos++;
8719                             }
8720                         }
8721                         else {
8722                             while (pos < text.length) {
8723                                 if (text.charCodeAt(pos) === 42 /* asterisk */ && text.charCodeAt(pos + 1) === 47 /* slash */) {
8724                                     pos += 2;
8725                                     break;
8726                                 }
8727                                 pos++;
8728                             }
8729                         }
8730                         if (collecting) {
8731                             if (hasPendingCommentRange) {
8732                                 accumulator = cb(pendingPos, pendingEnd, pendingKind, pendingHasTrailingNewLine, state, accumulator);
8733                                 if (!reduce && accumulator) {
8734                                     // If we are not reducing and we have a truthy result, return it.
8735                                     return accumulator;
8736                                 }
8737                             }
8738                             pendingPos = startPos;
8739                             pendingEnd = pos;
8740                             pendingKind = kind;
8741                             pendingHasTrailingNewLine = hasTrailingNewLine;
8742                             hasPendingCommentRange = true;
8743                         }
8744                         continue;
8745                     }
8746                     break scan;
8747                 default:
8748                     if (ch > 127 /* maxAsciiCharacter */ && (isWhiteSpaceLike(ch))) {
8749                         if (hasPendingCommentRange && isLineBreak(ch)) {
8750                             pendingHasTrailingNewLine = true;
8751                         }
8752                         pos++;
8753                         continue;
8754                     }
8755                     break scan;
8756             }
8757         }
8758         if (hasPendingCommentRange) {
8759             accumulator = cb(pendingPos, pendingEnd, pendingKind, pendingHasTrailingNewLine, state, accumulator);
8760         }
8761         return accumulator;
8762     }
8763     function forEachLeadingCommentRange(text, pos, cb, state) {
8764         return iterateCommentRanges(/*reduce*/ false, text, pos, /*trailing*/ false, cb, state);
8765     }
8766     ts.forEachLeadingCommentRange = forEachLeadingCommentRange;
8767     function forEachTrailingCommentRange(text, pos, cb, state) {
8768         return iterateCommentRanges(/*reduce*/ false, text, pos, /*trailing*/ true, cb, state);
8769     }
8770     ts.forEachTrailingCommentRange = forEachTrailingCommentRange;
8771     function reduceEachLeadingCommentRange(text, pos, cb, state, initial) {
8772         return iterateCommentRanges(/*reduce*/ true, text, pos, /*trailing*/ false, cb, state, initial);
8773     }
8774     ts.reduceEachLeadingCommentRange = reduceEachLeadingCommentRange;
8775     function reduceEachTrailingCommentRange(text, pos, cb, state, initial) {
8776         return iterateCommentRanges(/*reduce*/ true, text, pos, /*trailing*/ true, cb, state, initial);
8777     }
8778     ts.reduceEachTrailingCommentRange = reduceEachTrailingCommentRange;
8779     function appendCommentRange(pos, end, kind, hasTrailingNewLine, _state, comments) {
8780         if (!comments) {
8781             comments = [];
8782         }
8783         comments.push({ kind: kind, pos: pos, end: end, hasTrailingNewLine: hasTrailingNewLine });
8784         return comments;
8785     }
8786     function getLeadingCommentRanges(text, pos) {
8787         return reduceEachLeadingCommentRange(text, pos, appendCommentRange, /*state*/ undefined, /*initial*/ undefined);
8788     }
8789     ts.getLeadingCommentRanges = getLeadingCommentRanges;
8790     function getTrailingCommentRanges(text, pos) {
8791         return reduceEachTrailingCommentRange(text, pos, appendCommentRange, /*state*/ undefined, /*initial*/ undefined);
8792     }
8793     ts.getTrailingCommentRanges = getTrailingCommentRanges;
8794     /** Optionally, get the shebang */
8795     function getShebang(text) {
8796         var match = shebangTriviaRegex.exec(text);
8797         if (match) {
8798             return match[0];
8799         }
8800     }
8801     ts.getShebang = getShebang;
8802     function isIdentifierStart(ch, languageVersion) {
8803         return ch >= 65 /* A */ && ch <= 90 /* Z */ || ch >= 97 /* a */ && ch <= 122 /* z */ ||
8804             ch === 36 /* $ */ || ch === 95 /* _ */ ||
8805             ch > 127 /* maxAsciiCharacter */ && isUnicodeIdentifierStart(ch, languageVersion);
8806     }
8807     ts.isIdentifierStart = isIdentifierStart;
8808     function isIdentifierPart(ch, languageVersion, identifierVariant) {
8809         return ch >= 65 /* A */ && ch <= 90 /* Z */ || ch >= 97 /* a */ && ch <= 122 /* z */ ||
8810             ch >= 48 /* _0 */ && ch <= 57 /* _9 */ || ch === 36 /* $ */ || ch === 95 /* _ */ ||
8811             // "-" and ":" are valid in JSX Identifiers
8812             (identifierVariant === 1 /* JSX */ ? (ch === 45 /* minus */ || ch === 58 /* colon */) : false) ||
8813             ch > 127 /* maxAsciiCharacter */ && isUnicodeIdentifierPart(ch, languageVersion);
8814     }
8815     ts.isIdentifierPart = isIdentifierPart;
8816     /* @internal */
8817     function isIdentifierText(name, languageVersion, identifierVariant) {
8818         var ch = codePointAt(name, 0);
8819         if (!isIdentifierStart(ch, languageVersion)) {
8820             return false;
8821         }
8822         for (var i = charSize(ch); i < name.length; i += charSize(ch)) {
8823             if (!isIdentifierPart(ch = codePointAt(name, i), languageVersion, identifierVariant)) {
8824                 return false;
8825             }
8826         }
8827         return true;
8828     }
8829     ts.isIdentifierText = isIdentifierText;
8830     // Creates a scanner over a (possibly unspecified) range of a piece of text.
8831     function createScanner(languageVersion, skipTrivia, languageVariant, textInitial, onError, start, length) {
8832         if (languageVariant === void 0) { languageVariant = 0 /* Standard */; }
8833         var text = textInitial;
8834         // Current position (end position of text of current token)
8835         var pos;
8836         // end of text
8837         var end;
8838         // Start position of whitespace before current token
8839         var startPos;
8840         // Start position of text of current token
8841         var tokenPos;
8842         var token;
8843         var tokenValue;
8844         var tokenFlags;
8845         var commentDirectives;
8846         var inJSDocType = 0;
8847         setText(text, start, length);
8848         var scanner = {
8849             getStartPos: function () { return startPos; },
8850             getTextPos: function () { return pos; },
8851             getToken: function () { return token; },
8852             getTokenPos: function () { return tokenPos; },
8853             getTokenText: function () { return text.substring(tokenPos, pos); },
8854             getTokenValue: function () { return tokenValue; },
8855             hasUnicodeEscape: function () { return (tokenFlags & 1024 /* UnicodeEscape */) !== 0; },
8856             hasExtendedUnicodeEscape: function () { return (tokenFlags & 8 /* ExtendedUnicodeEscape */) !== 0; },
8857             hasPrecedingLineBreak: function () { return (tokenFlags & 1 /* PrecedingLineBreak */) !== 0; },
8858             isIdentifier: function () { return token === 75 /* Identifier */ || token > 112 /* LastReservedWord */; },
8859             isReservedWord: function () { return token >= 77 /* FirstReservedWord */ && token <= 112 /* LastReservedWord */; },
8860             isUnterminated: function () { return (tokenFlags & 4 /* Unterminated */) !== 0; },
8861             getCommentDirectives: function () { return commentDirectives; },
8862             getTokenFlags: function () { return tokenFlags; },
8863             reScanGreaterToken: reScanGreaterToken,
8864             reScanSlashToken: reScanSlashToken,
8865             reScanTemplateToken: reScanTemplateToken,
8866             reScanTemplateHeadOrNoSubstitutionTemplate: reScanTemplateHeadOrNoSubstitutionTemplate,
8867             scanJsxIdentifier: scanJsxIdentifier,
8868             scanJsxAttributeValue: scanJsxAttributeValue,
8869             reScanJsxAttributeValue: reScanJsxAttributeValue,
8870             reScanJsxToken: reScanJsxToken,
8871             reScanLessThanToken: reScanLessThanToken,
8872             reScanQuestionToken: reScanQuestionToken,
8873             scanJsxToken: scanJsxToken,
8874             scanJsDocToken: scanJsDocToken,
8875             scan: scan,
8876             getText: getText,
8877             clearCommentDirectives: clearCommentDirectives,
8878             setText: setText,
8879             setScriptTarget: setScriptTarget,
8880             setLanguageVariant: setLanguageVariant,
8881             setOnError: setOnError,
8882             setTextPos: setTextPos,
8883             setInJSDocType: setInJSDocType,
8884             tryScan: tryScan,
8885             lookAhead: lookAhead,
8886             scanRange: scanRange,
8887         };
8888         if (ts.Debug.isDebugging) {
8889             Object.defineProperty(scanner, "__debugShowCurrentPositionInText", {
8890                 get: function () {
8891                     var text = scanner.getText();
8892                     return text.slice(0, scanner.getStartPos()) + "â•‘" + text.slice(scanner.getStartPos());
8893                 },
8894             });
8895         }
8896         return scanner;
8897         function error(message, errPos, length) {
8898             if (errPos === void 0) { errPos = pos; }
8899             if (onError) {
8900                 var oldPos = pos;
8901                 pos = errPos;
8902                 onError(message, length || 0);
8903                 pos = oldPos;
8904             }
8905         }
8906         function scanNumberFragment() {
8907             var start = pos;
8908             var allowSeparator = false;
8909             var isPreviousTokenSeparator = false;
8910             var result = "";
8911             while (true) {
8912                 var ch = text.charCodeAt(pos);
8913                 if (ch === 95 /* _ */) {
8914                     tokenFlags |= 512 /* ContainsSeparator */;
8915                     if (allowSeparator) {
8916                         allowSeparator = false;
8917                         isPreviousTokenSeparator = true;
8918                         result += text.substring(start, pos);
8919                     }
8920                     else if (isPreviousTokenSeparator) {
8921                         error(ts.Diagnostics.Multiple_consecutive_numeric_separators_are_not_permitted, pos, 1);
8922                     }
8923                     else {
8924                         error(ts.Diagnostics.Numeric_separators_are_not_allowed_here, pos, 1);
8925                     }
8926                     pos++;
8927                     start = pos;
8928                     continue;
8929                 }
8930                 if (isDigit(ch)) {
8931                     allowSeparator = true;
8932                     isPreviousTokenSeparator = false;
8933                     pos++;
8934                     continue;
8935                 }
8936                 break;
8937             }
8938             if (text.charCodeAt(pos - 1) === 95 /* _ */) {
8939                 error(ts.Diagnostics.Numeric_separators_are_not_allowed_here, pos - 1, 1);
8940             }
8941             return result + text.substring(start, pos);
8942         }
8943         function scanNumber() {
8944             var start = pos;
8945             var mainFragment = scanNumberFragment();
8946             var decimalFragment;
8947             var scientificFragment;
8948             if (text.charCodeAt(pos) === 46 /* dot */) {
8949                 pos++;
8950                 decimalFragment = scanNumberFragment();
8951             }
8952             var end = pos;
8953             if (text.charCodeAt(pos) === 69 /* E */ || text.charCodeAt(pos) === 101 /* e */) {
8954                 pos++;
8955                 tokenFlags |= 16 /* Scientific */;
8956                 if (text.charCodeAt(pos) === 43 /* plus */ || text.charCodeAt(pos) === 45 /* minus */)
8957                     pos++;
8958                 var preNumericPart = pos;
8959                 var finalFragment = scanNumberFragment();
8960                 if (!finalFragment) {
8961                     error(ts.Diagnostics.Digit_expected);
8962                 }
8963                 else {
8964                     scientificFragment = text.substring(end, preNumericPart) + finalFragment;
8965                     end = pos;
8966                 }
8967             }
8968             var result;
8969             if (tokenFlags & 512 /* ContainsSeparator */) {
8970                 result = mainFragment;
8971                 if (decimalFragment) {
8972                     result += "." + decimalFragment;
8973                 }
8974                 if (scientificFragment) {
8975                     result += scientificFragment;
8976                 }
8977             }
8978             else {
8979                 result = text.substring(start, end); // No need to use all the fragments; no _ removal needed
8980             }
8981             if (decimalFragment !== undefined || tokenFlags & 16 /* Scientific */) {
8982                 checkForIdentifierStartAfterNumericLiteral(start, decimalFragment === undefined && !!(tokenFlags & 16 /* Scientific */));
8983                 return {
8984                     type: 8 /* NumericLiteral */,
8985                     value: "" + +result // if value is not an integer, it can be safely coerced to a number
8986                 };
8987             }
8988             else {
8989                 tokenValue = result;
8990                 var type = checkBigIntSuffix(); // if value is an integer, check whether it is a bigint
8991                 checkForIdentifierStartAfterNumericLiteral(start);
8992                 return { type: type, value: tokenValue };
8993             }
8994         }
8995         function checkForIdentifierStartAfterNumericLiteral(numericStart, isScientific) {
8996             if (!isIdentifierStart(codePointAt(text, pos), languageVersion)) {
8997                 return;
8998             }
8999             var identifierStart = pos;
9000             var length = scanIdentifierParts().length;
9001             if (length === 1 && text[identifierStart] === "n") {
9002                 if (isScientific) {
9003                     error(ts.Diagnostics.A_bigint_literal_cannot_use_exponential_notation, numericStart, identifierStart - numericStart + 1);
9004                 }
9005                 else {
9006                     error(ts.Diagnostics.A_bigint_literal_must_be_an_integer, numericStart, identifierStart - numericStart + 1);
9007                 }
9008             }
9009             else {
9010                 error(ts.Diagnostics.An_identifier_or_keyword_cannot_immediately_follow_a_numeric_literal, identifierStart, length);
9011                 pos = identifierStart;
9012             }
9013         }
9014         function scanOctalDigits() {
9015             var start = pos;
9016             while (isOctalDigit(text.charCodeAt(pos))) {
9017                 pos++;
9018             }
9019             return +(text.substring(start, pos));
9020         }
9021         /**
9022          * Scans the given number of hexadecimal digits in the text,
9023          * returning -1 if the given number is unavailable.
9024          */
9025         function scanExactNumberOfHexDigits(count, canHaveSeparators) {
9026             var valueString = scanHexDigits(/*minCount*/ count, /*scanAsManyAsPossible*/ false, canHaveSeparators);
9027             return valueString ? parseInt(valueString, 16) : -1;
9028         }
9029         /**
9030          * Scans as many hexadecimal digits as are available in the text,
9031          * returning "" if the given number of digits was unavailable.
9032          */
9033         function scanMinimumNumberOfHexDigits(count, canHaveSeparators) {
9034             return scanHexDigits(/*minCount*/ count, /*scanAsManyAsPossible*/ true, canHaveSeparators);
9035         }
9036         function scanHexDigits(minCount, scanAsManyAsPossible, canHaveSeparators) {
9037             var valueChars = [];
9038             var allowSeparator = false;
9039             var isPreviousTokenSeparator = false;
9040             while (valueChars.length < minCount || scanAsManyAsPossible) {
9041                 var ch = text.charCodeAt(pos);
9042                 if (canHaveSeparators && ch === 95 /* _ */) {
9043                     tokenFlags |= 512 /* ContainsSeparator */;
9044                     if (allowSeparator) {
9045                         allowSeparator = false;
9046                         isPreviousTokenSeparator = true;
9047                     }
9048                     else if (isPreviousTokenSeparator) {
9049                         error(ts.Diagnostics.Multiple_consecutive_numeric_separators_are_not_permitted, pos, 1);
9050                     }
9051                     else {
9052                         error(ts.Diagnostics.Numeric_separators_are_not_allowed_here, pos, 1);
9053                     }
9054                     pos++;
9055                     continue;
9056                 }
9057                 allowSeparator = canHaveSeparators;
9058                 if (ch >= 65 /* A */ && ch <= 70 /* F */) {
9059                     ch += 97 /* a */ - 65 /* A */; // standardize hex literals to lowercase
9060                 }
9061                 else if (!((ch >= 48 /* _0 */ && ch <= 57 /* _9 */) ||
9062                     (ch >= 97 /* a */ && ch <= 102 /* f */))) {
9063                     break;
9064                 }
9065                 valueChars.push(ch);
9066                 pos++;
9067                 isPreviousTokenSeparator = false;
9068             }
9069             if (valueChars.length < minCount) {
9070                 valueChars = [];
9071             }
9072             if (text.charCodeAt(pos - 1) === 95 /* _ */) {
9073                 error(ts.Diagnostics.Numeric_separators_are_not_allowed_here, pos - 1, 1);
9074             }
9075             return String.fromCharCode.apply(String, valueChars);
9076         }
9077         function scanString(jsxAttributeString) {
9078             if (jsxAttributeString === void 0) { jsxAttributeString = false; }
9079             var quote = text.charCodeAt(pos);
9080             pos++;
9081             var result = "";
9082             var start = pos;
9083             while (true) {
9084                 if (pos >= end) {
9085                     result += text.substring(start, pos);
9086                     tokenFlags |= 4 /* Unterminated */;
9087                     error(ts.Diagnostics.Unterminated_string_literal);
9088                     break;
9089                 }
9090                 var ch = text.charCodeAt(pos);
9091                 if (ch === quote) {
9092                     result += text.substring(start, pos);
9093                     pos++;
9094                     break;
9095                 }
9096                 if (ch === 92 /* backslash */ && !jsxAttributeString) {
9097                     result += text.substring(start, pos);
9098                     result += scanEscapeSequence();
9099                     start = pos;
9100                     continue;
9101                 }
9102                 if (isLineBreak(ch) && !jsxAttributeString) {
9103                     result += text.substring(start, pos);
9104                     tokenFlags |= 4 /* Unterminated */;
9105                     error(ts.Diagnostics.Unterminated_string_literal);
9106                     break;
9107                 }
9108                 pos++;
9109             }
9110             return result;
9111         }
9112         /**
9113          * Sets the current 'tokenValue' and returns a NoSubstitutionTemplateLiteral or
9114          * a literal component of a TemplateExpression.
9115          */
9116         function scanTemplateAndSetTokenValue(isTaggedTemplate) {
9117             var startedWithBacktick = text.charCodeAt(pos) === 96 /* backtick */;
9118             pos++;
9119             var start = pos;
9120             var contents = "";
9121             var resultingToken;
9122             while (true) {
9123                 if (pos >= end) {
9124                     contents += text.substring(start, pos);
9125                     tokenFlags |= 4 /* Unterminated */;
9126                     error(ts.Diagnostics.Unterminated_template_literal);
9127                     resultingToken = startedWithBacktick ? 14 /* NoSubstitutionTemplateLiteral */ : 17 /* TemplateTail */;
9128                     break;
9129                 }
9130                 var currChar = text.charCodeAt(pos);
9131                 // '`'
9132                 if (currChar === 96 /* backtick */) {
9133                     contents += text.substring(start, pos);
9134                     pos++;
9135                     resultingToken = startedWithBacktick ? 14 /* NoSubstitutionTemplateLiteral */ : 17 /* TemplateTail */;
9136                     break;
9137                 }
9138                 // '${'
9139                 if (currChar === 36 /* $ */ && pos + 1 < end && text.charCodeAt(pos + 1) === 123 /* openBrace */) {
9140                     contents += text.substring(start, pos);
9141                     pos += 2;
9142                     resultingToken = startedWithBacktick ? 15 /* TemplateHead */ : 16 /* TemplateMiddle */;
9143                     break;
9144                 }
9145                 // Escape character
9146                 if (currChar === 92 /* backslash */) {
9147                     contents += text.substring(start, pos);
9148                     contents += scanEscapeSequence(isTaggedTemplate);
9149                     start = pos;
9150                     continue;
9151                 }
9152                 // Speculated ECMAScript 6 Spec 11.8.6.1:
9153                 // <CR><LF> and <CR> LineTerminatorSequences are normalized to <LF> for Template Values
9154                 if (currChar === 13 /* carriageReturn */) {
9155                     contents += text.substring(start, pos);
9156                     pos++;
9157                     if (pos < end && text.charCodeAt(pos) === 10 /* lineFeed */) {
9158                         pos++;
9159                     }
9160                     contents += "\n";
9161                     start = pos;
9162                     continue;
9163                 }
9164                 pos++;
9165             }
9166             ts.Debug.assert(resultingToken !== undefined);
9167             tokenValue = contents;
9168             return resultingToken;
9169         }
9170         function scanEscapeSequence(isTaggedTemplate) {
9171             var start = pos;
9172             pos++;
9173             if (pos >= end) {
9174                 error(ts.Diagnostics.Unexpected_end_of_text);
9175                 return "";
9176             }
9177             var ch = text.charCodeAt(pos);
9178             pos++;
9179             switch (ch) {
9180                 case 48 /* _0 */:
9181                     // '\01'
9182                     if (isTaggedTemplate && pos < end && isDigit(text.charCodeAt(pos))) {
9183                         pos++;
9184                         tokenFlags |= 2048 /* ContainsInvalidEscape */;
9185                         return text.substring(start, pos);
9186                     }
9187                     return "\0";
9188                 case 98 /* b */:
9189                     return "\b";
9190                 case 116 /* t */:
9191                     return "\t";
9192                 case 110 /* n */:
9193                     return "\n";
9194                 case 118 /* v */:
9195                     return "\v";
9196                 case 102 /* f */:
9197                     return "\f";
9198                 case 114 /* r */:
9199                     return "\r";
9200                 case 39 /* singleQuote */:
9201                     return "\'";
9202                 case 34 /* doubleQuote */:
9203                     return "\"";
9204                 case 117 /* u */:
9205                     if (isTaggedTemplate) {
9206                         // '\u' or '\u0' or '\u00' or '\u000'
9207                         for (var escapePos = pos; escapePos < pos + 4; escapePos++) {
9208                             if (escapePos < end && !isHexDigit(text.charCodeAt(escapePos)) && text.charCodeAt(escapePos) !== 123 /* openBrace */) {
9209                                 pos = escapePos;
9210                                 tokenFlags |= 2048 /* ContainsInvalidEscape */;
9211                                 return text.substring(start, pos);
9212                             }
9213                         }
9214                     }
9215                     // '\u{DDDDDDDD}'
9216                     if (pos < end && text.charCodeAt(pos) === 123 /* openBrace */) {
9217                         pos++;
9218                         // '\u{'
9219                         if (isTaggedTemplate && !isHexDigit(text.charCodeAt(pos))) {
9220                             tokenFlags |= 2048 /* ContainsInvalidEscape */;
9221                             return text.substring(start, pos);
9222                         }
9223                         if (isTaggedTemplate) {
9224                             var savePos = pos;
9225                             var escapedValueString = scanMinimumNumberOfHexDigits(1, /*canHaveSeparators*/ false);
9226                             var escapedValue = escapedValueString ? parseInt(escapedValueString, 16) : -1;
9227                             // '\u{Not Code Point' or '\u{CodePoint'
9228                             if (!isCodePoint(escapedValue) || text.charCodeAt(pos) !== 125 /* closeBrace */) {
9229                                 tokenFlags |= 2048 /* ContainsInvalidEscape */;
9230                                 return text.substring(start, pos);
9231                             }
9232                             else {
9233                                 pos = savePos;
9234                             }
9235                         }
9236                         tokenFlags |= 8 /* ExtendedUnicodeEscape */;
9237                         return scanExtendedUnicodeEscape();
9238                     }
9239                     tokenFlags |= 1024 /* UnicodeEscape */;
9240                     // '\uDDDD'
9241                     return scanHexadecimalEscape(/*numDigits*/ 4);
9242                 case 120 /* x */:
9243                     if (isTaggedTemplate) {
9244                         if (!isHexDigit(text.charCodeAt(pos))) {
9245                             tokenFlags |= 2048 /* ContainsInvalidEscape */;
9246                             return text.substring(start, pos);
9247                         }
9248                         else if (!isHexDigit(text.charCodeAt(pos + 1))) {
9249                             pos++;
9250                             tokenFlags |= 2048 /* ContainsInvalidEscape */;
9251                             return text.substring(start, pos);
9252                         }
9253                     }
9254                     // '\xDD'
9255                     return scanHexadecimalEscape(/*numDigits*/ 2);
9256                 // when encountering a LineContinuation (i.e. a backslash and a line terminator sequence),
9257                 // the line terminator is interpreted to be "the empty code unit sequence".
9258                 case 13 /* carriageReturn */:
9259                     if (pos < end && text.charCodeAt(pos) === 10 /* lineFeed */) {
9260                         pos++;
9261                     }
9262                 // falls through
9263                 case 10 /* lineFeed */:
9264                 case 8232 /* lineSeparator */:
9265                 case 8233 /* paragraphSeparator */:
9266                     return "";
9267                 default:
9268                     return String.fromCharCode(ch);
9269             }
9270         }
9271         function scanHexadecimalEscape(numDigits) {
9272             var escapedValue = scanExactNumberOfHexDigits(numDigits, /*canHaveSeparators*/ false);
9273             if (escapedValue >= 0) {
9274                 return String.fromCharCode(escapedValue);
9275             }
9276             else {
9277                 error(ts.Diagnostics.Hexadecimal_digit_expected);
9278                 return "";
9279             }
9280         }
9281         function scanExtendedUnicodeEscape() {
9282             var escapedValueString = scanMinimumNumberOfHexDigits(1, /*canHaveSeparators*/ false);
9283             var escapedValue = escapedValueString ? parseInt(escapedValueString, 16) : -1;
9284             var isInvalidExtendedEscape = false;
9285             // Validate the value of the digit
9286             if (escapedValue < 0) {
9287                 error(ts.Diagnostics.Hexadecimal_digit_expected);
9288                 isInvalidExtendedEscape = true;
9289             }
9290             else if (escapedValue > 0x10FFFF) {
9291                 error(ts.Diagnostics.An_extended_Unicode_escape_value_must_be_between_0x0_and_0x10FFFF_inclusive);
9292                 isInvalidExtendedEscape = true;
9293             }
9294             if (pos >= end) {
9295                 error(ts.Diagnostics.Unexpected_end_of_text);
9296                 isInvalidExtendedEscape = true;
9297             }
9298             else if (text.charCodeAt(pos) === 125 /* closeBrace */) {
9299                 // Only swallow the following character up if it's a '}'.
9300                 pos++;
9301             }
9302             else {
9303                 error(ts.Diagnostics.Unterminated_Unicode_escape_sequence);
9304                 isInvalidExtendedEscape = true;
9305             }
9306             if (isInvalidExtendedEscape) {
9307                 return "";
9308             }
9309             return utf16EncodeAsString(escapedValue);
9310         }
9311         // Current character is known to be a backslash. Check for Unicode escape of the form '\uXXXX'
9312         // and return code point value if valid Unicode escape is found. Otherwise return -1.
9313         function peekUnicodeEscape() {
9314             if (pos + 5 < end && text.charCodeAt(pos + 1) === 117 /* u */) {
9315                 var start_1 = pos;
9316                 pos += 2;
9317                 var value = scanExactNumberOfHexDigits(4, /*canHaveSeparators*/ false);
9318                 pos = start_1;
9319                 return value;
9320             }
9321             return -1;
9322         }
9323         function peekExtendedUnicodeEscape() {
9324             if (languageVersion >= 2 /* ES2015 */ && codePointAt(text, pos + 1) === 117 /* u */ && codePointAt(text, pos + 2) === 123 /* openBrace */) {
9325                 var start_2 = pos;
9326                 pos += 3;
9327                 var escapedValueString = scanMinimumNumberOfHexDigits(1, /*canHaveSeparators*/ false);
9328                 var escapedValue = escapedValueString ? parseInt(escapedValueString, 16) : -1;
9329                 pos = start_2;
9330                 return escapedValue;
9331             }
9332             return -1;
9333         }
9334         function scanIdentifierParts() {
9335             var result = "";
9336             var start = pos;
9337             while (pos < end) {
9338                 var ch = codePointAt(text, pos);
9339                 if (isIdentifierPart(ch, languageVersion)) {
9340                     pos += charSize(ch);
9341                 }
9342                 else if (ch === 92 /* backslash */) {
9343                     ch = peekExtendedUnicodeEscape();
9344                     if (ch >= 0 && isIdentifierPart(ch, languageVersion)) {
9345                         pos += 3;
9346                         tokenFlags |= 8 /* ExtendedUnicodeEscape */;
9347                         result += scanExtendedUnicodeEscape();
9348                         start = pos;
9349                         continue;
9350                     }
9351                     ch = peekUnicodeEscape();
9352                     if (!(ch >= 0 && isIdentifierPart(ch, languageVersion))) {
9353                         break;
9354                     }
9355                     tokenFlags |= 1024 /* UnicodeEscape */;
9356                     result += text.substring(start, pos);
9357                     result += utf16EncodeAsString(ch);
9358                     // Valid Unicode escape is always six characters
9359                     pos += 6;
9360                     start = pos;
9361                 }
9362                 else {
9363                     break;
9364                 }
9365             }
9366             result += text.substring(start, pos);
9367             return result;
9368         }
9369         function getIdentifierToken() {
9370             // Reserved words are between 2 and 11 characters long and start with a lowercase letter
9371             var len = tokenValue.length;
9372             if (len >= 2 && len <= 11) {
9373                 var ch = tokenValue.charCodeAt(0);
9374                 if (ch >= 97 /* a */ && ch <= 122 /* z */) {
9375                     var keyword = textToKeyword.get(tokenValue);
9376                     if (keyword !== undefined) {
9377                         return token = keyword;
9378                     }
9379                 }
9380             }
9381             return token = 75 /* Identifier */;
9382         }
9383         function scanBinaryOrOctalDigits(base) {
9384             var value = "";
9385             // For counting number of digits; Valid binaryIntegerLiteral must have at least one binary digit following B or b.
9386             // Similarly valid octalIntegerLiteral must have at least one octal digit following o or O.
9387             var separatorAllowed = false;
9388             var isPreviousTokenSeparator = false;
9389             while (true) {
9390                 var ch = text.charCodeAt(pos);
9391                 // Numeric separators are allowed anywhere within a numeric literal, except not at the beginning, or following another separator
9392                 if (ch === 95 /* _ */) {
9393                     tokenFlags |= 512 /* ContainsSeparator */;
9394                     if (separatorAllowed) {
9395                         separatorAllowed = false;
9396                         isPreviousTokenSeparator = true;
9397                     }
9398                     else if (isPreviousTokenSeparator) {
9399                         error(ts.Diagnostics.Multiple_consecutive_numeric_separators_are_not_permitted, pos, 1);
9400                     }
9401                     else {
9402                         error(ts.Diagnostics.Numeric_separators_are_not_allowed_here, pos, 1);
9403                     }
9404                     pos++;
9405                     continue;
9406                 }
9407                 separatorAllowed = true;
9408                 if (!isDigit(ch) || ch - 48 /* _0 */ >= base) {
9409                     break;
9410                 }
9411                 value += text[pos];
9412                 pos++;
9413                 isPreviousTokenSeparator = false;
9414             }
9415             if (text.charCodeAt(pos - 1) === 95 /* _ */) {
9416                 // Literal ends with underscore - not allowed
9417                 error(ts.Diagnostics.Numeric_separators_are_not_allowed_here, pos - 1, 1);
9418             }
9419             return value;
9420         }
9421         function checkBigIntSuffix() {
9422             if (text.charCodeAt(pos) === 110 /* n */) {
9423                 tokenValue += "n";
9424                 // Use base 10 instead of base 2 or base 8 for shorter literals
9425                 if (tokenFlags & 384 /* BinaryOrOctalSpecifier */) {
9426                     tokenValue = ts.parsePseudoBigInt(tokenValue) + "n";
9427                 }
9428                 pos++;
9429                 return 9 /* BigIntLiteral */;
9430             }
9431             else { // not a bigint, so can convert to number in simplified form
9432                 // Number() may not support 0b or 0o, so use parseInt() instead
9433                 var numericValue = tokenFlags & 128 /* BinarySpecifier */
9434                     ? parseInt(tokenValue.slice(2), 2) // skip "0b"
9435                     : tokenFlags & 256 /* OctalSpecifier */
9436                         ? parseInt(tokenValue.slice(2), 8) // skip "0o"
9437                         : +tokenValue;
9438                 tokenValue = "" + numericValue;
9439                 return 8 /* NumericLiteral */;
9440             }
9441         }
9442         function scan() {
9443             var _a;
9444             startPos = pos;
9445             tokenFlags = 0 /* None */;
9446             var asteriskSeen = false;
9447             while (true) {
9448                 tokenPos = pos;
9449                 if (pos >= end) {
9450                     return token = 1 /* EndOfFileToken */;
9451                 }
9452                 var ch = codePointAt(text, pos);
9453                 // Special handling for shebang
9454                 if (ch === 35 /* hash */ && pos === 0 && isShebangTrivia(text, pos)) {
9455                     pos = scanShebangTrivia(text, pos);
9456                     if (skipTrivia) {
9457                         continue;
9458                     }
9459                     else {
9460                         return token = 6 /* ShebangTrivia */;
9461                     }
9462                 }
9463                 switch (ch) {
9464                     case 10 /* lineFeed */:
9465                     case 13 /* carriageReturn */:
9466                         tokenFlags |= 1 /* PrecedingLineBreak */;
9467                         if (skipTrivia) {
9468                             pos++;
9469                             continue;
9470                         }
9471                         else {
9472                             if (ch === 13 /* carriageReturn */ && pos + 1 < end && text.charCodeAt(pos + 1) === 10 /* lineFeed */) {
9473                                 // consume both CR and LF
9474                                 pos += 2;
9475                             }
9476                             else {
9477                                 pos++;
9478                             }
9479                             return token = 4 /* NewLineTrivia */;
9480                         }
9481                     case 9 /* tab */:
9482                     case 11 /* verticalTab */:
9483                     case 12 /* formFeed */:
9484                     case 32 /* space */:
9485                     case 160 /* nonBreakingSpace */:
9486                     case 5760 /* ogham */:
9487                     case 8192 /* enQuad */:
9488                     case 8193 /* emQuad */:
9489                     case 8194 /* enSpace */:
9490                     case 8195 /* emSpace */:
9491                     case 8196 /* threePerEmSpace */:
9492                     case 8197 /* fourPerEmSpace */:
9493                     case 8198 /* sixPerEmSpace */:
9494                     case 8199 /* figureSpace */:
9495                     case 8200 /* punctuationSpace */:
9496                     case 8201 /* thinSpace */:
9497                     case 8202 /* hairSpace */:
9498                     case 8203 /* zeroWidthSpace */:
9499                     case 8239 /* narrowNoBreakSpace */:
9500                     case 8287 /* mathematicalSpace */:
9501                     case 12288 /* ideographicSpace */:
9502                     case 65279 /* byteOrderMark */:
9503                         if (skipTrivia) {
9504                             pos++;
9505                             continue;
9506                         }
9507                         else {
9508                             while (pos < end && isWhiteSpaceSingleLine(text.charCodeAt(pos))) {
9509                                 pos++;
9510                             }
9511                             return token = 5 /* WhitespaceTrivia */;
9512                         }
9513                     case 33 /* exclamation */:
9514                         if (text.charCodeAt(pos + 1) === 61 /* equals */) {
9515                             if (text.charCodeAt(pos + 2) === 61 /* equals */) {
9516                                 return pos += 3, token = 37 /* ExclamationEqualsEqualsToken */;
9517                             }
9518                             return pos += 2, token = 35 /* ExclamationEqualsToken */;
9519                         }
9520                         pos++;
9521                         return token = 53 /* ExclamationToken */;
9522                     case 34 /* doubleQuote */:
9523                     case 39 /* singleQuote */:
9524                         tokenValue = scanString();
9525                         return token = 10 /* StringLiteral */;
9526                     case 96 /* backtick */:
9527                         return token = scanTemplateAndSetTokenValue(/* isTaggedTemplate */ false);
9528                     case 37 /* percent */:
9529                         if (text.charCodeAt(pos + 1) === 61 /* equals */) {
9530                             return pos += 2, token = 68 /* PercentEqualsToken */;
9531                         }
9532                         pos++;
9533                         return token = 44 /* PercentToken */;
9534                     case 38 /* ampersand */:
9535                         if (text.charCodeAt(pos + 1) === 38 /* ampersand */) {
9536                             return pos += 2, token = 55 /* AmpersandAmpersandToken */;
9537                         }
9538                         if (text.charCodeAt(pos + 1) === 61 /* equals */) {
9539                             return pos += 2, token = 72 /* AmpersandEqualsToken */;
9540                         }
9541                         pos++;
9542                         return token = 50 /* AmpersandToken */;
9543                     case 40 /* openParen */:
9544                         pos++;
9545                         return token = 20 /* OpenParenToken */;
9546                     case 41 /* closeParen */:
9547                         pos++;
9548                         return token = 21 /* CloseParenToken */;
9549                     case 42 /* asterisk */:
9550                         if (text.charCodeAt(pos + 1) === 61 /* equals */) {
9551                             return pos += 2, token = 65 /* AsteriskEqualsToken */;
9552                         }
9553                         if (text.charCodeAt(pos + 1) === 42 /* asterisk */) {
9554                             if (text.charCodeAt(pos + 2) === 61 /* equals */) {
9555                                 return pos += 3, token = 66 /* AsteriskAsteriskEqualsToken */;
9556                             }
9557                             return pos += 2, token = 42 /* AsteriskAsteriskToken */;
9558                         }
9559                         pos++;
9560                         if (inJSDocType && !asteriskSeen && (tokenFlags & 1 /* PrecedingLineBreak */)) {
9561                             // decoration at the start of a JSDoc comment line
9562                             asteriskSeen = true;
9563                             continue;
9564                         }
9565                         return token = 41 /* AsteriskToken */;
9566                     case 43 /* plus */:
9567                         if (text.charCodeAt(pos + 1) === 43 /* plus */) {
9568                             return pos += 2, token = 45 /* PlusPlusToken */;
9569                         }
9570                         if (text.charCodeAt(pos + 1) === 61 /* equals */) {
9571                             return pos += 2, token = 63 /* PlusEqualsToken */;
9572                         }
9573                         pos++;
9574                         return token = 39 /* PlusToken */;
9575                     case 44 /* comma */:
9576                         pos++;
9577                         return token = 27 /* CommaToken */;
9578                     case 45 /* minus */:
9579                         if (text.charCodeAt(pos + 1) === 45 /* minus */) {
9580                             return pos += 2, token = 46 /* MinusMinusToken */;
9581                         }
9582                         if (text.charCodeAt(pos + 1) === 61 /* equals */) {
9583                             return pos += 2, token = 64 /* MinusEqualsToken */;
9584                         }
9585                         pos++;
9586                         return token = 40 /* MinusToken */;
9587                     case 46 /* dot */:
9588                         if (isDigit(text.charCodeAt(pos + 1))) {
9589                             tokenValue = scanNumber().value;
9590                             return token = 8 /* NumericLiteral */;
9591                         }
9592                         if (text.charCodeAt(pos + 1) === 46 /* dot */ && text.charCodeAt(pos + 2) === 46 /* dot */) {
9593                             return pos += 3, token = 25 /* DotDotDotToken */;
9594                         }
9595                         pos++;
9596                         return token = 24 /* DotToken */;
9597                     case 47 /* slash */:
9598                         // Single-line comment
9599                         if (text.charCodeAt(pos + 1) === 47 /* slash */) {
9600                             pos += 2;
9601                             while (pos < end) {
9602                                 if (isLineBreak(text.charCodeAt(pos))) {
9603                                     break;
9604                                 }
9605                                 pos++;
9606                             }
9607                             commentDirectives = appendIfCommentDirective(commentDirectives, text.slice(tokenPos, pos), commentDirectiveRegExSingleLine, tokenPos);
9608                             if (skipTrivia) {
9609                                 continue;
9610                             }
9611                             else {
9612                                 return token = 2 /* SingleLineCommentTrivia */;
9613                             }
9614                         }
9615                         // Multi-line comment
9616                         if (text.charCodeAt(pos + 1) === 42 /* asterisk */) {
9617                             pos += 2;
9618                             if (text.charCodeAt(pos) === 42 /* asterisk */ && text.charCodeAt(pos + 1) !== 47 /* slash */) {
9619                                 tokenFlags |= 2 /* PrecedingJSDocComment */;
9620                             }
9621                             var commentClosed = false;
9622                             var lastLineStart = tokenPos;
9623                             while (pos < end) {
9624                                 var ch_1 = text.charCodeAt(pos);
9625                                 if (ch_1 === 42 /* asterisk */ && text.charCodeAt(pos + 1) === 47 /* slash */) {
9626                                     pos += 2;
9627                                     commentClosed = true;
9628                                     break;
9629                                 }
9630                                 pos++;
9631                                 if (isLineBreak(ch_1)) {
9632                                     lastLineStart = pos;
9633                                     tokenFlags |= 1 /* PrecedingLineBreak */;
9634                                 }
9635                             }
9636                             commentDirectives = appendIfCommentDirective(commentDirectives, text.slice(lastLineStart, pos), commentDirectiveRegExMultiLine, lastLineStart);
9637                             if (!commentClosed) {
9638                                 error(ts.Diagnostics.Asterisk_Slash_expected);
9639                             }
9640                             if (skipTrivia) {
9641                                 continue;
9642                             }
9643                             else {
9644                                 if (!commentClosed) {
9645                                     tokenFlags |= 4 /* Unterminated */;
9646                                 }
9647                                 return token = 3 /* MultiLineCommentTrivia */;
9648                             }
9649                         }
9650                         if (text.charCodeAt(pos + 1) === 61 /* equals */) {
9651                             return pos += 2, token = 67 /* SlashEqualsToken */;
9652                         }
9653                         pos++;
9654                         return token = 43 /* SlashToken */;
9655                     case 48 /* _0 */:
9656                         if (pos + 2 < end && (text.charCodeAt(pos + 1) === 88 /* X */ || text.charCodeAt(pos + 1) === 120 /* x */)) {
9657                             pos += 2;
9658                             tokenValue = scanMinimumNumberOfHexDigits(1, /*canHaveSeparators*/ true);
9659                             if (!tokenValue) {
9660                                 error(ts.Diagnostics.Hexadecimal_digit_expected);
9661                                 tokenValue = "0";
9662                             }
9663                             tokenValue = "0x" + tokenValue;
9664                             tokenFlags |= 64 /* HexSpecifier */;
9665                             return token = checkBigIntSuffix();
9666                         }
9667                         else if (pos + 2 < end && (text.charCodeAt(pos + 1) === 66 /* B */ || text.charCodeAt(pos + 1) === 98 /* b */)) {
9668                             pos += 2;
9669                             tokenValue = scanBinaryOrOctalDigits(/* base */ 2);
9670                             if (!tokenValue) {
9671                                 error(ts.Diagnostics.Binary_digit_expected);
9672                                 tokenValue = "0";
9673                             }
9674                             tokenValue = "0b" + tokenValue;
9675                             tokenFlags |= 128 /* BinarySpecifier */;
9676                             return token = checkBigIntSuffix();
9677                         }
9678                         else if (pos + 2 < end && (text.charCodeAt(pos + 1) === 79 /* O */ || text.charCodeAt(pos + 1) === 111 /* o */)) {
9679                             pos += 2;
9680                             tokenValue = scanBinaryOrOctalDigits(/* base */ 8);
9681                             if (!tokenValue) {
9682                                 error(ts.Diagnostics.Octal_digit_expected);
9683                                 tokenValue = "0";
9684                             }
9685                             tokenValue = "0o" + tokenValue;
9686                             tokenFlags |= 256 /* OctalSpecifier */;
9687                             return token = checkBigIntSuffix();
9688                         }
9689                         // Try to parse as an octal
9690                         if (pos + 1 < end && isOctalDigit(text.charCodeAt(pos + 1))) {
9691                             tokenValue = "" + scanOctalDigits();
9692                             tokenFlags |= 32 /* Octal */;
9693                             return token = 8 /* NumericLiteral */;
9694                         }
9695                     // This fall-through is a deviation from the EcmaScript grammar. The grammar says that a leading zero
9696                     // can only be followed by an octal digit, a dot, or the end of the number literal. However, we are being
9697                     // permissive and allowing decimal digits of the form 08* and 09* (which many browsers also do).
9698                     // falls through
9699                     case 49 /* _1 */:
9700                     case 50 /* _2 */:
9701                     case 51 /* _3 */:
9702                     case 52 /* _4 */:
9703                     case 53 /* _5 */:
9704                     case 54 /* _6 */:
9705                     case 55 /* _7 */:
9706                     case 56 /* _8 */:
9707                     case 57 /* _9 */:
9708                         (_a = scanNumber(), token = _a.type, tokenValue = _a.value);
9709                         return token;
9710                     case 58 /* colon */:
9711                         pos++;
9712                         return token = 58 /* ColonToken */;
9713                     case 59 /* semicolon */:
9714                         pos++;
9715                         return token = 26 /* SemicolonToken */;
9716                     case 60 /* lessThan */:
9717                         if (isConflictMarkerTrivia(text, pos)) {
9718                             pos = scanConflictMarkerTrivia(text, pos, error);
9719                             if (skipTrivia) {
9720                                 continue;
9721                             }
9722                             else {
9723                                 return token = 7 /* ConflictMarkerTrivia */;
9724                             }
9725                         }
9726                         if (text.charCodeAt(pos + 1) === 60 /* lessThan */) {
9727                             if (text.charCodeAt(pos + 2) === 61 /* equals */) {
9728                                 return pos += 3, token = 69 /* LessThanLessThanEqualsToken */;
9729                             }
9730                             return pos += 2, token = 47 /* LessThanLessThanToken */;
9731                         }
9732                         if (text.charCodeAt(pos + 1) === 61 /* equals */) {
9733                             return pos += 2, token = 32 /* LessThanEqualsToken */;
9734                         }
9735                         if (languageVariant === 1 /* JSX */ &&
9736                             text.charCodeAt(pos + 1) === 47 /* slash */ &&
9737                             text.charCodeAt(pos + 2) !== 42 /* asterisk */) {
9738                             return pos += 2, token = 30 /* LessThanSlashToken */;
9739                         }
9740                         pos++;
9741                         return token = 29 /* LessThanToken */;
9742                     case 61 /* equals */:
9743                         if (isConflictMarkerTrivia(text, pos)) {
9744                             pos = scanConflictMarkerTrivia(text, pos, error);
9745                             if (skipTrivia) {
9746                                 continue;
9747                             }
9748                             else {
9749                                 return token = 7 /* ConflictMarkerTrivia */;
9750                             }
9751                         }
9752                         if (text.charCodeAt(pos + 1) === 61 /* equals */) {
9753                             if (text.charCodeAt(pos + 2) === 61 /* equals */) {
9754                                 return pos += 3, token = 36 /* EqualsEqualsEqualsToken */;
9755                             }
9756                             return pos += 2, token = 34 /* EqualsEqualsToken */;
9757                         }
9758                         if (text.charCodeAt(pos + 1) === 62 /* greaterThan */) {
9759                             return pos += 2, token = 38 /* EqualsGreaterThanToken */;
9760                         }
9761                         pos++;
9762                         return token = 62 /* EqualsToken */;
9763                     case 62 /* greaterThan */:
9764                         if (isConflictMarkerTrivia(text, pos)) {
9765                             pos = scanConflictMarkerTrivia(text, pos, error);
9766                             if (skipTrivia) {
9767                                 continue;
9768                             }
9769                             else {
9770                                 return token = 7 /* ConflictMarkerTrivia */;
9771                             }
9772                         }
9773                         pos++;
9774                         return token = 31 /* GreaterThanToken */;
9775                     case 63 /* question */:
9776                         pos++;
9777                         if (text.charCodeAt(pos) === 46 /* dot */ && !isDigit(text.charCodeAt(pos + 1))) {
9778                             pos++;
9779                             return token = 28 /* QuestionDotToken */;
9780                         }
9781                         if (text.charCodeAt(pos) === 63 /* question */) {
9782                             pos++;
9783                             return token = 60 /* QuestionQuestionToken */;
9784                         }
9785                         return token = 57 /* QuestionToken */;
9786                     case 91 /* openBracket */:
9787                         pos++;
9788                         return token = 22 /* OpenBracketToken */;
9789                     case 93 /* closeBracket */:
9790                         pos++;
9791                         return token = 23 /* CloseBracketToken */;
9792                     case 94 /* caret */:
9793                         if (text.charCodeAt(pos + 1) === 61 /* equals */) {
9794                             return pos += 2, token = 74 /* CaretEqualsToken */;
9795                         }
9796                         pos++;
9797                         return token = 52 /* CaretToken */;
9798                     case 123 /* openBrace */:
9799                         pos++;
9800                         return token = 18 /* OpenBraceToken */;
9801                     case 124 /* bar */:
9802                         if (isConflictMarkerTrivia(text, pos)) {
9803                             pos = scanConflictMarkerTrivia(text, pos, error);
9804                             if (skipTrivia) {
9805                                 continue;
9806                             }
9807                             else {
9808                                 return token = 7 /* ConflictMarkerTrivia */;
9809                             }
9810                         }
9811                         if (text.charCodeAt(pos + 1) === 124 /* bar */) {
9812                             return pos += 2, token = 56 /* BarBarToken */;
9813                         }
9814                         if (text.charCodeAt(pos + 1) === 61 /* equals */) {
9815                             return pos += 2, token = 73 /* BarEqualsToken */;
9816                         }
9817                         pos++;
9818                         return token = 51 /* BarToken */;
9819                     case 125 /* closeBrace */:
9820                         pos++;
9821                         return token = 19 /* CloseBraceToken */;
9822                     case 126 /* tilde */:
9823                         pos++;
9824                         return token = 54 /* TildeToken */;
9825                     case 64 /* at */:
9826                         pos++;
9827                         return token = 59 /* AtToken */;
9828                     case 92 /* backslash */:
9829                         var extendedCookedChar = peekExtendedUnicodeEscape();
9830                         if (extendedCookedChar >= 0 && isIdentifierStart(extendedCookedChar, languageVersion)) {
9831                             pos += 3;
9832                             tokenFlags |= 8 /* ExtendedUnicodeEscape */;
9833                             tokenValue = scanExtendedUnicodeEscape() + scanIdentifierParts();
9834                             return token = getIdentifierToken();
9835                         }
9836                         var cookedChar = peekUnicodeEscape();
9837                         if (cookedChar >= 0 && isIdentifierStart(cookedChar, languageVersion)) {
9838                             pos += 6;
9839                             tokenFlags |= 1024 /* UnicodeEscape */;
9840                             tokenValue = String.fromCharCode(cookedChar) + scanIdentifierParts();
9841                             return token = getIdentifierToken();
9842                         }
9843                         error(ts.Diagnostics.Invalid_character);
9844                         pos++;
9845                         return token = 0 /* Unknown */;
9846                     case 35 /* hash */:
9847                         if (pos !== 0 && text[pos + 1] === "!") {
9848                             error(ts.Diagnostics.can_only_be_used_at_the_start_of_a_file);
9849                             pos++;
9850                             return token = 0 /* Unknown */;
9851                         }
9852                         pos++;
9853                         if (isIdentifierStart(ch = text.charCodeAt(pos), languageVersion)) {
9854                             pos++;
9855                             while (pos < end && isIdentifierPart(ch = text.charCodeAt(pos), languageVersion))
9856                                 pos++;
9857                             tokenValue = text.substring(tokenPos, pos);
9858                             if (ch === 92 /* backslash */) {
9859                                 tokenValue += scanIdentifierParts();
9860                             }
9861                         }
9862                         else {
9863                             tokenValue = "#";
9864                             error(ts.Diagnostics.Invalid_character);
9865                         }
9866                         return token = 76 /* PrivateIdentifier */;
9867                     default:
9868                         if (isIdentifierStart(ch, languageVersion)) {
9869                             pos += charSize(ch);
9870                             while (pos < end && isIdentifierPart(ch = codePointAt(text, pos), languageVersion))
9871                                 pos += charSize(ch);
9872                             tokenValue = text.substring(tokenPos, pos);
9873                             if (ch === 92 /* backslash */) {
9874                                 tokenValue += scanIdentifierParts();
9875                             }
9876                             return token = getIdentifierToken();
9877                         }
9878                         else if (isWhiteSpaceSingleLine(ch)) {
9879                             pos += charSize(ch);
9880                             continue;
9881                         }
9882                         else if (isLineBreak(ch)) {
9883                             tokenFlags |= 1 /* PrecedingLineBreak */;
9884                             pos += charSize(ch);
9885                             continue;
9886                         }
9887                         error(ts.Diagnostics.Invalid_character);
9888                         pos += charSize(ch);
9889                         return token = 0 /* Unknown */;
9890                 }
9891             }
9892         }
9893         function reScanGreaterToken() {
9894             if (token === 31 /* GreaterThanToken */) {
9895                 if (text.charCodeAt(pos) === 62 /* greaterThan */) {
9896                     if (text.charCodeAt(pos + 1) === 62 /* greaterThan */) {
9897                         if (text.charCodeAt(pos + 2) === 61 /* equals */) {
9898                             return pos += 3, token = 71 /* GreaterThanGreaterThanGreaterThanEqualsToken */;
9899                         }
9900                         return pos += 2, token = 49 /* GreaterThanGreaterThanGreaterThanToken */;
9901                     }
9902                     if (text.charCodeAt(pos + 1) === 61 /* equals */) {
9903                         return pos += 2, token = 70 /* GreaterThanGreaterThanEqualsToken */;
9904                     }
9905                     pos++;
9906                     return token = 48 /* GreaterThanGreaterThanToken */;
9907                 }
9908                 if (text.charCodeAt(pos) === 61 /* equals */) {
9909                     pos++;
9910                     return token = 33 /* GreaterThanEqualsToken */;
9911                 }
9912             }
9913             return token;
9914         }
9915         function reScanSlashToken() {
9916             if (token === 43 /* SlashToken */ || token === 67 /* SlashEqualsToken */) {
9917                 var p = tokenPos + 1;
9918                 var inEscape = false;
9919                 var inCharacterClass = false;
9920                 while (true) {
9921                     // If we reach the end of a file, or hit a newline, then this is an unterminated
9922                     // regex.  Report error and return what we have so far.
9923                     if (p >= end) {
9924                         tokenFlags |= 4 /* Unterminated */;
9925                         error(ts.Diagnostics.Unterminated_regular_expression_literal);
9926                         break;
9927                     }
9928                     var ch = text.charCodeAt(p);
9929                     if (isLineBreak(ch)) {
9930                         tokenFlags |= 4 /* Unterminated */;
9931                         error(ts.Diagnostics.Unterminated_regular_expression_literal);
9932                         break;
9933                     }
9934                     if (inEscape) {
9935                         // Parsing an escape character;
9936                         // reset the flag and just advance to the next char.
9937                         inEscape = false;
9938                     }
9939                     else if (ch === 47 /* slash */ && !inCharacterClass) {
9940                         // A slash within a character class is permissible,
9941                         // but in general it signals the end of the regexp literal.
9942                         p++;
9943                         break;
9944                     }
9945                     else if (ch === 91 /* openBracket */) {
9946                         inCharacterClass = true;
9947                     }
9948                     else if (ch === 92 /* backslash */) {
9949                         inEscape = true;
9950                     }
9951                     else if (ch === 93 /* closeBracket */) {
9952                         inCharacterClass = false;
9953                     }
9954                     p++;
9955                 }
9956                 while (p < end && isIdentifierPart(text.charCodeAt(p), languageVersion)) {
9957                     p++;
9958                 }
9959                 pos = p;
9960                 tokenValue = text.substring(tokenPos, pos);
9961                 token = 13 /* RegularExpressionLiteral */;
9962             }
9963             return token;
9964         }
9965         function appendIfCommentDirective(commentDirectives, text, commentDirectiveRegEx, lineStart) {
9966             var type = getDirectiveFromComment(text, commentDirectiveRegEx);
9967             if (type === undefined) {
9968                 return commentDirectives;
9969             }
9970             return ts.append(commentDirectives, {
9971                 range: { pos: lineStart, end: pos },
9972                 type: type,
9973             });
9974         }
9975         function getDirectiveFromComment(text, commentDirectiveRegEx) {
9976             var match = commentDirectiveRegEx.exec(text);
9977             if (!match) {
9978                 return undefined;
9979             }
9980             switch (match[1]) {
9981                 case "ts-expect-error":
9982                     return 0 /* ExpectError */;
9983                 case "ts-ignore":
9984                     return 1 /* Ignore */;
9985             }
9986             return undefined;
9987         }
9988         /**
9989          * Unconditionally back up and scan a template expression portion.
9990          */
9991         function reScanTemplateToken(isTaggedTemplate) {
9992             ts.Debug.assert(token === 19 /* CloseBraceToken */, "'reScanTemplateToken' should only be called on a '}'");
9993             pos = tokenPos;
9994             return token = scanTemplateAndSetTokenValue(isTaggedTemplate);
9995         }
9996         function reScanTemplateHeadOrNoSubstitutionTemplate() {
9997             pos = tokenPos;
9998             return token = scanTemplateAndSetTokenValue(/* isTaggedTemplate */ true);
9999         }
10000         function reScanJsxToken() {
10001             pos = tokenPos = startPos;
10002             return token = scanJsxToken();
10003         }
10004         function reScanLessThanToken() {
10005             if (token === 47 /* LessThanLessThanToken */) {
10006                 pos = tokenPos + 1;
10007                 return token = 29 /* LessThanToken */;
10008             }
10009             return token;
10010         }
10011         function reScanQuestionToken() {
10012             ts.Debug.assert(token === 60 /* QuestionQuestionToken */, "'reScanQuestionToken' should only be called on a '??'");
10013             pos = tokenPos + 1;
10014             return token = 57 /* QuestionToken */;
10015         }
10016         function scanJsxToken() {
10017             startPos = tokenPos = pos;
10018             if (pos >= end) {
10019                 return token = 1 /* EndOfFileToken */;
10020             }
10021             var char = text.charCodeAt(pos);
10022             if (char === 60 /* lessThan */) {
10023                 if (text.charCodeAt(pos + 1) === 47 /* slash */) {
10024                     pos += 2;
10025                     return token = 30 /* LessThanSlashToken */;
10026                 }
10027                 pos++;
10028                 return token = 29 /* LessThanToken */;
10029             }
10030             if (char === 123 /* openBrace */) {
10031                 pos++;
10032                 return token = 18 /* OpenBraceToken */;
10033             }
10034             // First non-whitespace character on this line.
10035             var firstNonWhitespace = 0;
10036             var lastNonWhitespace = -1;
10037             // These initial values are special because the first line is:
10038             // firstNonWhitespace = 0 to indicate that we want leading whitespace,
10039             while (pos < end) {
10040                 // We want to keep track of the last non-whitespace (but including
10041                 // newlines character for hitting the end of the JSX Text region)
10042                 if (!isWhiteSpaceSingleLine(char)) {
10043                     lastNonWhitespace = pos;
10044                 }
10045                 char = text.charCodeAt(pos);
10046                 if (char === 123 /* openBrace */) {
10047                     break;
10048                 }
10049                 if (char === 60 /* lessThan */) {
10050                     if (isConflictMarkerTrivia(text, pos)) {
10051                         pos = scanConflictMarkerTrivia(text, pos, error);
10052                         return token = 7 /* ConflictMarkerTrivia */;
10053                     }
10054                     break;
10055                 }
10056                 if (char === 62 /* greaterThan */) {
10057                     error(ts.Diagnostics.Unexpected_token_Did_you_mean_or_gt, pos, 1);
10058                 }
10059                 if (char === 125 /* closeBrace */) {
10060                     error(ts.Diagnostics.Unexpected_token_Did_you_mean_or_rbrace, pos, 1);
10061                 }
10062                 if (lastNonWhitespace > 0)
10063                     lastNonWhitespace++;
10064                 // FirstNonWhitespace is 0, then we only see whitespaces so far. If we see a linebreak, we want to ignore that whitespaces.
10065                 // i.e (- : whitespace)
10066                 //      <div>----
10067                 //      </div> becomes <div></div>
10068                 //
10069                 //      <div>----</div> becomes <div>----</div>
10070                 if (isLineBreak(char) && firstNonWhitespace === 0) {
10071                     firstNonWhitespace = -1;
10072                 }
10073                 else if (!isWhiteSpaceLike(char)) {
10074                     firstNonWhitespace = pos;
10075                 }
10076                 pos++;
10077             }
10078             var endPosition = lastNonWhitespace === -1 ? pos : lastNonWhitespace;
10079             tokenValue = text.substring(startPos, endPosition);
10080             return firstNonWhitespace === -1 ? 12 /* JsxTextAllWhiteSpaces */ : 11 /* JsxText */;
10081         }
10082         // Scans a JSX identifier; these differ from normal identifiers in that
10083         // they allow dashes
10084         function scanJsxIdentifier() {
10085             if (tokenIsIdentifierOrKeyword(token)) {
10086                 // An identifier or keyword has already been parsed - check for a `-` and then append it and everything after it to the token
10087                 // Do note that this means that `scanJsxIdentifier` effectively _mutates_ the visible token without advancing to a new token
10088                 // Any caller should be expecting this behavior and should only read the pos or token value after calling it.
10089                 while (pos < end) {
10090                     var ch = text.charCodeAt(pos);
10091                     if (ch === 45 /* minus */) {
10092                         tokenValue += "-";
10093                         pos++;
10094                         continue;
10095                     }
10096                     var oldPos = pos;
10097                     tokenValue += scanIdentifierParts(); // reuse `scanIdentifierParts` so unicode escapes are handled
10098                     if (pos === oldPos) {
10099                         break;
10100                     }
10101                 }
10102             }
10103             return token;
10104         }
10105         function scanJsxAttributeValue() {
10106             startPos = pos;
10107             switch (text.charCodeAt(pos)) {
10108                 case 34 /* doubleQuote */:
10109                 case 39 /* singleQuote */:
10110                     tokenValue = scanString(/*jsxAttributeString*/ true);
10111                     return token = 10 /* StringLiteral */;
10112                 default:
10113                     // If this scans anything other than `{`, it's a parse error.
10114                     return scan();
10115             }
10116         }
10117         function reScanJsxAttributeValue() {
10118             pos = tokenPos = startPos;
10119             return scanJsxAttributeValue();
10120         }
10121         function scanJsDocToken() {
10122             startPos = tokenPos = pos;
10123             tokenFlags = 0 /* None */;
10124             if (pos >= end) {
10125                 return token = 1 /* EndOfFileToken */;
10126             }
10127             var ch = codePointAt(text, pos);
10128             pos += charSize(ch);
10129             switch (ch) {
10130                 case 9 /* tab */:
10131                 case 11 /* verticalTab */:
10132                 case 12 /* formFeed */:
10133                 case 32 /* space */:
10134                     while (pos < end && isWhiteSpaceSingleLine(text.charCodeAt(pos))) {
10135                         pos++;
10136                     }
10137                     return token = 5 /* WhitespaceTrivia */;
10138                 case 64 /* at */:
10139                     return token = 59 /* AtToken */;
10140                 case 10 /* lineFeed */:
10141                 case 13 /* carriageReturn */:
10142                     tokenFlags |= 1 /* PrecedingLineBreak */;
10143                     return token = 4 /* NewLineTrivia */;
10144                 case 42 /* asterisk */:
10145                     return token = 41 /* AsteriskToken */;
10146                 case 123 /* openBrace */:
10147                     return token = 18 /* OpenBraceToken */;
10148                 case 125 /* closeBrace */:
10149                     return token = 19 /* CloseBraceToken */;
10150                 case 91 /* openBracket */:
10151                     return token = 22 /* OpenBracketToken */;
10152                 case 93 /* closeBracket */:
10153                     return token = 23 /* CloseBracketToken */;
10154                 case 60 /* lessThan */:
10155                     return token = 29 /* LessThanToken */;
10156                 case 62 /* greaterThan */:
10157                     return token = 31 /* GreaterThanToken */;
10158                 case 61 /* equals */:
10159                     return token = 62 /* EqualsToken */;
10160                 case 44 /* comma */:
10161                     return token = 27 /* CommaToken */;
10162                 case 46 /* dot */:
10163                     return token = 24 /* DotToken */;
10164                 case 96 /* backtick */:
10165                     return token = 61 /* BacktickToken */;
10166                 case 92 /* backslash */:
10167                     pos--;
10168                     var extendedCookedChar = peekExtendedUnicodeEscape();
10169                     if (extendedCookedChar >= 0 && isIdentifierStart(extendedCookedChar, languageVersion)) {
10170                         pos += 3;
10171                         tokenFlags |= 8 /* ExtendedUnicodeEscape */;
10172                         tokenValue = scanExtendedUnicodeEscape() + scanIdentifierParts();
10173                         return token = getIdentifierToken();
10174                     }
10175                     var cookedChar = peekUnicodeEscape();
10176                     if (cookedChar >= 0 && isIdentifierStart(cookedChar, languageVersion)) {
10177                         pos += 6;
10178                         tokenFlags |= 1024 /* UnicodeEscape */;
10179                         tokenValue = String.fromCharCode(cookedChar) + scanIdentifierParts();
10180                         return token = getIdentifierToken();
10181                     }
10182                     pos++;
10183                     return token = 0 /* Unknown */;
10184             }
10185             if (isIdentifierStart(ch, languageVersion)) {
10186                 var char = ch;
10187                 while (pos < end && isIdentifierPart(char = codePointAt(text, pos), languageVersion) || text.charCodeAt(pos) === 45 /* minus */)
10188                     pos += charSize(char);
10189                 tokenValue = text.substring(tokenPos, pos);
10190                 if (char === 92 /* backslash */) {
10191                     tokenValue += scanIdentifierParts();
10192                 }
10193                 return token = getIdentifierToken();
10194             }
10195             else {
10196                 return token = 0 /* Unknown */;
10197             }
10198         }
10199         function speculationHelper(callback, isLookahead) {
10200             var savePos = pos;
10201             var saveStartPos = startPos;
10202             var saveTokenPos = tokenPos;
10203             var saveToken = token;
10204             var saveTokenValue = tokenValue;
10205             var saveTokenFlags = tokenFlags;
10206             var result = callback();
10207             // If our callback returned something 'falsy' or we're just looking ahead,
10208             // then unconditionally restore us to where we were.
10209             if (!result || isLookahead) {
10210                 pos = savePos;
10211                 startPos = saveStartPos;
10212                 tokenPos = saveTokenPos;
10213                 token = saveToken;
10214                 tokenValue = saveTokenValue;
10215                 tokenFlags = saveTokenFlags;
10216             }
10217             return result;
10218         }
10219         function scanRange(start, length, callback) {
10220             var saveEnd = end;
10221             var savePos = pos;
10222             var saveStartPos = startPos;
10223             var saveTokenPos = tokenPos;
10224             var saveToken = token;
10225             var saveTokenValue = tokenValue;
10226             var saveTokenFlags = tokenFlags;
10227             var saveErrorExpectations = commentDirectives;
10228             setText(text, start, length);
10229             var result = callback();
10230             end = saveEnd;
10231             pos = savePos;
10232             startPos = saveStartPos;
10233             tokenPos = saveTokenPos;
10234             token = saveToken;
10235             tokenValue = saveTokenValue;
10236             tokenFlags = saveTokenFlags;
10237             commentDirectives = saveErrorExpectations;
10238             return result;
10239         }
10240         function lookAhead(callback) {
10241             return speculationHelper(callback, /*isLookahead*/ true);
10242         }
10243         function tryScan(callback) {
10244             return speculationHelper(callback, /*isLookahead*/ false);
10245         }
10246         function getText() {
10247             return text;
10248         }
10249         function clearCommentDirectives() {
10250             commentDirectives = undefined;
10251         }
10252         function setText(newText, start, length) {
10253             text = newText || "";
10254             end = length === undefined ? text.length : start + length;
10255             setTextPos(start || 0);
10256         }
10257         function setOnError(errorCallback) {
10258             onError = errorCallback;
10259         }
10260         function setScriptTarget(scriptTarget) {
10261             languageVersion = scriptTarget;
10262         }
10263         function setLanguageVariant(variant) {
10264             languageVariant = variant;
10265         }
10266         function setTextPos(textPos) {
10267             ts.Debug.assert(textPos >= 0);
10268             pos = textPos;
10269             startPos = textPos;
10270             tokenPos = textPos;
10271             token = 0 /* Unknown */;
10272             tokenValue = undefined;
10273             tokenFlags = 0 /* None */;
10274         }
10275         function setInJSDocType(inType) {
10276             inJSDocType += inType ? 1 : -1;
10277         }
10278     }
10279     ts.createScanner = createScanner;
10280     /* @internal */
10281     var codePointAt = String.prototype.codePointAt ? function (s, i) { return s.codePointAt(i); } : function codePointAt(str, i) {
10282         // from https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/codePointAt
10283         var size = str.length;
10284         // Account for out-of-bounds indices:
10285         if (i < 0 || i >= size) {
10286             return undefined; // String.codePointAt returns `undefined` for OOB indexes
10287         }
10288         // Get the first code unit
10289         var first = str.charCodeAt(i);
10290         // check if it’s the start of a surrogate pair
10291         if (first >= 0xD800 && first <= 0xDBFF && size > i + 1) { // high surrogate and there is a next code unit
10292             var second = str.charCodeAt(i + 1);
10293             if (second >= 0xDC00 && second <= 0xDFFF) { // low surrogate
10294                 // https://mathiasbynens.be/notes/javascript-encoding#surrogate-formulae
10295                 return (first - 0xD800) * 0x400 + second - 0xDC00 + 0x10000;
10296             }
10297         }
10298         return first;
10299     };
10300     /* @internal */
10301     function charSize(ch) {
10302         if (ch >= 0x10000) {
10303             return 2;
10304         }
10305         return 1;
10306     }
10307     // Derived from the 10.1.1 UTF16Encoding of the ES6 Spec.
10308     function utf16EncodeAsStringFallback(codePoint) {
10309         ts.Debug.assert(0x0 <= codePoint && codePoint <= 0x10FFFF);
10310         if (codePoint <= 65535) {
10311             return String.fromCharCode(codePoint);
10312         }
10313         var codeUnit1 = Math.floor((codePoint - 65536) / 1024) + 0xD800;
10314         var codeUnit2 = ((codePoint - 65536) % 1024) + 0xDC00;
10315         return String.fromCharCode(codeUnit1, codeUnit2);
10316     }
10317     var utf16EncodeAsStringWorker = String.fromCodePoint ? function (codePoint) { return String.fromCodePoint(codePoint); } : utf16EncodeAsStringFallback;
10318     /* @internal */
10319     function utf16EncodeAsString(codePoint) {
10320         return utf16EncodeAsStringWorker(codePoint);
10321     }
10322     ts.utf16EncodeAsString = utf16EncodeAsString;
10323 })(ts || (ts = {}));
10324 var ts;
10325 (function (ts) {
10326     function isExternalModuleNameRelative(moduleName) {
10327         // TypeScript 1.0 spec (April 2014): 11.2.1
10328         // An external module name is "relative" if the first term is "." or "..".
10329         // 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.
10330         return ts.pathIsRelative(moduleName) || ts.isRootedDiskPath(moduleName);
10331     }
10332     ts.isExternalModuleNameRelative = isExternalModuleNameRelative;
10333     function sortAndDeduplicateDiagnostics(diagnostics) {
10334         return ts.sortAndDeduplicate(diagnostics, ts.compareDiagnostics);
10335     }
10336     ts.sortAndDeduplicateDiagnostics = sortAndDeduplicateDiagnostics;
10337     function getDefaultLibFileName(options) {
10338         switch (options.target) {
10339             case 99 /* ESNext */:
10340                 return "lib.esnext.full.d.ts";
10341             case 7 /* ES2020 */:
10342                 return "lib.es2020.full.d.ts";
10343             case 6 /* ES2019 */:
10344                 return "lib.es2019.full.d.ts";
10345             case 5 /* ES2018 */:
10346                 return "lib.es2018.full.d.ts";
10347             case 4 /* ES2017 */:
10348                 return "lib.es2017.full.d.ts";
10349             case 3 /* ES2016 */:
10350                 return "lib.es2016.full.d.ts";
10351             case 2 /* ES2015 */:
10352                 return "lib.es6.d.ts"; // We don't use lib.es2015.full.d.ts due to breaking change.
10353             default:
10354                 return "lib.d.ts";
10355         }
10356     }
10357     ts.getDefaultLibFileName = getDefaultLibFileName;
10358     function textSpanEnd(span) {
10359         return span.start + span.length;
10360     }
10361     ts.textSpanEnd = textSpanEnd;
10362     function textSpanIsEmpty(span) {
10363         return span.length === 0;
10364     }
10365     ts.textSpanIsEmpty = textSpanIsEmpty;
10366     function textSpanContainsPosition(span, position) {
10367         return position >= span.start && position < textSpanEnd(span);
10368     }
10369     ts.textSpanContainsPosition = textSpanContainsPosition;
10370     /* @internal */
10371     function textRangeContainsPositionInclusive(span, position) {
10372         return position >= span.pos && position <= span.end;
10373     }
10374     ts.textRangeContainsPositionInclusive = textRangeContainsPositionInclusive;
10375     // Returns true if 'span' contains 'other'.
10376     function textSpanContainsTextSpan(span, other) {
10377         return other.start >= span.start && textSpanEnd(other) <= textSpanEnd(span);
10378     }
10379     ts.textSpanContainsTextSpan = textSpanContainsTextSpan;
10380     function textSpanOverlapsWith(span, other) {
10381         return textSpanOverlap(span, other) !== undefined;
10382     }
10383     ts.textSpanOverlapsWith = textSpanOverlapsWith;
10384     function textSpanOverlap(span1, span2) {
10385         var overlap = textSpanIntersection(span1, span2);
10386         return overlap && overlap.length === 0 ? undefined : overlap;
10387     }
10388     ts.textSpanOverlap = textSpanOverlap;
10389     function textSpanIntersectsWithTextSpan(span, other) {
10390         return decodedTextSpanIntersectsWith(span.start, span.length, other.start, other.length);
10391     }
10392     ts.textSpanIntersectsWithTextSpan = textSpanIntersectsWithTextSpan;
10393     function textSpanIntersectsWith(span, start, length) {
10394         return decodedTextSpanIntersectsWith(span.start, span.length, start, length);
10395     }
10396     ts.textSpanIntersectsWith = textSpanIntersectsWith;
10397     function decodedTextSpanIntersectsWith(start1, length1, start2, length2) {
10398         var end1 = start1 + length1;
10399         var end2 = start2 + length2;
10400         return start2 <= end1 && end2 >= start1;
10401     }
10402     ts.decodedTextSpanIntersectsWith = decodedTextSpanIntersectsWith;
10403     function textSpanIntersectsWithPosition(span, position) {
10404         return position <= textSpanEnd(span) && position >= span.start;
10405     }
10406     ts.textSpanIntersectsWithPosition = textSpanIntersectsWithPosition;
10407     function textSpanIntersection(span1, span2) {
10408         var start = Math.max(span1.start, span2.start);
10409         var end = Math.min(textSpanEnd(span1), textSpanEnd(span2));
10410         return start <= end ? createTextSpanFromBounds(start, end) : undefined;
10411     }
10412     ts.textSpanIntersection = textSpanIntersection;
10413     function createTextSpan(start, length) {
10414         if (start < 0) {
10415             throw new Error("start < 0");
10416         }
10417         if (length < 0) {
10418             throw new Error("length < 0");
10419         }
10420         return { start: start, length: length };
10421     }
10422     ts.createTextSpan = createTextSpan;
10423     function createTextSpanFromBounds(start, end) {
10424         return createTextSpan(start, end - start);
10425     }
10426     ts.createTextSpanFromBounds = createTextSpanFromBounds;
10427     function textChangeRangeNewSpan(range) {
10428         return createTextSpan(range.span.start, range.newLength);
10429     }
10430     ts.textChangeRangeNewSpan = textChangeRangeNewSpan;
10431     function textChangeRangeIsUnchanged(range) {
10432         return textSpanIsEmpty(range.span) && range.newLength === 0;
10433     }
10434     ts.textChangeRangeIsUnchanged = textChangeRangeIsUnchanged;
10435     function createTextChangeRange(span, newLength) {
10436         if (newLength < 0) {
10437             throw new Error("newLength < 0");
10438         }
10439         return { span: span, newLength: newLength };
10440     }
10441     ts.createTextChangeRange = createTextChangeRange;
10442     ts.unchangedTextChangeRange = createTextChangeRange(createTextSpan(0, 0), 0); // eslint-disable-line prefer-const
10443     /**
10444      * Called to merge all the changes that occurred across several versions of a script snapshot
10445      * into a single change.  i.e. if a user keeps making successive edits to a script we will
10446      * have a text change from V1 to V2, V2 to V3, ..., Vn.
10447      *
10448      * This function will then merge those changes into a single change range valid between V1 and
10449      * Vn.
10450      */
10451     function collapseTextChangeRangesAcrossMultipleVersions(changes) {
10452         if (changes.length === 0) {
10453             return ts.unchangedTextChangeRange;
10454         }
10455         if (changes.length === 1) {
10456             return changes[0];
10457         }
10458         // We change from talking about { { oldStart, oldLength }, newLength } to { oldStart, oldEnd, newEnd }
10459         // as it makes things much easier to reason about.
10460         var change0 = changes[0];
10461         var oldStartN = change0.span.start;
10462         var oldEndN = textSpanEnd(change0.span);
10463         var newEndN = oldStartN + change0.newLength;
10464         for (var i = 1; i < changes.length; i++) {
10465             var nextChange = changes[i];
10466             // Consider the following case:
10467             // i.e. two edits.  The first represents the text change range { { 10, 50 }, 30 }.  i.e. The span starting
10468             // at 10, with length 50 is reduced to length 30.  The second represents the text change range { { 30, 30 }, 40 }.
10469             // i.e. the span starting at 30 with length 30 is increased to length 40.
10470             //
10471             //      0         10        20        30        40        50        60        70        80        90        100
10472             //      -------------------------------------------------------------------------------------------------------
10473             //                |                                                 /
10474             //                |                                            /----
10475             //  T1            |                                       /----
10476             //                |                                  /----
10477             //                |                             /----
10478             //      -------------------------------------------------------------------------------------------------------
10479             //                                     |                            \
10480             //                                     |                               \
10481             //   T2                                |                                 \
10482             //                                     |                                   \
10483             //                                     |                                      \
10484             //      -------------------------------------------------------------------------------------------------------
10485             //
10486             // Merging these turns out to not be too difficult.  First, determining the new start of the change is trivial
10487             // it's just the min of the old and new starts.  i.e.:
10488             //
10489             //      0         10        20        30        40        50        60        70        80        90        100
10490             //      ------------------------------------------------------------*------------------------------------------
10491             //                |                                                 /
10492             //                |                                            /----
10493             //  T1            |                                       /----
10494             //                |                                  /----
10495             //                |                             /----
10496             //      ----------------------------------------$-------------------$------------------------------------------
10497             //                .                    |                            \
10498             //                .                    |                               \
10499             //   T2           .                    |                                 \
10500             //                .                    |                                   \
10501             //                .                    |                                      \
10502             //      ----------------------------------------------------------------------*--------------------------------
10503             //
10504             // (Note the dots represent the newly inferred start.
10505             // Determining the new and old end is also pretty simple.  Basically it boils down to paying attention to the
10506             // absolute positions at the asterisks, and the relative change between the dollar signs. Basically, we see
10507             // which if the two $'s precedes the other, and we move that one forward until they line up.  in this case that
10508             // means:
10509             //
10510             //      0         10        20        30        40        50        60        70        80        90        100
10511             //      --------------------------------------------------------------------------------*----------------------
10512             //                |                                                                     /
10513             //                |                                                                /----
10514             //  T1            |                                                           /----
10515             //                |                                                      /----
10516             //                |                                                 /----
10517             //      ------------------------------------------------------------$------------------------------------------
10518             //                .                    |                            \
10519             //                .                    |                               \
10520             //   T2           .                    |                                 \
10521             //                .                    |                                   \
10522             //                .                    |                                      \
10523             //      ----------------------------------------------------------------------*--------------------------------
10524             //
10525             // In other words (in this case), we're recognizing that the second edit happened after where the first edit
10526             // ended with a delta of 20 characters (60 - 40).  Thus, if we go back in time to where the first edit started
10527             // that's the same as if we started at char 80 instead of 60.
10528             //
10529             // As it so happens, the same logic applies if the second edit precedes the first edit.  In that case rather
10530             // than pushing the first edit forward to match the second, we'll push the second edit forward to match the
10531             // first.
10532             //
10533             // In this case that means we have { oldStart: 10, oldEnd: 80, newEnd: 70 } or, in TextChangeRange
10534             // semantics: { { start: 10, length: 70 }, newLength: 60 }
10535             //
10536             // The math then works out as follows.
10537             // If we have { oldStart1, oldEnd1, newEnd1 } and { oldStart2, oldEnd2, newEnd2 } then we can compute the
10538             // final result like so:
10539             //
10540             // {
10541             //      oldStart3: Min(oldStart1, oldStart2),
10542             //      oldEnd3: Max(oldEnd1, oldEnd1 + (oldEnd2 - newEnd1)),
10543             //      newEnd3: Max(newEnd2, newEnd2 + (newEnd1 - oldEnd2))
10544             // }
10545             var oldStart1 = oldStartN;
10546             var oldEnd1 = oldEndN;
10547             var newEnd1 = newEndN;
10548             var oldStart2 = nextChange.span.start;
10549             var oldEnd2 = textSpanEnd(nextChange.span);
10550             var newEnd2 = oldStart2 + nextChange.newLength;
10551             oldStartN = Math.min(oldStart1, oldStart2);
10552             oldEndN = Math.max(oldEnd1, oldEnd1 + (oldEnd2 - newEnd1));
10553             newEndN = Math.max(newEnd2, newEnd2 + (newEnd1 - oldEnd2));
10554         }
10555         return createTextChangeRange(createTextSpanFromBounds(oldStartN, oldEndN), /*newLength*/ newEndN - oldStartN);
10556     }
10557     ts.collapseTextChangeRangesAcrossMultipleVersions = collapseTextChangeRangesAcrossMultipleVersions;
10558     function getTypeParameterOwner(d) {
10559         if (d && d.kind === 155 /* TypeParameter */) {
10560             for (var current = d; current; current = current.parent) {
10561                 if (isFunctionLike(current) || isClassLike(current) || current.kind === 246 /* InterfaceDeclaration */) {
10562                     return current;
10563                 }
10564             }
10565         }
10566     }
10567     ts.getTypeParameterOwner = getTypeParameterOwner;
10568     function isParameterPropertyDeclaration(node, parent) {
10569         return ts.hasModifier(node, 92 /* ParameterPropertyModifier */) && parent.kind === 162 /* Constructor */;
10570     }
10571     ts.isParameterPropertyDeclaration = isParameterPropertyDeclaration;
10572     function isEmptyBindingPattern(node) {
10573         if (isBindingPattern(node)) {
10574             return ts.every(node.elements, isEmptyBindingElement);
10575         }
10576         return false;
10577     }
10578     ts.isEmptyBindingPattern = isEmptyBindingPattern;
10579     function isEmptyBindingElement(node) {
10580         if (isOmittedExpression(node)) {
10581             return true;
10582         }
10583         return isEmptyBindingPattern(node.name);
10584     }
10585     ts.isEmptyBindingElement = isEmptyBindingElement;
10586     function walkUpBindingElementsAndPatterns(binding) {
10587         var node = binding.parent;
10588         while (isBindingElement(node.parent)) {
10589             node = node.parent.parent;
10590         }
10591         return node.parent;
10592     }
10593     ts.walkUpBindingElementsAndPatterns = walkUpBindingElementsAndPatterns;
10594     function getCombinedFlags(node, getFlags) {
10595         if (isBindingElement(node)) {
10596             node = walkUpBindingElementsAndPatterns(node);
10597         }
10598         var flags = getFlags(node);
10599         if (node.kind === 242 /* VariableDeclaration */) {
10600             node = node.parent;
10601         }
10602         if (node && node.kind === 243 /* VariableDeclarationList */) {
10603             flags |= getFlags(node);
10604             node = node.parent;
10605         }
10606         if (node && node.kind === 225 /* VariableStatement */) {
10607             flags |= getFlags(node);
10608         }
10609         return flags;
10610     }
10611     function getCombinedModifierFlags(node) {
10612         return getCombinedFlags(node, ts.getModifierFlags);
10613     }
10614     ts.getCombinedModifierFlags = getCombinedModifierFlags;
10615     // Returns the node flags for this node and all relevant parent nodes.  This is done so that
10616     // nodes like variable declarations and binding elements can returned a view of their flags
10617     // that includes the modifiers from their container.  i.e. flags like export/declare aren't
10618     // stored on the variable declaration directly, but on the containing variable statement
10619     // (if it has one).  Similarly, flags for let/const are store on the variable declaration
10620     // list.  By calling this function, all those flags are combined so that the client can treat
10621     // the node as if it actually had those flags.
10622     function getCombinedNodeFlags(node) {
10623         return getCombinedFlags(node, function (n) { return n.flags; });
10624     }
10625     ts.getCombinedNodeFlags = getCombinedNodeFlags;
10626     /**
10627      * Checks to see if the locale is in the appropriate format,
10628      * and if it is, attempts to set the appropriate language.
10629      */
10630     function validateLocaleAndSetLanguage(locale, sys, errors) {
10631         var matchResult = /^([a-z]+)([_\-]([a-z]+))?$/.exec(locale.toLowerCase());
10632         if (!matchResult) {
10633             if (errors) {
10634                 errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Locale_must_be_of_the_form_language_or_language_territory_For_example_0_or_1, "en", "ja-jp"));
10635             }
10636             return;
10637         }
10638         var language = matchResult[1];
10639         var territory = matchResult[3];
10640         // First try the entire locale, then fall back to just language if that's all we have.
10641         // Either ways do not fail, and fallback to the English diagnostic strings.
10642         if (!trySetLanguageAndTerritory(language, territory, errors)) {
10643             trySetLanguageAndTerritory(language, /*territory*/ undefined, errors);
10644         }
10645         // Set the UI locale for string collation
10646         ts.setUILocale(locale);
10647         function trySetLanguageAndTerritory(language, territory, errors) {
10648             var compilerFilePath = ts.normalizePath(sys.getExecutingFilePath());
10649             var containingDirectoryPath = ts.getDirectoryPath(compilerFilePath);
10650             var filePath = ts.combinePaths(containingDirectoryPath, language);
10651             if (territory) {
10652                 filePath = filePath + "-" + territory;
10653             }
10654             filePath = sys.resolvePath(ts.combinePaths(filePath, "diagnosticMessages.generated.json"));
10655             if (!sys.fileExists(filePath)) {
10656                 return false;
10657             }
10658             // TODO: Add codePage support for readFile?
10659             var fileContents = "";
10660             try {
10661                 fileContents = sys.readFile(filePath);
10662             }
10663             catch (e) {
10664                 if (errors) {
10665                     errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Unable_to_open_file_0, filePath));
10666                 }
10667                 return false;
10668             }
10669             try {
10670                 // this is a global mutation (or live binding update)!
10671                 ts.setLocalizedDiagnosticMessages(JSON.parse(fileContents));
10672             }
10673             catch (_a) {
10674                 if (errors) {
10675                     errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Corrupted_locale_file_0, filePath));
10676                 }
10677                 return false;
10678             }
10679             return true;
10680         }
10681     }
10682     ts.validateLocaleAndSetLanguage = validateLocaleAndSetLanguage;
10683     function getOriginalNode(node, nodeTest) {
10684         if (node) {
10685             while (node.original !== undefined) {
10686                 node = node.original;
10687             }
10688         }
10689         return !nodeTest || nodeTest(node) ? node : undefined;
10690     }
10691     ts.getOriginalNode = getOriginalNode;
10692     /**
10693      * Gets a value indicating whether a node originated in the parse tree.
10694      *
10695      * @param node The node to test.
10696      */
10697     function isParseTreeNode(node) {
10698         return (node.flags & 8 /* Synthesized */) === 0;
10699     }
10700     ts.isParseTreeNode = isParseTreeNode;
10701     function getParseTreeNode(node, nodeTest) {
10702         if (node === undefined || isParseTreeNode(node)) {
10703             return node;
10704         }
10705         node = getOriginalNode(node);
10706         if (isParseTreeNode(node) && (!nodeTest || nodeTest(node))) {
10707             return node;
10708         }
10709         return undefined;
10710     }
10711     ts.getParseTreeNode = getParseTreeNode;
10712     /** Add an extra underscore to identifiers that start with two underscores to avoid issues with magic names like '__proto__' */
10713     function escapeLeadingUnderscores(identifier) {
10714         return (identifier.length >= 2 && identifier.charCodeAt(0) === 95 /* _ */ && identifier.charCodeAt(1) === 95 /* _ */ ? "_" + identifier : identifier);
10715     }
10716     ts.escapeLeadingUnderscores = escapeLeadingUnderscores;
10717     /**
10718      * Remove extra underscore from escaped identifier text content.
10719      *
10720      * @param identifier The escaped identifier text.
10721      * @returns The unescaped identifier text.
10722      */
10723     function unescapeLeadingUnderscores(identifier) {
10724         var id = identifier;
10725         return id.length >= 3 && id.charCodeAt(0) === 95 /* _ */ && id.charCodeAt(1) === 95 /* _ */ && id.charCodeAt(2) === 95 /* _ */ ? id.substr(1) : id;
10726     }
10727     ts.unescapeLeadingUnderscores = unescapeLeadingUnderscores;
10728     function idText(identifierOrPrivateName) {
10729         return unescapeLeadingUnderscores(identifierOrPrivateName.escapedText);
10730     }
10731     ts.idText = idText;
10732     function symbolName(symbol) {
10733         if (symbol.valueDeclaration && isPrivateIdentifierPropertyDeclaration(symbol.valueDeclaration)) {
10734             return idText(symbol.valueDeclaration.name);
10735         }
10736         return unescapeLeadingUnderscores(symbol.escapedName);
10737     }
10738     ts.symbolName = symbolName;
10739     /**
10740      * A JSDocTypedef tag has an _optional_ name field - if a name is not directly present, we should
10741      * attempt to draw the name from the node the declaration is on (as that declaration is what its' symbol
10742      * will be merged with)
10743      */
10744     function nameForNamelessJSDocTypedef(declaration) {
10745         var hostNode = declaration.parent.parent;
10746         if (!hostNode) {
10747             return undefined;
10748         }
10749         // Covers classes, functions - any named declaration host node
10750         if (isDeclaration(hostNode)) {
10751             return getDeclarationIdentifier(hostNode);
10752         }
10753         // Covers remaining cases (returning undefined if none match).
10754         switch (hostNode.kind) {
10755             case 225 /* VariableStatement */:
10756                 if (hostNode.declarationList && hostNode.declarationList.declarations[0]) {
10757                     return getDeclarationIdentifier(hostNode.declarationList.declarations[0]);
10758                 }
10759                 break;
10760             case 226 /* ExpressionStatement */:
10761                 var expr = hostNode.expression;
10762                 if (expr.kind === 209 /* BinaryExpression */ && expr.operatorToken.kind === 62 /* EqualsToken */) {
10763                     expr = expr.left;
10764                 }
10765                 switch (expr.kind) {
10766                     case 194 /* PropertyAccessExpression */:
10767                         return expr.name;
10768                     case 195 /* ElementAccessExpression */:
10769                         var arg = expr.argumentExpression;
10770                         if (isIdentifier(arg)) {
10771                             return arg;
10772                         }
10773                 }
10774                 break;
10775             case 200 /* ParenthesizedExpression */: {
10776                 return getDeclarationIdentifier(hostNode.expression);
10777             }
10778             case 238 /* LabeledStatement */: {
10779                 if (isDeclaration(hostNode.statement) || isExpression(hostNode.statement)) {
10780                     return getDeclarationIdentifier(hostNode.statement);
10781                 }
10782                 break;
10783             }
10784         }
10785     }
10786     function getDeclarationIdentifier(node) {
10787         var name = getNameOfDeclaration(node);
10788         return name && isIdentifier(name) ? name : undefined;
10789     }
10790     /** @internal */
10791     function nodeHasName(statement, name) {
10792         if (isNamedDeclaration(statement) && isIdentifier(statement.name) && idText(statement.name) === idText(name)) {
10793             return true;
10794         }
10795         if (isVariableStatement(statement) && ts.some(statement.declarationList.declarations, function (d) { return nodeHasName(d, name); })) {
10796             return true;
10797         }
10798         return false;
10799     }
10800     ts.nodeHasName = nodeHasName;
10801     function getNameOfJSDocTypedef(declaration) {
10802         return declaration.name || nameForNamelessJSDocTypedef(declaration);
10803     }
10804     ts.getNameOfJSDocTypedef = getNameOfJSDocTypedef;
10805     /** @internal */
10806     function isNamedDeclaration(node) {
10807         return !!node.name; // A 'name' property should always be a DeclarationName.
10808     }
10809     ts.isNamedDeclaration = isNamedDeclaration;
10810     /** @internal */
10811     function getNonAssignedNameOfDeclaration(declaration) {
10812         switch (declaration.kind) {
10813             case 75 /* Identifier */:
10814                 return declaration;
10815             case 323 /* JSDocPropertyTag */:
10816             case 317 /* JSDocParameterTag */: {
10817                 var name = declaration.name;
10818                 if (name.kind === 153 /* QualifiedName */) {
10819                     return name.right;
10820                 }
10821                 break;
10822             }
10823             case 196 /* CallExpression */:
10824             case 209 /* BinaryExpression */: {
10825                 var expr_1 = declaration;
10826                 switch (ts.getAssignmentDeclarationKind(expr_1)) {
10827                     case 1 /* ExportsProperty */:
10828                     case 4 /* ThisProperty */:
10829                     case 5 /* Property */:
10830                     case 3 /* PrototypeProperty */:
10831                         return ts.getElementOrPropertyAccessArgumentExpressionOrName(expr_1.left);
10832                     case 7 /* ObjectDefinePropertyValue */:
10833                     case 8 /* ObjectDefinePropertyExports */:
10834                     case 9 /* ObjectDefinePrototypeProperty */:
10835                         return expr_1.arguments[1];
10836                     default:
10837                         return undefined;
10838                 }
10839             }
10840             case 322 /* JSDocTypedefTag */:
10841                 return getNameOfJSDocTypedef(declaration);
10842             case 316 /* JSDocEnumTag */:
10843                 return nameForNamelessJSDocTypedef(declaration);
10844             case 259 /* ExportAssignment */: {
10845                 var expression = declaration.expression;
10846                 return isIdentifier(expression) ? expression : undefined;
10847             }
10848             case 195 /* ElementAccessExpression */:
10849                 var expr = declaration;
10850                 if (ts.isBindableStaticElementAccessExpression(expr)) {
10851                     return expr.argumentExpression;
10852                 }
10853         }
10854         return declaration.name;
10855     }
10856     ts.getNonAssignedNameOfDeclaration = getNonAssignedNameOfDeclaration;
10857     function getNameOfDeclaration(declaration) {
10858         if (declaration === undefined)
10859             return undefined;
10860         return getNonAssignedNameOfDeclaration(declaration) ||
10861             (isFunctionExpression(declaration) || isClassExpression(declaration) ? getAssignedName(declaration) : undefined);
10862     }
10863     ts.getNameOfDeclaration = getNameOfDeclaration;
10864     function getAssignedName(node) {
10865         if (!node.parent) {
10866             return undefined;
10867         }
10868         else if (isPropertyAssignment(node.parent) || isBindingElement(node.parent)) {
10869             return node.parent.name;
10870         }
10871         else if (isBinaryExpression(node.parent) && node === node.parent.right) {
10872             if (isIdentifier(node.parent.left)) {
10873                 return node.parent.left;
10874             }
10875             else if (ts.isAccessExpression(node.parent.left)) {
10876                 return ts.getElementOrPropertyAccessArgumentExpressionOrName(node.parent.left);
10877             }
10878         }
10879         else if (isVariableDeclaration(node.parent) && isIdentifier(node.parent.name)) {
10880             return node.parent.name;
10881         }
10882     }
10883     /**
10884      * Gets the JSDoc parameter tags for the node if present.
10885      *
10886      * @remarks Returns any JSDoc param tag whose name matches the provided
10887      * parameter, whether a param tag on a containing function
10888      * expression, or a param tag on a variable declaration whose
10889      * initializer is the containing function. The tags closest to the
10890      * node are returned first, so in the previous example, the param
10891      * tag on the containing function expression would be first.
10892      *
10893      * For binding patterns, parameter tags are matched by position.
10894      */
10895     function getJSDocParameterTags(param) {
10896         if (param.name) {
10897             if (isIdentifier(param.name)) {
10898                 var name_1 = param.name.escapedText;
10899                 return getJSDocTags(param.parent).filter(function (tag) { return isJSDocParameterTag(tag) && isIdentifier(tag.name) && tag.name.escapedText === name_1; });
10900             }
10901             else {
10902                 var i = param.parent.parameters.indexOf(param);
10903                 ts.Debug.assert(i > -1, "Parameters should always be in their parents' parameter list");
10904                 var paramTags = getJSDocTags(param.parent).filter(isJSDocParameterTag);
10905                 if (i < paramTags.length) {
10906                     return [paramTags[i]];
10907                 }
10908             }
10909         }
10910         // return empty array for: out-of-order binding patterns and JSDoc function syntax, which has un-named parameters
10911         return ts.emptyArray;
10912     }
10913     ts.getJSDocParameterTags = getJSDocParameterTags;
10914     /**
10915      * Gets the JSDoc type parameter tags for the node if present.
10916      *
10917      * @remarks Returns any JSDoc template tag whose names match the provided
10918      * parameter, whether a template tag on a containing function
10919      * expression, or a template tag on a variable declaration whose
10920      * initializer is the containing function. The tags closest to the
10921      * node are returned first, so in the previous example, the template
10922      * tag on the containing function expression would be first.
10923      */
10924     function getJSDocTypeParameterTags(param) {
10925         var name = param.name.escapedText;
10926         return getJSDocTags(param.parent).filter(function (tag) {
10927             return isJSDocTemplateTag(tag) && tag.typeParameters.some(function (tp) { return tp.name.escapedText === name; });
10928         });
10929     }
10930     ts.getJSDocTypeParameterTags = getJSDocTypeParameterTags;
10931     /**
10932      * Return true if the node has JSDoc parameter tags.
10933      *
10934      * @remarks Includes parameter tags that are not directly on the node,
10935      * for example on a variable declaration whose initializer is a function expression.
10936      */
10937     function hasJSDocParameterTags(node) {
10938         return !!getFirstJSDocTag(node, isJSDocParameterTag);
10939     }
10940     ts.hasJSDocParameterTags = hasJSDocParameterTags;
10941     /** Gets the JSDoc augments tag for the node if present */
10942     function getJSDocAugmentsTag(node) {
10943         return getFirstJSDocTag(node, isJSDocAugmentsTag);
10944     }
10945     ts.getJSDocAugmentsTag = getJSDocAugmentsTag;
10946     /** Gets the JSDoc implements tags for the node if present */
10947     function getJSDocImplementsTags(node) {
10948         return getAllJSDocTags(node, isJSDocImplementsTag);
10949     }
10950     ts.getJSDocImplementsTags = getJSDocImplementsTags;
10951     /** Gets the JSDoc class tag for the node if present */
10952     function getJSDocClassTag(node) {
10953         return getFirstJSDocTag(node, isJSDocClassTag);
10954     }
10955     ts.getJSDocClassTag = getJSDocClassTag;
10956     /** Gets the JSDoc public tag for the node if present */
10957     function getJSDocPublicTag(node) {
10958         return getFirstJSDocTag(node, isJSDocPublicTag);
10959     }
10960     ts.getJSDocPublicTag = getJSDocPublicTag;
10961     /** Gets the JSDoc private tag for the node if present */
10962     function getJSDocPrivateTag(node) {
10963         return getFirstJSDocTag(node, isJSDocPrivateTag);
10964     }
10965     ts.getJSDocPrivateTag = getJSDocPrivateTag;
10966     /** Gets the JSDoc protected tag for the node if present */
10967     function getJSDocProtectedTag(node) {
10968         return getFirstJSDocTag(node, isJSDocProtectedTag);
10969     }
10970     ts.getJSDocProtectedTag = getJSDocProtectedTag;
10971     /** Gets the JSDoc protected tag for the node if present */
10972     function getJSDocReadonlyTag(node) {
10973         return getFirstJSDocTag(node, isJSDocReadonlyTag);
10974     }
10975     ts.getJSDocReadonlyTag = getJSDocReadonlyTag;
10976     /** Gets the JSDoc enum tag for the node if present */
10977     function getJSDocEnumTag(node) {
10978         return getFirstJSDocTag(node, isJSDocEnumTag);
10979     }
10980     ts.getJSDocEnumTag = getJSDocEnumTag;
10981     /** Gets the JSDoc this tag for the node if present */
10982     function getJSDocThisTag(node) {
10983         return getFirstJSDocTag(node, isJSDocThisTag);
10984     }
10985     ts.getJSDocThisTag = getJSDocThisTag;
10986     /** Gets the JSDoc return tag for the node if present */
10987     function getJSDocReturnTag(node) {
10988         return getFirstJSDocTag(node, isJSDocReturnTag);
10989     }
10990     ts.getJSDocReturnTag = getJSDocReturnTag;
10991     /** Gets the JSDoc template tag for the node if present */
10992     function getJSDocTemplateTag(node) {
10993         return getFirstJSDocTag(node, isJSDocTemplateTag);
10994     }
10995     ts.getJSDocTemplateTag = getJSDocTemplateTag;
10996     /** Gets the JSDoc type tag for the node if present and valid */
10997     function getJSDocTypeTag(node) {
10998         // We should have already issued an error if there were multiple type jsdocs, so just use the first one.
10999         var tag = getFirstJSDocTag(node, isJSDocTypeTag);
11000         if (tag && tag.typeExpression && tag.typeExpression.type) {
11001             return tag;
11002         }
11003         return undefined;
11004     }
11005     ts.getJSDocTypeTag = getJSDocTypeTag;
11006     /**
11007      * Gets the type node for the node if provided via JSDoc.
11008      *
11009      * @remarks The search includes any JSDoc param tag that relates
11010      * to the provided parameter, for example a type tag on the
11011      * parameter itself, or a param tag on a containing function
11012      * expression, or a param tag on a variable declaration whose
11013      * initializer is the containing function. The tags closest to the
11014      * node are examined first, so in the previous example, the type
11015      * tag directly on the node would be returned.
11016      */
11017     function getJSDocType(node) {
11018         var tag = getFirstJSDocTag(node, isJSDocTypeTag);
11019         if (!tag && isParameter(node)) {
11020             tag = ts.find(getJSDocParameterTags(node), function (tag) { return !!tag.typeExpression; });
11021         }
11022         return tag && tag.typeExpression && tag.typeExpression.type;
11023     }
11024     ts.getJSDocType = getJSDocType;
11025     /**
11026      * Gets the return type node for the node if provided via JSDoc return tag or type tag.
11027      *
11028      * @remarks `getJSDocReturnTag` just gets the whole JSDoc tag. This function
11029      * gets the type from inside the braces, after the fat arrow, etc.
11030      */
11031     function getJSDocReturnType(node) {
11032         var returnTag = getJSDocReturnTag(node);
11033         if (returnTag && returnTag.typeExpression) {
11034             return returnTag.typeExpression.type;
11035         }
11036         var typeTag = getJSDocTypeTag(node);
11037         if (typeTag && typeTag.typeExpression) {
11038             var type = typeTag.typeExpression.type;
11039             if (isTypeLiteralNode(type)) {
11040                 var sig = ts.find(type.members, isCallSignatureDeclaration);
11041                 return sig && sig.type;
11042             }
11043             if (isFunctionTypeNode(type) || isJSDocFunctionType(type)) {
11044                 return type.type;
11045             }
11046         }
11047     }
11048     ts.getJSDocReturnType = getJSDocReturnType;
11049     /** Get all JSDoc tags related to a node, including those on parent nodes. */
11050     function getJSDocTags(node) {
11051         var tags = node.jsDocCache;
11052         // If cache is 'null', that means we did the work of searching for JSDoc tags and came up with nothing.
11053         if (tags === undefined) {
11054             var comments = ts.getJSDocCommentsAndTags(node);
11055             ts.Debug.assert(comments.length < 2 || comments[0] !== comments[1]);
11056             node.jsDocCache = tags = ts.flatMap(comments, function (j) { return isJSDoc(j) ? j.tags : j; });
11057         }
11058         return tags;
11059     }
11060     ts.getJSDocTags = getJSDocTags;
11061     /** Get the first JSDoc tag of a specified kind, or undefined if not present. */
11062     function getFirstJSDocTag(node, predicate) {
11063         return ts.find(getJSDocTags(node), predicate);
11064     }
11065     /** Gets all JSDoc tags that match a specified predicate */
11066     function getAllJSDocTags(node, predicate) {
11067         return getJSDocTags(node).filter(predicate);
11068     }
11069     ts.getAllJSDocTags = getAllJSDocTags;
11070     /** Gets all JSDoc tags of a specified kind */
11071     function getAllJSDocTagsOfKind(node, kind) {
11072         return getJSDocTags(node).filter(function (doc) { return doc.kind === kind; });
11073     }
11074     ts.getAllJSDocTagsOfKind = getAllJSDocTagsOfKind;
11075     /**
11076      * Gets the effective type parameters. If the node was parsed in a
11077      * JavaScript file, gets the type parameters from the `@template` tag from JSDoc.
11078      */
11079     function getEffectiveTypeParameterDeclarations(node) {
11080         if (isJSDocSignature(node)) {
11081             return ts.emptyArray;
11082         }
11083         if (ts.isJSDocTypeAlias(node)) {
11084             ts.Debug.assert(node.parent.kind === 303 /* JSDocComment */);
11085             return ts.flatMap(node.parent.tags, function (tag) { return isJSDocTemplateTag(tag) ? tag.typeParameters : undefined; });
11086         }
11087         if (node.typeParameters) {
11088             return node.typeParameters;
11089         }
11090         if (ts.isInJSFile(node)) {
11091             var decls = ts.getJSDocTypeParameterDeclarations(node);
11092             if (decls.length) {
11093                 return decls;
11094             }
11095             var typeTag = getJSDocType(node);
11096             if (typeTag && isFunctionTypeNode(typeTag) && typeTag.typeParameters) {
11097                 return typeTag.typeParameters;
11098             }
11099         }
11100         return ts.emptyArray;
11101     }
11102     ts.getEffectiveTypeParameterDeclarations = getEffectiveTypeParameterDeclarations;
11103     function getEffectiveConstraintOfTypeParameter(node) {
11104         return node.constraint ? node.constraint :
11105             isJSDocTemplateTag(node.parent) && node === node.parent.typeParameters[0] ? node.parent.constraint :
11106                 undefined;
11107     }
11108     ts.getEffectiveConstraintOfTypeParameter = getEffectiveConstraintOfTypeParameter;
11109     // #region
11110     // Simple node tests of the form `node.kind === SyntaxKind.Foo`.
11111     // Literals
11112     function isNumericLiteral(node) {
11113         return node.kind === 8 /* NumericLiteral */;
11114     }
11115     ts.isNumericLiteral = isNumericLiteral;
11116     function isBigIntLiteral(node) {
11117         return node.kind === 9 /* BigIntLiteral */;
11118     }
11119     ts.isBigIntLiteral = isBigIntLiteral;
11120     function isStringLiteral(node) {
11121         return node.kind === 10 /* StringLiteral */;
11122     }
11123     ts.isStringLiteral = isStringLiteral;
11124     function isJsxText(node) {
11125         return node.kind === 11 /* JsxText */;
11126     }
11127     ts.isJsxText = isJsxText;
11128     function isRegularExpressionLiteral(node) {
11129         return node.kind === 13 /* RegularExpressionLiteral */;
11130     }
11131     ts.isRegularExpressionLiteral = isRegularExpressionLiteral;
11132     function isNoSubstitutionTemplateLiteral(node) {
11133         return node.kind === 14 /* NoSubstitutionTemplateLiteral */;
11134     }
11135     ts.isNoSubstitutionTemplateLiteral = isNoSubstitutionTemplateLiteral;
11136     // Pseudo-literals
11137     function isTemplateHead(node) {
11138         return node.kind === 15 /* TemplateHead */;
11139     }
11140     ts.isTemplateHead = isTemplateHead;
11141     function isTemplateMiddle(node) {
11142         return node.kind === 16 /* TemplateMiddle */;
11143     }
11144     ts.isTemplateMiddle = isTemplateMiddle;
11145     function isTemplateTail(node) {
11146         return node.kind === 17 /* TemplateTail */;
11147     }
11148     ts.isTemplateTail = isTemplateTail;
11149     function isIdentifier(node) {
11150         return node.kind === 75 /* Identifier */;
11151     }
11152     ts.isIdentifier = isIdentifier;
11153     // Names
11154     function isQualifiedName(node) {
11155         return node.kind === 153 /* QualifiedName */;
11156     }
11157     ts.isQualifiedName = isQualifiedName;
11158     function isComputedPropertyName(node) {
11159         return node.kind === 154 /* ComputedPropertyName */;
11160     }
11161     ts.isComputedPropertyName = isComputedPropertyName;
11162     function isPrivateIdentifier(node) {
11163         return node.kind === 76 /* PrivateIdentifier */;
11164     }
11165     ts.isPrivateIdentifier = isPrivateIdentifier;
11166     function isIdentifierOrPrivateIdentifier(node) {
11167         return node.kind === 75 /* Identifier */ || node.kind === 76 /* PrivateIdentifier */;
11168     }
11169     ts.isIdentifierOrPrivateIdentifier = isIdentifierOrPrivateIdentifier;
11170     // Signature elements
11171     function isTypeParameterDeclaration(node) {
11172         return node.kind === 155 /* TypeParameter */;
11173     }
11174     ts.isTypeParameterDeclaration = isTypeParameterDeclaration;
11175     function isParameter(node) {
11176         return node.kind === 156 /* Parameter */;
11177     }
11178     ts.isParameter = isParameter;
11179     function isDecorator(node) {
11180         return node.kind === 157 /* Decorator */;
11181     }
11182     ts.isDecorator = isDecorator;
11183     // TypeMember
11184     function isPropertySignature(node) {
11185         return node.kind === 158 /* PropertySignature */;
11186     }
11187     ts.isPropertySignature = isPropertySignature;
11188     function isPropertyDeclaration(node) {
11189         return node.kind === 159 /* PropertyDeclaration */;
11190     }
11191     ts.isPropertyDeclaration = isPropertyDeclaration;
11192     function isMethodSignature(node) {
11193         return node.kind === 160 /* MethodSignature */;
11194     }
11195     ts.isMethodSignature = isMethodSignature;
11196     function isMethodDeclaration(node) {
11197         return node.kind === 161 /* MethodDeclaration */;
11198     }
11199     ts.isMethodDeclaration = isMethodDeclaration;
11200     function isConstructorDeclaration(node) {
11201         return node.kind === 162 /* Constructor */;
11202     }
11203     ts.isConstructorDeclaration = isConstructorDeclaration;
11204     function isGetAccessorDeclaration(node) {
11205         return node.kind === 163 /* GetAccessor */;
11206     }
11207     ts.isGetAccessorDeclaration = isGetAccessorDeclaration;
11208     function isSetAccessorDeclaration(node) {
11209         return node.kind === 164 /* SetAccessor */;
11210     }
11211     ts.isSetAccessorDeclaration = isSetAccessorDeclaration;
11212     function isCallSignatureDeclaration(node) {
11213         return node.kind === 165 /* CallSignature */;
11214     }
11215     ts.isCallSignatureDeclaration = isCallSignatureDeclaration;
11216     function isConstructSignatureDeclaration(node) {
11217         return node.kind === 166 /* ConstructSignature */;
11218     }
11219     ts.isConstructSignatureDeclaration = isConstructSignatureDeclaration;
11220     function isIndexSignatureDeclaration(node) {
11221         return node.kind === 167 /* IndexSignature */;
11222     }
11223     ts.isIndexSignatureDeclaration = isIndexSignatureDeclaration;
11224     /* @internal */
11225     function isGetOrSetAccessorDeclaration(node) {
11226         return node.kind === 164 /* SetAccessor */ || node.kind === 163 /* GetAccessor */;
11227     }
11228     ts.isGetOrSetAccessorDeclaration = isGetOrSetAccessorDeclaration;
11229     // Type
11230     function isTypePredicateNode(node) {
11231         return node.kind === 168 /* TypePredicate */;
11232     }
11233     ts.isTypePredicateNode = isTypePredicateNode;
11234     function isTypeReferenceNode(node) {
11235         return node.kind === 169 /* TypeReference */;
11236     }
11237     ts.isTypeReferenceNode = isTypeReferenceNode;
11238     function isFunctionTypeNode(node) {
11239         return node.kind === 170 /* FunctionType */;
11240     }
11241     ts.isFunctionTypeNode = isFunctionTypeNode;
11242     function isConstructorTypeNode(node) {
11243         return node.kind === 171 /* ConstructorType */;
11244     }
11245     ts.isConstructorTypeNode = isConstructorTypeNode;
11246     function isTypeQueryNode(node) {
11247         return node.kind === 172 /* TypeQuery */;
11248     }
11249     ts.isTypeQueryNode = isTypeQueryNode;
11250     function isTypeLiteralNode(node) {
11251         return node.kind === 173 /* TypeLiteral */;
11252     }
11253     ts.isTypeLiteralNode = isTypeLiteralNode;
11254     function isArrayTypeNode(node) {
11255         return node.kind === 174 /* ArrayType */;
11256     }
11257     ts.isArrayTypeNode = isArrayTypeNode;
11258     function isTupleTypeNode(node) {
11259         return node.kind === 175 /* TupleType */;
11260     }
11261     ts.isTupleTypeNode = isTupleTypeNode;
11262     function isUnionTypeNode(node) {
11263         return node.kind === 178 /* UnionType */;
11264     }
11265     ts.isUnionTypeNode = isUnionTypeNode;
11266     function isIntersectionTypeNode(node) {
11267         return node.kind === 179 /* IntersectionType */;
11268     }
11269     ts.isIntersectionTypeNode = isIntersectionTypeNode;
11270     function isConditionalTypeNode(node) {
11271         return node.kind === 180 /* ConditionalType */;
11272     }
11273     ts.isConditionalTypeNode = isConditionalTypeNode;
11274     function isInferTypeNode(node) {
11275         return node.kind === 181 /* InferType */;
11276     }
11277     ts.isInferTypeNode = isInferTypeNode;
11278     function isParenthesizedTypeNode(node) {
11279         return node.kind === 182 /* ParenthesizedType */;
11280     }
11281     ts.isParenthesizedTypeNode = isParenthesizedTypeNode;
11282     function isThisTypeNode(node) {
11283         return node.kind === 183 /* ThisType */;
11284     }
11285     ts.isThisTypeNode = isThisTypeNode;
11286     function isTypeOperatorNode(node) {
11287         return node.kind === 184 /* TypeOperator */;
11288     }
11289     ts.isTypeOperatorNode = isTypeOperatorNode;
11290     function isIndexedAccessTypeNode(node) {
11291         return node.kind === 185 /* IndexedAccessType */;
11292     }
11293     ts.isIndexedAccessTypeNode = isIndexedAccessTypeNode;
11294     function isMappedTypeNode(node) {
11295         return node.kind === 186 /* MappedType */;
11296     }
11297     ts.isMappedTypeNode = isMappedTypeNode;
11298     function isLiteralTypeNode(node) {
11299         return node.kind === 187 /* LiteralType */;
11300     }
11301     ts.isLiteralTypeNode = isLiteralTypeNode;
11302     function isImportTypeNode(node) {
11303         return node.kind === 188 /* ImportType */;
11304     }
11305     ts.isImportTypeNode = isImportTypeNode;
11306     // Binding patterns
11307     function isObjectBindingPattern(node) {
11308         return node.kind === 189 /* ObjectBindingPattern */;
11309     }
11310     ts.isObjectBindingPattern = isObjectBindingPattern;
11311     function isArrayBindingPattern(node) {
11312         return node.kind === 190 /* ArrayBindingPattern */;
11313     }
11314     ts.isArrayBindingPattern = isArrayBindingPattern;
11315     function isBindingElement(node) {
11316         return node.kind === 191 /* BindingElement */;
11317     }
11318     ts.isBindingElement = isBindingElement;
11319     // Expression
11320     function isArrayLiteralExpression(node) {
11321         return node.kind === 192 /* ArrayLiteralExpression */;
11322     }
11323     ts.isArrayLiteralExpression = isArrayLiteralExpression;
11324     function isObjectLiteralExpression(node) {
11325         return node.kind === 193 /* ObjectLiteralExpression */;
11326     }
11327     ts.isObjectLiteralExpression = isObjectLiteralExpression;
11328     function isPropertyAccessExpression(node) {
11329         return node.kind === 194 /* PropertyAccessExpression */;
11330     }
11331     ts.isPropertyAccessExpression = isPropertyAccessExpression;
11332     function isPropertyAccessChain(node) {
11333         return isPropertyAccessExpression(node) && !!(node.flags & 32 /* OptionalChain */);
11334     }
11335     ts.isPropertyAccessChain = isPropertyAccessChain;
11336     function isElementAccessExpression(node) {
11337         return node.kind === 195 /* ElementAccessExpression */;
11338     }
11339     ts.isElementAccessExpression = isElementAccessExpression;
11340     function isElementAccessChain(node) {
11341         return isElementAccessExpression(node) && !!(node.flags & 32 /* OptionalChain */);
11342     }
11343     ts.isElementAccessChain = isElementAccessChain;
11344     function isCallExpression(node) {
11345         return node.kind === 196 /* CallExpression */;
11346     }
11347     ts.isCallExpression = isCallExpression;
11348     function isCallChain(node) {
11349         return isCallExpression(node) && !!(node.flags & 32 /* OptionalChain */);
11350     }
11351     ts.isCallChain = isCallChain;
11352     function isOptionalChain(node) {
11353         var kind = node.kind;
11354         return !!(node.flags & 32 /* OptionalChain */) &&
11355             (kind === 194 /* PropertyAccessExpression */
11356                 || kind === 195 /* ElementAccessExpression */
11357                 || kind === 196 /* CallExpression */
11358                 || kind === 218 /* NonNullExpression */);
11359     }
11360     ts.isOptionalChain = isOptionalChain;
11361     /* @internal */
11362     function isOptionalChainRoot(node) {
11363         return isOptionalChain(node) && !isNonNullExpression(node) && !!node.questionDotToken;
11364     }
11365     ts.isOptionalChainRoot = isOptionalChainRoot;
11366     /**
11367      * Determines whether a node is the expression preceding an optional chain (i.e. `a` in `a?.b`).
11368      */
11369     /* @internal */
11370     function isExpressionOfOptionalChainRoot(node) {
11371         return isOptionalChainRoot(node.parent) && node.parent.expression === node;
11372     }
11373     ts.isExpressionOfOptionalChainRoot = isExpressionOfOptionalChainRoot;
11374     /**
11375      * Determines whether a node is the outermost `OptionalChain` in an ECMAScript `OptionalExpression`:
11376      *
11377      * 1. For `a?.b.c`, the outermost chain is `a?.b.c` (`c` is the end of the chain starting at `a?.`)
11378      * 2. For `a?.b!`, the outermost chain is `a?.b` (`b` is the end of the chain starting at `a?.`)
11379      * 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)
11380      * 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
11381      *   the end of the chain starting at `c?.`)
11382      * 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
11383      *   the end of the chain starting at `a?.`)
11384      */
11385     /* @internal */
11386     function isOutermostOptionalChain(node) {
11387         return !isOptionalChain(node.parent) // cases 1, 2, and 3
11388             || isOptionalChainRoot(node.parent) // case 4
11389             || node !== node.parent.expression; // case 5
11390     }
11391     ts.isOutermostOptionalChain = isOutermostOptionalChain;
11392     function isNullishCoalesce(node) {
11393         return node.kind === 209 /* BinaryExpression */ && node.operatorToken.kind === 60 /* QuestionQuestionToken */;
11394     }
11395     ts.isNullishCoalesce = isNullishCoalesce;
11396     function isNewExpression(node) {
11397         return node.kind === 197 /* NewExpression */;
11398     }
11399     ts.isNewExpression = isNewExpression;
11400     function isTaggedTemplateExpression(node) {
11401         return node.kind === 198 /* TaggedTemplateExpression */;
11402     }
11403     ts.isTaggedTemplateExpression = isTaggedTemplateExpression;
11404     function isTypeAssertion(node) {
11405         return node.kind === 199 /* TypeAssertionExpression */;
11406     }
11407     ts.isTypeAssertion = isTypeAssertion;
11408     function isConstTypeReference(node) {
11409         return isTypeReferenceNode(node) && isIdentifier(node.typeName) &&
11410             node.typeName.escapedText === "const" && !node.typeArguments;
11411     }
11412     ts.isConstTypeReference = isConstTypeReference;
11413     function isParenthesizedExpression(node) {
11414         return node.kind === 200 /* ParenthesizedExpression */;
11415     }
11416     ts.isParenthesizedExpression = isParenthesizedExpression;
11417     function skipPartiallyEmittedExpressions(node) {
11418         return ts.skipOuterExpressions(node, 8 /* PartiallyEmittedExpressions */);
11419     }
11420     ts.skipPartiallyEmittedExpressions = skipPartiallyEmittedExpressions;
11421     function isFunctionExpression(node) {
11422         return node.kind === 201 /* FunctionExpression */;
11423     }
11424     ts.isFunctionExpression = isFunctionExpression;
11425     function isArrowFunction(node) {
11426         return node.kind === 202 /* ArrowFunction */;
11427     }
11428     ts.isArrowFunction = isArrowFunction;
11429     function isDeleteExpression(node) {
11430         return node.kind === 203 /* DeleteExpression */;
11431     }
11432     ts.isDeleteExpression = isDeleteExpression;
11433     function isTypeOfExpression(node) {
11434         return node.kind === 204 /* TypeOfExpression */;
11435     }
11436     ts.isTypeOfExpression = isTypeOfExpression;
11437     function isVoidExpression(node) {
11438         return node.kind === 205 /* VoidExpression */;
11439     }
11440     ts.isVoidExpression = isVoidExpression;
11441     function isAwaitExpression(node) {
11442         return node.kind === 206 /* AwaitExpression */;
11443     }
11444     ts.isAwaitExpression = isAwaitExpression;
11445     function isPrefixUnaryExpression(node) {
11446         return node.kind === 207 /* PrefixUnaryExpression */;
11447     }
11448     ts.isPrefixUnaryExpression = isPrefixUnaryExpression;
11449     function isPostfixUnaryExpression(node) {
11450         return node.kind === 208 /* PostfixUnaryExpression */;
11451     }
11452     ts.isPostfixUnaryExpression = isPostfixUnaryExpression;
11453     function isBinaryExpression(node) {
11454         return node.kind === 209 /* BinaryExpression */;
11455     }
11456     ts.isBinaryExpression = isBinaryExpression;
11457     function isConditionalExpression(node) {
11458         return node.kind === 210 /* ConditionalExpression */;
11459     }
11460     ts.isConditionalExpression = isConditionalExpression;
11461     function isTemplateExpression(node) {
11462         return node.kind === 211 /* TemplateExpression */;
11463     }
11464     ts.isTemplateExpression = isTemplateExpression;
11465     function isYieldExpression(node) {
11466         return node.kind === 212 /* YieldExpression */;
11467     }
11468     ts.isYieldExpression = isYieldExpression;
11469     function isSpreadElement(node) {
11470         return node.kind === 213 /* SpreadElement */;
11471     }
11472     ts.isSpreadElement = isSpreadElement;
11473     function isClassExpression(node) {
11474         return node.kind === 214 /* ClassExpression */;
11475     }
11476     ts.isClassExpression = isClassExpression;
11477     function isOmittedExpression(node) {
11478         return node.kind === 215 /* OmittedExpression */;
11479     }
11480     ts.isOmittedExpression = isOmittedExpression;
11481     function isExpressionWithTypeArguments(node) {
11482         return node.kind === 216 /* ExpressionWithTypeArguments */;
11483     }
11484     ts.isExpressionWithTypeArguments = isExpressionWithTypeArguments;
11485     function isAsExpression(node) {
11486         return node.kind === 217 /* AsExpression */;
11487     }
11488     ts.isAsExpression = isAsExpression;
11489     function isNonNullExpression(node) {
11490         return node.kind === 218 /* NonNullExpression */;
11491     }
11492     ts.isNonNullExpression = isNonNullExpression;
11493     function isNonNullChain(node) {
11494         return isNonNullExpression(node) && !!(node.flags & 32 /* OptionalChain */);
11495     }
11496     ts.isNonNullChain = isNonNullChain;
11497     function isMetaProperty(node) {
11498         return node.kind === 219 /* MetaProperty */;
11499     }
11500     ts.isMetaProperty = isMetaProperty;
11501     // Misc
11502     function isTemplateSpan(node) {
11503         return node.kind === 221 /* TemplateSpan */;
11504     }
11505     ts.isTemplateSpan = isTemplateSpan;
11506     function isSemicolonClassElement(node) {
11507         return node.kind === 222 /* SemicolonClassElement */;
11508     }
11509     ts.isSemicolonClassElement = isSemicolonClassElement;
11510     // Block
11511     function isBlock(node) {
11512         return node.kind === 223 /* Block */;
11513     }
11514     ts.isBlock = isBlock;
11515     function isVariableStatement(node) {
11516         return node.kind === 225 /* VariableStatement */;
11517     }
11518     ts.isVariableStatement = isVariableStatement;
11519     function isEmptyStatement(node) {
11520         return node.kind === 224 /* EmptyStatement */;
11521     }
11522     ts.isEmptyStatement = isEmptyStatement;
11523     function isExpressionStatement(node) {
11524         return node.kind === 226 /* ExpressionStatement */;
11525     }
11526     ts.isExpressionStatement = isExpressionStatement;
11527     function isIfStatement(node) {
11528         return node.kind === 227 /* IfStatement */;
11529     }
11530     ts.isIfStatement = isIfStatement;
11531     function isDoStatement(node) {
11532         return node.kind === 228 /* DoStatement */;
11533     }
11534     ts.isDoStatement = isDoStatement;
11535     function isWhileStatement(node) {
11536         return node.kind === 229 /* WhileStatement */;
11537     }
11538     ts.isWhileStatement = isWhileStatement;
11539     function isForStatement(node) {
11540         return node.kind === 230 /* ForStatement */;
11541     }
11542     ts.isForStatement = isForStatement;
11543     function isForInStatement(node) {
11544         return node.kind === 231 /* ForInStatement */;
11545     }
11546     ts.isForInStatement = isForInStatement;
11547     function isForOfStatement(node) {
11548         return node.kind === 232 /* ForOfStatement */;
11549     }
11550     ts.isForOfStatement = isForOfStatement;
11551     function isContinueStatement(node) {
11552         return node.kind === 233 /* ContinueStatement */;
11553     }
11554     ts.isContinueStatement = isContinueStatement;
11555     function isBreakStatement(node) {
11556         return node.kind === 234 /* BreakStatement */;
11557     }
11558     ts.isBreakStatement = isBreakStatement;
11559     function isBreakOrContinueStatement(node) {
11560         return node.kind === 234 /* BreakStatement */ || node.kind === 233 /* ContinueStatement */;
11561     }
11562     ts.isBreakOrContinueStatement = isBreakOrContinueStatement;
11563     function isReturnStatement(node) {
11564         return node.kind === 235 /* ReturnStatement */;
11565     }
11566     ts.isReturnStatement = isReturnStatement;
11567     function isWithStatement(node) {
11568         return node.kind === 236 /* WithStatement */;
11569     }
11570     ts.isWithStatement = isWithStatement;
11571     function isSwitchStatement(node) {
11572         return node.kind === 237 /* SwitchStatement */;
11573     }
11574     ts.isSwitchStatement = isSwitchStatement;
11575     function isLabeledStatement(node) {
11576         return node.kind === 238 /* LabeledStatement */;
11577     }
11578     ts.isLabeledStatement = isLabeledStatement;
11579     function isThrowStatement(node) {
11580         return node.kind === 239 /* ThrowStatement */;
11581     }
11582     ts.isThrowStatement = isThrowStatement;
11583     function isTryStatement(node) {
11584         return node.kind === 240 /* TryStatement */;
11585     }
11586     ts.isTryStatement = isTryStatement;
11587     function isDebuggerStatement(node) {
11588         return node.kind === 241 /* DebuggerStatement */;
11589     }
11590     ts.isDebuggerStatement = isDebuggerStatement;
11591     function isVariableDeclaration(node) {
11592         return node.kind === 242 /* VariableDeclaration */;
11593     }
11594     ts.isVariableDeclaration = isVariableDeclaration;
11595     function isVariableDeclarationList(node) {
11596         return node.kind === 243 /* VariableDeclarationList */;
11597     }
11598     ts.isVariableDeclarationList = isVariableDeclarationList;
11599     function isFunctionDeclaration(node) {
11600         return node.kind === 244 /* FunctionDeclaration */;
11601     }
11602     ts.isFunctionDeclaration = isFunctionDeclaration;
11603     function isClassDeclaration(node) {
11604         return node.kind === 245 /* ClassDeclaration */;
11605     }
11606     ts.isClassDeclaration = isClassDeclaration;
11607     function isInterfaceDeclaration(node) {
11608         return node.kind === 246 /* InterfaceDeclaration */;
11609     }
11610     ts.isInterfaceDeclaration = isInterfaceDeclaration;
11611     function isTypeAliasDeclaration(node) {
11612         return node.kind === 247 /* TypeAliasDeclaration */;
11613     }
11614     ts.isTypeAliasDeclaration = isTypeAliasDeclaration;
11615     function isEnumDeclaration(node) {
11616         return node.kind === 248 /* EnumDeclaration */;
11617     }
11618     ts.isEnumDeclaration = isEnumDeclaration;
11619     function isModuleDeclaration(node) {
11620         return node.kind === 249 /* ModuleDeclaration */;
11621     }
11622     ts.isModuleDeclaration = isModuleDeclaration;
11623     function isModuleBlock(node) {
11624         return node.kind === 250 /* ModuleBlock */;
11625     }
11626     ts.isModuleBlock = isModuleBlock;
11627     function isCaseBlock(node) {
11628         return node.kind === 251 /* CaseBlock */;
11629     }
11630     ts.isCaseBlock = isCaseBlock;
11631     function isNamespaceExportDeclaration(node) {
11632         return node.kind === 252 /* NamespaceExportDeclaration */;
11633     }
11634     ts.isNamespaceExportDeclaration = isNamespaceExportDeclaration;
11635     function isImportEqualsDeclaration(node) {
11636         return node.kind === 253 /* ImportEqualsDeclaration */;
11637     }
11638     ts.isImportEqualsDeclaration = isImportEqualsDeclaration;
11639     function isImportDeclaration(node) {
11640         return node.kind === 254 /* ImportDeclaration */;
11641     }
11642     ts.isImportDeclaration = isImportDeclaration;
11643     function isImportClause(node) {
11644         return node.kind === 255 /* ImportClause */;
11645     }
11646     ts.isImportClause = isImportClause;
11647     function isNamespaceImport(node) {
11648         return node.kind === 256 /* NamespaceImport */;
11649     }
11650     ts.isNamespaceImport = isNamespaceImport;
11651     function isNamespaceExport(node) {
11652         return node.kind === 262 /* NamespaceExport */;
11653     }
11654     ts.isNamespaceExport = isNamespaceExport;
11655     function isNamedExportBindings(node) {
11656         return node.kind === 262 /* NamespaceExport */ || node.kind === 261 /* NamedExports */;
11657     }
11658     ts.isNamedExportBindings = isNamedExportBindings;
11659     function isNamedImports(node) {
11660         return node.kind === 257 /* NamedImports */;
11661     }
11662     ts.isNamedImports = isNamedImports;
11663     function isImportSpecifier(node) {
11664         return node.kind === 258 /* ImportSpecifier */;
11665     }
11666     ts.isImportSpecifier = isImportSpecifier;
11667     function isExportAssignment(node) {
11668         return node.kind === 259 /* ExportAssignment */;
11669     }
11670     ts.isExportAssignment = isExportAssignment;
11671     function isExportDeclaration(node) {
11672         return node.kind === 260 /* ExportDeclaration */;
11673     }
11674     ts.isExportDeclaration = isExportDeclaration;
11675     function isNamedExports(node) {
11676         return node.kind === 261 /* NamedExports */;
11677     }
11678     ts.isNamedExports = isNamedExports;
11679     function isExportSpecifier(node) {
11680         return node.kind === 263 /* ExportSpecifier */;
11681     }
11682     ts.isExportSpecifier = isExportSpecifier;
11683     function isMissingDeclaration(node) {
11684         return node.kind === 264 /* MissingDeclaration */;
11685     }
11686     ts.isMissingDeclaration = isMissingDeclaration;
11687     // Module References
11688     function isExternalModuleReference(node) {
11689         return node.kind === 265 /* ExternalModuleReference */;
11690     }
11691     ts.isExternalModuleReference = isExternalModuleReference;
11692     // JSX
11693     function isJsxElement(node) {
11694         return node.kind === 266 /* JsxElement */;
11695     }
11696     ts.isJsxElement = isJsxElement;
11697     function isJsxSelfClosingElement(node) {
11698         return node.kind === 267 /* JsxSelfClosingElement */;
11699     }
11700     ts.isJsxSelfClosingElement = isJsxSelfClosingElement;
11701     function isJsxOpeningElement(node) {
11702         return node.kind === 268 /* JsxOpeningElement */;
11703     }
11704     ts.isJsxOpeningElement = isJsxOpeningElement;
11705     function isJsxClosingElement(node) {
11706         return node.kind === 269 /* JsxClosingElement */;
11707     }
11708     ts.isJsxClosingElement = isJsxClosingElement;
11709     function isJsxFragment(node) {
11710         return node.kind === 270 /* JsxFragment */;
11711     }
11712     ts.isJsxFragment = isJsxFragment;
11713     function isJsxOpeningFragment(node) {
11714         return node.kind === 271 /* JsxOpeningFragment */;
11715     }
11716     ts.isJsxOpeningFragment = isJsxOpeningFragment;
11717     function isJsxClosingFragment(node) {
11718         return node.kind === 272 /* JsxClosingFragment */;
11719     }
11720     ts.isJsxClosingFragment = isJsxClosingFragment;
11721     function isJsxAttribute(node) {
11722         return node.kind === 273 /* JsxAttribute */;
11723     }
11724     ts.isJsxAttribute = isJsxAttribute;
11725     function isJsxAttributes(node) {
11726         return node.kind === 274 /* JsxAttributes */;
11727     }
11728     ts.isJsxAttributes = isJsxAttributes;
11729     function isJsxSpreadAttribute(node) {
11730         return node.kind === 275 /* JsxSpreadAttribute */;
11731     }
11732     ts.isJsxSpreadAttribute = isJsxSpreadAttribute;
11733     function isJsxExpression(node) {
11734         return node.kind === 276 /* JsxExpression */;
11735     }
11736     ts.isJsxExpression = isJsxExpression;
11737     // Clauses
11738     function isCaseClause(node) {
11739         return node.kind === 277 /* CaseClause */;
11740     }
11741     ts.isCaseClause = isCaseClause;
11742     function isDefaultClause(node) {
11743         return node.kind === 278 /* DefaultClause */;
11744     }
11745     ts.isDefaultClause = isDefaultClause;
11746     function isHeritageClause(node) {
11747         return node.kind === 279 /* HeritageClause */;
11748     }
11749     ts.isHeritageClause = isHeritageClause;
11750     function isCatchClause(node) {
11751         return node.kind === 280 /* CatchClause */;
11752     }
11753     ts.isCatchClause = isCatchClause;
11754     // Property assignments
11755     function isPropertyAssignment(node) {
11756         return node.kind === 281 /* PropertyAssignment */;
11757     }
11758     ts.isPropertyAssignment = isPropertyAssignment;
11759     function isShorthandPropertyAssignment(node) {
11760         return node.kind === 282 /* ShorthandPropertyAssignment */;
11761     }
11762     ts.isShorthandPropertyAssignment = isShorthandPropertyAssignment;
11763     function isSpreadAssignment(node) {
11764         return node.kind === 283 /* SpreadAssignment */;
11765     }
11766     ts.isSpreadAssignment = isSpreadAssignment;
11767     // Enum
11768     function isEnumMember(node) {
11769         return node.kind === 284 /* EnumMember */;
11770     }
11771     ts.isEnumMember = isEnumMember;
11772     // Top-level nodes
11773     function isSourceFile(node) {
11774         return node.kind === 290 /* SourceFile */;
11775     }
11776     ts.isSourceFile = isSourceFile;
11777     function isBundle(node) {
11778         return node.kind === 291 /* Bundle */;
11779     }
11780     ts.isBundle = isBundle;
11781     function isUnparsedSource(node) {
11782         return node.kind === 292 /* UnparsedSource */;
11783     }
11784     ts.isUnparsedSource = isUnparsedSource;
11785     function isUnparsedPrepend(node) {
11786         return node.kind === 286 /* UnparsedPrepend */;
11787     }
11788     ts.isUnparsedPrepend = isUnparsedPrepend;
11789     function isUnparsedTextLike(node) {
11790         switch (node.kind) {
11791             case 287 /* UnparsedText */:
11792             case 288 /* UnparsedInternalText */:
11793                 return true;
11794             default:
11795                 return false;
11796         }
11797     }
11798     ts.isUnparsedTextLike = isUnparsedTextLike;
11799     function isUnparsedNode(node) {
11800         return isUnparsedTextLike(node) ||
11801             node.kind === 285 /* UnparsedPrologue */ ||
11802             node.kind === 289 /* UnparsedSyntheticReference */;
11803     }
11804     ts.isUnparsedNode = isUnparsedNode;
11805     // JSDoc
11806     function isJSDocTypeExpression(node) {
11807         return node.kind === 294 /* JSDocTypeExpression */;
11808     }
11809     ts.isJSDocTypeExpression = isJSDocTypeExpression;
11810     function isJSDocAllType(node) {
11811         return node.kind === 295 /* JSDocAllType */;
11812     }
11813     ts.isJSDocAllType = isJSDocAllType;
11814     function isJSDocUnknownType(node) {
11815         return node.kind === 296 /* JSDocUnknownType */;
11816     }
11817     ts.isJSDocUnknownType = isJSDocUnknownType;
11818     function isJSDocNullableType(node) {
11819         return node.kind === 297 /* JSDocNullableType */;
11820     }
11821     ts.isJSDocNullableType = isJSDocNullableType;
11822     function isJSDocNonNullableType(node) {
11823         return node.kind === 298 /* JSDocNonNullableType */;
11824     }
11825     ts.isJSDocNonNullableType = isJSDocNonNullableType;
11826     function isJSDocOptionalType(node) {
11827         return node.kind === 299 /* JSDocOptionalType */;
11828     }
11829     ts.isJSDocOptionalType = isJSDocOptionalType;
11830     function isJSDocFunctionType(node) {
11831         return node.kind === 300 /* JSDocFunctionType */;
11832     }
11833     ts.isJSDocFunctionType = isJSDocFunctionType;
11834     function isJSDocVariadicType(node) {
11835         return node.kind === 301 /* JSDocVariadicType */;
11836     }
11837     ts.isJSDocVariadicType = isJSDocVariadicType;
11838     function isJSDoc(node) {
11839         return node.kind === 303 /* JSDocComment */;
11840     }
11841     ts.isJSDoc = isJSDoc;
11842     function isJSDocAuthorTag(node) {
11843         return node.kind === 309 /* JSDocAuthorTag */;
11844     }
11845     ts.isJSDocAuthorTag = isJSDocAuthorTag;
11846     function isJSDocAugmentsTag(node) {
11847         return node.kind === 307 /* JSDocAugmentsTag */;
11848     }
11849     ts.isJSDocAugmentsTag = isJSDocAugmentsTag;
11850     function isJSDocImplementsTag(node) {
11851         return node.kind === 308 /* JSDocImplementsTag */;
11852     }
11853     ts.isJSDocImplementsTag = isJSDocImplementsTag;
11854     function isJSDocClassTag(node) {
11855         return node.kind === 310 /* JSDocClassTag */;
11856     }
11857     ts.isJSDocClassTag = isJSDocClassTag;
11858     function isJSDocPublicTag(node) {
11859         return node.kind === 311 /* JSDocPublicTag */;
11860     }
11861     ts.isJSDocPublicTag = isJSDocPublicTag;
11862     function isJSDocPrivateTag(node) {
11863         return node.kind === 312 /* JSDocPrivateTag */;
11864     }
11865     ts.isJSDocPrivateTag = isJSDocPrivateTag;
11866     function isJSDocProtectedTag(node) {
11867         return node.kind === 313 /* JSDocProtectedTag */;
11868     }
11869     ts.isJSDocProtectedTag = isJSDocProtectedTag;
11870     function isJSDocReadonlyTag(node) {
11871         return node.kind === 314 /* JSDocReadonlyTag */;
11872     }
11873     ts.isJSDocReadonlyTag = isJSDocReadonlyTag;
11874     function isJSDocEnumTag(node) {
11875         return node.kind === 316 /* JSDocEnumTag */;
11876     }
11877     ts.isJSDocEnumTag = isJSDocEnumTag;
11878     function isJSDocThisTag(node) {
11879         return node.kind === 319 /* JSDocThisTag */;
11880     }
11881     ts.isJSDocThisTag = isJSDocThisTag;
11882     function isJSDocParameterTag(node) {
11883         return node.kind === 317 /* JSDocParameterTag */;
11884     }
11885     ts.isJSDocParameterTag = isJSDocParameterTag;
11886     function isJSDocReturnTag(node) {
11887         return node.kind === 318 /* JSDocReturnTag */;
11888     }
11889     ts.isJSDocReturnTag = isJSDocReturnTag;
11890     function isJSDocTypeTag(node) {
11891         return node.kind === 320 /* JSDocTypeTag */;
11892     }
11893     ts.isJSDocTypeTag = isJSDocTypeTag;
11894     function isJSDocTemplateTag(node) {
11895         return node.kind === 321 /* JSDocTemplateTag */;
11896     }
11897     ts.isJSDocTemplateTag = isJSDocTemplateTag;
11898     function isJSDocTypedefTag(node) {
11899         return node.kind === 322 /* JSDocTypedefTag */;
11900     }
11901     ts.isJSDocTypedefTag = isJSDocTypedefTag;
11902     function isJSDocPropertyTag(node) {
11903         return node.kind === 323 /* JSDocPropertyTag */;
11904     }
11905     ts.isJSDocPropertyTag = isJSDocPropertyTag;
11906     function isJSDocPropertyLikeTag(node) {
11907         return node.kind === 323 /* JSDocPropertyTag */ || node.kind === 317 /* JSDocParameterTag */;
11908     }
11909     ts.isJSDocPropertyLikeTag = isJSDocPropertyLikeTag;
11910     function isJSDocTypeLiteral(node) {
11911         return node.kind === 304 /* JSDocTypeLiteral */;
11912     }
11913     ts.isJSDocTypeLiteral = isJSDocTypeLiteral;
11914     function isJSDocCallbackTag(node) {
11915         return node.kind === 315 /* JSDocCallbackTag */;
11916     }
11917     ts.isJSDocCallbackTag = isJSDocCallbackTag;
11918     function isJSDocSignature(node) {
11919         return node.kind === 305 /* JSDocSignature */;
11920     }
11921     ts.isJSDocSignature = isJSDocSignature;
11922     // #endregion
11923     // #region
11924     // Node tests
11925     //
11926     // All node tests in the following list should *not* reference parent pointers so that
11927     // they may be used with transformations.
11928     /* @internal */
11929     function isSyntaxList(n) {
11930         return n.kind === 324 /* SyntaxList */;
11931     }
11932     ts.isSyntaxList = isSyntaxList;
11933     /* @internal */
11934     function isNode(node) {
11935         return isNodeKind(node.kind);
11936     }
11937     ts.isNode = isNode;
11938     /* @internal */
11939     function isNodeKind(kind) {
11940         return kind >= 153 /* FirstNode */;
11941     }
11942     ts.isNodeKind = isNodeKind;
11943     /**
11944      * True if node is of some token syntax kind.
11945      * For example, this is true for an IfKeyword but not for an IfStatement.
11946      * Literals are considered tokens, except TemplateLiteral, but does include TemplateHead/Middle/Tail.
11947      */
11948     function isToken(n) {
11949         return n.kind >= 0 /* FirstToken */ && n.kind <= 152 /* LastToken */;
11950     }
11951     ts.isToken = isToken;
11952     // Node Arrays
11953     /* @internal */
11954     function isNodeArray(array) {
11955         return array.hasOwnProperty("pos") && array.hasOwnProperty("end");
11956     }
11957     ts.isNodeArray = isNodeArray;
11958     // Literals
11959     /* @internal */
11960     function isLiteralKind(kind) {
11961         return 8 /* FirstLiteralToken */ <= kind && kind <= 14 /* LastLiteralToken */;
11962     }
11963     ts.isLiteralKind = isLiteralKind;
11964     function isLiteralExpression(node) {
11965         return isLiteralKind(node.kind);
11966     }
11967     ts.isLiteralExpression = isLiteralExpression;
11968     // Pseudo-literals
11969     /* @internal */
11970     function isTemplateLiteralKind(kind) {
11971         return 14 /* FirstTemplateToken */ <= kind && kind <= 17 /* LastTemplateToken */;
11972     }
11973     ts.isTemplateLiteralKind = isTemplateLiteralKind;
11974     function isTemplateLiteralToken(node) {
11975         return isTemplateLiteralKind(node.kind);
11976     }
11977     ts.isTemplateLiteralToken = isTemplateLiteralToken;
11978     function isTemplateMiddleOrTemplateTail(node) {
11979         var kind = node.kind;
11980         return kind === 16 /* TemplateMiddle */
11981             || kind === 17 /* TemplateTail */;
11982     }
11983     ts.isTemplateMiddleOrTemplateTail = isTemplateMiddleOrTemplateTail;
11984     function isImportOrExportSpecifier(node) {
11985         return isImportSpecifier(node) || isExportSpecifier(node);
11986     }
11987     ts.isImportOrExportSpecifier = isImportOrExportSpecifier;
11988     function isTypeOnlyImportOrExportDeclaration(node) {
11989         switch (node.kind) {
11990             case 258 /* ImportSpecifier */:
11991             case 263 /* ExportSpecifier */:
11992                 return node.parent.parent.isTypeOnly;
11993             case 256 /* NamespaceImport */:
11994                 return node.parent.isTypeOnly;
11995             case 255 /* ImportClause */:
11996                 return node.isTypeOnly;
11997             default:
11998                 return false;
11999         }
12000     }
12001     ts.isTypeOnlyImportOrExportDeclaration = isTypeOnlyImportOrExportDeclaration;
12002     function isStringTextContainingNode(node) {
12003         return node.kind === 10 /* StringLiteral */ || isTemplateLiteralKind(node.kind);
12004     }
12005     ts.isStringTextContainingNode = isStringTextContainingNode;
12006     // Identifiers
12007     /* @internal */
12008     function isGeneratedIdentifier(node) {
12009         return isIdentifier(node) && (node.autoGenerateFlags & 7 /* KindMask */) > 0 /* None */;
12010     }
12011     ts.isGeneratedIdentifier = isGeneratedIdentifier;
12012     // Private Identifiers
12013     /*@internal*/
12014     function isPrivateIdentifierPropertyDeclaration(node) {
12015         return isPropertyDeclaration(node) && isPrivateIdentifier(node.name);
12016     }
12017     ts.isPrivateIdentifierPropertyDeclaration = isPrivateIdentifierPropertyDeclaration;
12018     /*@internal*/
12019     function isPrivateIdentifierPropertyAccessExpression(node) {
12020         return isPropertyAccessExpression(node) && isPrivateIdentifier(node.name);
12021     }
12022     ts.isPrivateIdentifierPropertyAccessExpression = isPrivateIdentifierPropertyAccessExpression;
12023     // Keywords
12024     /* @internal */
12025     function isModifierKind(token) {
12026         switch (token) {
12027             case 122 /* AbstractKeyword */:
12028             case 126 /* AsyncKeyword */:
12029             case 81 /* ConstKeyword */:
12030             case 130 /* DeclareKeyword */:
12031             case 84 /* DefaultKeyword */:
12032             case 89 /* ExportKeyword */:
12033             case 119 /* PublicKeyword */:
12034             case 117 /* PrivateKeyword */:
12035             case 118 /* ProtectedKeyword */:
12036             case 138 /* ReadonlyKeyword */:
12037             case 120 /* StaticKeyword */:
12038                 return true;
12039         }
12040         return false;
12041     }
12042     ts.isModifierKind = isModifierKind;
12043     /* @internal */
12044     function isParameterPropertyModifier(kind) {
12045         return !!(ts.modifierToFlag(kind) & 92 /* ParameterPropertyModifier */);
12046     }
12047     ts.isParameterPropertyModifier = isParameterPropertyModifier;
12048     /* @internal */
12049     function isClassMemberModifier(idToken) {
12050         return isParameterPropertyModifier(idToken) || idToken === 120 /* StaticKeyword */;
12051     }
12052     ts.isClassMemberModifier = isClassMemberModifier;
12053     function isModifier(node) {
12054         return isModifierKind(node.kind);
12055     }
12056     ts.isModifier = isModifier;
12057     function isEntityName(node) {
12058         var kind = node.kind;
12059         return kind === 153 /* QualifiedName */
12060             || kind === 75 /* Identifier */;
12061     }
12062     ts.isEntityName = isEntityName;
12063     function isPropertyName(node) {
12064         var kind = node.kind;
12065         return kind === 75 /* Identifier */
12066             || kind === 76 /* PrivateIdentifier */
12067             || kind === 10 /* StringLiteral */
12068             || kind === 8 /* NumericLiteral */
12069             || kind === 154 /* ComputedPropertyName */;
12070     }
12071     ts.isPropertyName = isPropertyName;
12072     function isBindingName(node) {
12073         var kind = node.kind;
12074         return kind === 75 /* Identifier */
12075             || kind === 189 /* ObjectBindingPattern */
12076             || kind === 190 /* ArrayBindingPattern */;
12077     }
12078     ts.isBindingName = isBindingName;
12079     // Functions
12080     function isFunctionLike(node) {
12081         return node && isFunctionLikeKind(node.kind);
12082     }
12083     ts.isFunctionLike = isFunctionLike;
12084     /* @internal */
12085     function isFunctionLikeDeclaration(node) {
12086         return node && isFunctionLikeDeclarationKind(node.kind);
12087     }
12088     ts.isFunctionLikeDeclaration = isFunctionLikeDeclaration;
12089     function isFunctionLikeDeclarationKind(kind) {
12090         switch (kind) {
12091             case 244 /* FunctionDeclaration */:
12092             case 161 /* MethodDeclaration */:
12093             case 162 /* Constructor */:
12094             case 163 /* GetAccessor */:
12095             case 164 /* SetAccessor */:
12096             case 201 /* FunctionExpression */:
12097             case 202 /* ArrowFunction */:
12098                 return true;
12099             default:
12100                 return false;
12101         }
12102     }
12103     /* @internal */
12104     function isFunctionLikeKind(kind) {
12105         switch (kind) {
12106             case 160 /* MethodSignature */:
12107             case 165 /* CallSignature */:
12108             case 305 /* JSDocSignature */:
12109             case 166 /* ConstructSignature */:
12110             case 167 /* IndexSignature */:
12111             case 170 /* FunctionType */:
12112             case 300 /* JSDocFunctionType */:
12113             case 171 /* ConstructorType */:
12114                 return true;
12115             default:
12116                 return isFunctionLikeDeclarationKind(kind);
12117         }
12118     }
12119     ts.isFunctionLikeKind = isFunctionLikeKind;
12120     /* @internal */
12121     function isFunctionOrModuleBlock(node) {
12122         return isSourceFile(node) || isModuleBlock(node) || isBlock(node) && isFunctionLike(node.parent);
12123     }
12124     ts.isFunctionOrModuleBlock = isFunctionOrModuleBlock;
12125     // Classes
12126     function isClassElement(node) {
12127         var kind = node.kind;
12128         return kind === 162 /* Constructor */
12129             || kind === 159 /* PropertyDeclaration */
12130             || kind === 161 /* MethodDeclaration */
12131             || kind === 163 /* GetAccessor */
12132             || kind === 164 /* SetAccessor */
12133             || kind === 167 /* IndexSignature */
12134             || kind === 222 /* SemicolonClassElement */;
12135     }
12136     ts.isClassElement = isClassElement;
12137     function isClassLike(node) {
12138         return node && (node.kind === 245 /* ClassDeclaration */ || node.kind === 214 /* ClassExpression */);
12139     }
12140     ts.isClassLike = isClassLike;
12141     function isAccessor(node) {
12142         return node && (node.kind === 163 /* GetAccessor */ || node.kind === 164 /* SetAccessor */);
12143     }
12144     ts.isAccessor = isAccessor;
12145     /* @internal */
12146     function isMethodOrAccessor(node) {
12147         switch (node.kind) {
12148             case 161 /* MethodDeclaration */:
12149             case 163 /* GetAccessor */:
12150             case 164 /* SetAccessor */:
12151                 return true;
12152             default:
12153                 return false;
12154         }
12155     }
12156     ts.isMethodOrAccessor = isMethodOrAccessor;
12157     // Type members
12158     function isTypeElement(node) {
12159         var kind = node.kind;
12160         return kind === 166 /* ConstructSignature */
12161             || kind === 165 /* CallSignature */
12162             || kind === 158 /* PropertySignature */
12163             || kind === 160 /* MethodSignature */
12164             || kind === 167 /* IndexSignature */;
12165     }
12166     ts.isTypeElement = isTypeElement;
12167     function isClassOrTypeElement(node) {
12168         return isTypeElement(node) || isClassElement(node);
12169     }
12170     ts.isClassOrTypeElement = isClassOrTypeElement;
12171     function isObjectLiteralElementLike(node) {
12172         var kind = node.kind;
12173         return kind === 281 /* PropertyAssignment */
12174             || kind === 282 /* ShorthandPropertyAssignment */
12175             || kind === 283 /* SpreadAssignment */
12176             || kind === 161 /* MethodDeclaration */
12177             || kind === 163 /* GetAccessor */
12178             || kind === 164 /* SetAccessor */;
12179     }
12180     ts.isObjectLiteralElementLike = isObjectLiteralElementLike;
12181     // Type
12182     /**
12183      * Node test that determines whether a node is a valid type node.
12184      * This differs from the `isPartOfTypeNode` function which determines whether a node is *part*
12185      * of a TypeNode.
12186      */
12187     function isTypeNode(node) {
12188         return ts.isTypeNodeKind(node.kind);
12189     }
12190     ts.isTypeNode = isTypeNode;
12191     function isFunctionOrConstructorTypeNode(node) {
12192         switch (node.kind) {
12193             case 170 /* FunctionType */:
12194             case 171 /* ConstructorType */:
12195                 return true;
12196         }
12197         return false;
12198     }
12199     ts.isFunctionOrConstructorTypeNode = isFunctionOrConstructorTypeNode;
12200     // Binding patterns
12201     /* @internal */
12202     function isBindingPattern(node) {
12203         if (node) {
12204             var kind = node.kind;
12205             return kind === 190 /* ArrayBindingPattern */
12206                 || kind === 189 /* ObjectBindingPattern */;
12207         }
12208         return false;
12209     }
12210     ts.isBindingPattern = isBindingPattern;
12211     /* @internal */
12212     function isAssignmentPattern(node) {
12213         var kind = node.kind;
12214         return kind === 192 /* ArrayLiteralExpression */
12215             || kind === 193 /* ObjectLiteralExpression */;
12216     }
12217     ts.isAssignmentPattern = isAssignmentPattern;
12218     /* @internal */
12219     function isArrayBindingElement(node) {
12220         var kind = node.kind;
12221         return kind === 191 /* BindingElement */
12222             || kind === 215 /* OmittedExpression */;
12223     }
12224     ts.isArrayBindingElement = isArrayBindingElement;
12225     /**
12226      * Determines whether the BindingOrAssignmentElement is a BindingElement-like declaration
12227      */
12228     /* @internal */
12229     function isDeclarationBindingElement(bindingElement) {
12230         switch (bindingElement.kind) {
12231             case 242 /* VariableDeclaration */:
12232             case 156 /* Parameter */:
12233             case 191 /* BindingElement */:
12234                 return true;
12235         }
12236         return false;
12237     }
12238     ts.isDeclarationBindingElement = isDeclarationBindingElement;
12239     /**
12240      * Determines whether a node is a BindingOrAssignmentPattern
12241      */
12242     /* @internal */
12243     function isBindingOrAssignmentPattern(node) {
12244         return isObjectBindingOrAssignmentPattern(node)
12245             || isArrayBindingOrAssignmentPattern(node);
12246     }
12247     ts.isBindingOrAssignmentPattern = isBindingOrAssignmentPattern;
12248     /**
12249      * Determines whether a node is an ObjectBindingOrAssignmentPattern
12250      */
12251     /* @internal */
12252     function isObjectBindingOrAssignmentPattern(node) {
12253         switch (node.kind) {
12254             case 189 /* ObjectBindingPattern */:
12255             case 193 /* ObjectLiteralExpression */:
12256                 return true;
12257         }
12258         return false;
12259     }
12260     ts.isObjectBindingOrAssignmentPattern = isObjectBindingOrAssignmentPattern;
12261     /**
12262      * Determines whether a node is an ArrayBindingOrAssignmentPattern
12263      */
12264     /* @internal */
12265     function isArrayBindingOrAssignmentPattern(node) {
12266         switch (node.kind) {
12267             case 190 /* ArrayBindingPattern */:
12268             case 192 /* ArrayLiteralExpression */:
12269                 return true;
12270         }
12271         return false;
12272     }
12273     ts.isArrayBindingOrAssignmentPattern = isArrayBindingOrAssignmentPattern;
12274     /* @internal */
12275     function isPropertyAccessOrQualifiedNameOrImportTypeNode(node) {
12276         var kind = node.kind;
12277         return kind === 194 /* PropertyAccessExpression */
12278             || kind === 153 /* QualifiedName */
12279             || kind === 188 /* ImportType */;
12280     }
12281     ts.isPropertyAccessOrQualifiedNameOrImportTypeNode = isPropertyAccessOrQualifiedNameOrImportTypeNode;
12282     // Expression
12283     function isPropertyAccessOrQualifiedName(node) {
12284         var kind = node.kind;
12285         return kind === 194 /* PropertyAccessExpression */
12286             || kind === 153 /* QualifiedName */;
12287     }
12288     ts.isPropertyAccessOrQualifiedName = isPropertyAccessOrQualifiedName;
12289     function isCallLikeExpression(node) {
12290         switch (node.kind) {
12291             case 268 /* JsxOpeningElement */:
12292             case 267 /* JsxSelfClosingElement */:
12293             case 196 /* CallExpression */:
12294             case 197 /* NewExpression */:
12295             case 198 /* TaggedTemplateExpression */:
12296             case 157 /* Decorator */:
12297                 return true;
12298             default:
12299                 return false;
12300         }
12301     }
12302     ts.isCallLikeExpression = isCallLikeExpression;
12303     function isCallOrNewExpression(node) {
12304         return node.kind === 196 /* CallExpression */ || node.kind === 197 /* NewExpression */;
12305     }
12306     ts.isCallOrNewExpression = isCallOrNewExpression;
12307     function isTemplateLiteral(node) {
12308         var kind = node.kind;
12309         return kind === 211 /* TemplateExpression */
12310             || kind === 14 /* NoSubstitutionTemplateLiteral */;
12311     }
12312     ts.isTemplateLiteral = isTemplateLiteral;
12313     /* @internal */
12314     function isLeftHandSideExpression(node) {
12315         return isLeftHandSideExpressionKind(skipPartiallyEmittedExpressions(node).kind);
12316     }
12317     ts.isLeftHandSideExpression = isLeftHandSideExpression;
12318     function isLeftHandSideExpressionKind(kind) {
12319         switch (kind) {
12320             case 194 /* PropertyAccessExpression */:
12321             case 195 /* ElementAccessExpression */:
12322             case 197 /* NewExpression */:
12323             case 196 /* CallExpression */:
12324             case 266 /* JsxElement */:
12325             case 267 /* JsxSelfClosingElement */:
12326             case 270 /* JsxFragment */:
12327             case 198 /* TaggedTemplateExpression */:
12328             case 192 /* ArrayLiteralExpression */:
12329             case 200 /* ParenthesizedExpression */:
12330             case 193 /* ObjectLiteralExpression */:
12331             case 214 /* ClassExpression */:
12332             case 201 /* FunctionExpression */:
12333             case 75 /* Identifier */:
12334             case 13 /* RegularExpressionLiteral */:
12335             case 8 /* NumericLiteral */:
12336             case 9 /* BigIntLiteral */:
12337             case 10 /* StringLiteral */:
12338             case 14 /* NoSubstitutionTemplateLiteral */:
12339             case 211 /* TemplateExpression */:
12340             case 91 /* FalseKeyword */:
12341             case 100 /* NullKeyword */:
12342             case 104 /* ThisKeyword */:
12343             case 106 /* TrueKeyword */:
12344             case 102 /* SuperKeyword */:
12345             case 218 /* NonNullExpression */:
12346             case 219 /* MetaProperty */:
12347             case 96 /* ImportKeyword */: // technically this is only an Expression if it's in a CallExpression
12348                 return true;
12349             default:
12350                 return false;
12351         }
12352     }
12353     /* @internal */
12354     function isUnaryExpression(node) {
12355         return isUnaryExpressionKind(skipPartiallyEmittedExpressions(node).kind);
12356     }
12357     ts.isUnaryExpression = isUnaryExpression;
12358     function isUnaryExpressionKind(kind) {
12359         switch (kind) {
12360             case 207 /* PrefixUnaryExpression */:
12361             case 208 /* PostfixUnaryExpression */:
12362             case 203 /* DeleteExpression */:
12363             case 204 /* TypeOfExpression */:
12364             case 205 /* VoidExpression */:
12365             case 206 /* AwaitExpression */:
12366             case 199 /* TypeAssertionExpression */:
12367                 return true;
12368             default:
12369                 return isLeftHandSideExpressionKind(kind);
12370         }
12371     }
12372     /* @internal */
12373     function isUnaryExpressionWithWrite(expr) {
12374         switch (expr.kind) {
12375             case 208 /* PostfixUnaryExpression */:
12376                 return true;
12377             case 207 /* PrefixUnaryExpression */:
12378                 return expr.operator === 45 /* PlusPlusToken */ ||
12379                     expr.operator === 46 /* MinusMinusToken */;
12380             default:
12381                 return false;
12382         }
12383     }
12384     ts.isUnaryExpressionWithWrite = isUnaryExpressionWithWrite;
12385     /* @internal */
12386     /**
12387      * Determines whether a node is an expression based only on its kind.
12388      * Use `isExpressionNode` if not in transforms.
12389      */
12390     function isExpression(node) {
12391         return isExpressionKind(skipPartiallyEmittedExpressions(node).kind);
12392     }
12393     ts.isExpression = isExpression;
12394     function isExpressionKind(kind) {
12395         switch (kind) {
12396             case 210 /* ConditionalExpression */:
12397             case 212 /* YieldExpression */:
12398             case 202 /* ArrowFunction */:
12399             case 209 /* BinaryExpression */:
12400             case 213 /* SpreadElement */:
12401             case 217 /* AsExpression */:
12402             case 215 /* OmittedExpression */:
12403             case 327 /* CommaListExpression */:
12404             case 326 /* PartiallyEmittedExpression */:
12405                 return true;
12406             default:
12407                 return isUnaryExpressionKind(kind);
12408         }
12409     }
12410     function isAssertionExpression(node) {
12411         var kind = node.kind;
12412         return kind === 199 /* TypeAssertionExpression */
12413             || kind === 217 /* AsExpression */;
12414     }
12415     ts.isAssertionExpression = isAssertionExpression;
12416     /* @internal */
12417     function isPartiallyEmittedExpression(node) {
12418         return node.kind === 326 /* PartiallyEmittedExpression */;
12419     }
12420     ts.isPartiallyEmittedExpression = isPartiallyEmittedExpression;
12421     /* @internal */
12422     function isNotEmittedStatement(node) {
12423         return node.kind === 325 /* NotEmittedStatement */;
12424     }
12425     ts.isNotEmittedStatement = isNotEmittedStatement;
12426     /* @internal */
12427     function isSyntheticReference(node) {
12428         return node.kind === 330 /* SyntheticReferenceExpression */;
12429     }
12430     ts.isSyntheticReference = isSyntheticReference;
12431     /* @internal */
12432     function isNotEmittedOrPartiallyEmittedNode(node) {
12433         return isNotEmittedStatement(node)
12434             || isPartiallyEmittedExpression(node);
12435     }
12436     ts.isNotEmittedOrPartiallyEmittedNode = isNotEmittedOrPartiallyEmittedNode;
12437     function isIterationStatement(node, lookInLabeledStatements) {
12438         switch (node.kind) {
12439             case 230 /* ForStatement */:
12440             case 231 /* ForInStatement */:
12441             case 232 /* ForOfStatement */:
12442             case 228 /* DoStatement */:
12443             case 229 /* WhileStatement */:
12444                 return true;
12445             case 238 /* LabeledStatement */:
12446                 return lookInLabeledStatements && isIterationStatement(node.statement, lookInLabeledStatements);
12447         }
12448         return false;
12449     }
12450     ts.isIterationStatement = isIterationStatement;
12451     /* @internal */
12452     function isScopeMarker(node) {
12453         return isExportAssignment(node) || isExportDeclaration(node);
12454     }
12455     ts.isScopeMarker = isScopeMarker;
12456     /* @internal */
12457     function hasScopeMarker(statements) {
12458         return ts.some(statements, isScopeMarker);
12459     }
12460     ts.hasScopeMarker = hasScopeMarker;
12461     /* @internal */
12462     function needsScopeMarker(result) {
12463         return !ts.isAnyImportOrReExport(result) && !isExportAssignment(result) && !ts.hasModifier(result, 1 /* Export */) && !ts.isAmbientModule(result);
12464     }
12465     ts.needsScopeMarker = needsScopeMarker;
12466     /* @internal */
12467     function isExternalModuleIndicator(result) {
12468         // Exported top-level member indicates moduleness
12469         return ts.isAnyImportOrReExport(result) || isExportAssignment(result) || ts.hasModifier(result, 1 /* Export */);
12470     }
12471     ts.isExternalModuleIndicator = isExternalModuleIndicator;
12472     /* @internal */
12473     function isForInOrOfStatement(node) {
12474         return node.kind === 231 /* ForInStatement */ || node.kind === 232 /* ForOfStatement */;
12475     }
12476     ts.isForInOrOfStatement = isForInOrOfStatement;
12477     // Element
12478     /* @internal */
12479     function isConciseBody(node) {
12480         return isBlock(node)
12481             || isExpression(node);
12482     }
12483     ts.isConciseBody = isConciseBody;
12484     /* @internal */
12485     function isFunctionBody(node) {
12486         return isBlock(node);
12487     }
12488     ts.isFunctionBody = isFunctionBody;
12489     /* @internal */
12490     function isForInitializer(node) {
12491         return isVariableDeclarationList(node)
12492             || isExpression(node);
12493     }
12494     ts.isForInitializer = isForInitializer;
12495     /* @internal */
12496     function isModuleBody(node) {
12497         var kind = node.kind;
12498         return kind === 250 /* ModuleBlock */
12499             || kind === 249 /* ModuleDeclaration */
12500             || kind === 75 /* Identifier */;
12501     }
12502     ts.isModuleBody = isModuleBody;
12503     /* @internal */
12504     function isNamespaceBody(node) {
12505         var kind = node.kind;
12506         return kind === 250 /* ModuleBlock */
12507             || kind === 249 /* ModuleDeclaration */;
12508     }
12509     ts.isNamespaceBody = isNamespaceBody;
12510     /* @internal */
12511     function isJSDocNamespaceBody(node) {
12512         var kind = node.kind;
12513         return kind === 75 /* Identifier */
12514             || kind === 249 /* ModuleDeclaration */;
12515     }
12516     ts.isJSDocNamespaceBody = isJSDocNamespaceBody;
12517     /* @internal */
12518     function isNamedImportBindings(node) {
12519         var kind = node.kind;
12520         return kind === 257 /* NamedImports */
12521             || kind === 256 /* NamespaceImport */;
12522     }
12523     ts.isNamedImportBindings = isNamedImportBindings;
12524     /* @internal */
12525     function isModuleOrEnumDeclaration(node) {
12526         return node.kind === 249 /* ModuleDeclaration */ || node.kind === 248 /* EnumDeclaration */;
12527     }
12528     ts.isModuleOrEnumDeclaration = isModuleOrEnumDeclaration;
12529     function isDeclarationKind(kind) {
12530         return kind === 202 /* ArrowFunction */
12531             || kind === 191 /* BindingElement */
12532             || kind === 245 /* ClassDeclaration */
12533             || kind === 214 /* ClassExpression */
12534             || kind === 162 /* Constructor */
12535             || kind === 248 /* EnumDeclaration */
12536             || kind === 284 /* EnumMember */
12537             || kind === 263 /* ExportSpecifier */
12538             || kind === 244 /* FunctionDeclaration */
12539             || kind === 201 /* FunctionExpression */
12540             || kind === 163 /* GetAccessor */
12541             || kind === 255 /* ImportClause */
12542             || kind === 253 /* ImportEqualsDeclaration */
12543             || kind === 258 /* ImportSpecifier */
12544             || kind === 246 /* InterfaceDeclaration */
12545             || kind === 273 /* JsxAttribute */
12546             || kind === 161 /* MethodDeclaration */
12547             || kind === 160 /* MethodSignature */
12548             || kind === 249 /* ModuleDeclaration */
12549             || kind === 252 /* NamespaceExportDeclaration */
12550             || kind === 256 /* NamespaceImport */
12551             || kind === 262 /* NamespaceExport */
12552             || kind === 156 /* Parameter */
12553             || kind === 281 /* PropertyAssignment */
12554             || kind === 159 /* PropertyDeclaration */
12555             || kind === 158 /* PropertySignature */
12556             || kind === 164 /* SetAccessor */
12557             || kind === 282 /* ShorthandPropertyAssignment */
12558             || kind === 247 /* TypeAliasDeclaration */
12559             || kind === 155 /* TypeParameter */
12560             || kind === 242 /* VariableDeclaration */
12561             || kind === 322 /* JSDocTypedefTag */
12562             || kind === 315 /* JSDocCallbackTag */
12563             || kind === 323 /* JSDocPropertyTag */;
12564     }
12565     function isDeclarationStatementKind(kind) {
12566         return kind === 244 /* FunctionDeclaration */
12567             || kind === 264 /* MissingDeclaration */
12568             || kind === 245 /* ClassDeclaration */
12569             || kind === 246 /* InterfaceDeclaration */
12570             || kind === 247 /* TypeAliasDeclaration */
12571             || kind === 248 /* EnumDeclaration */
12572             || kind === 249 /* ModuleDeclaration */
12573             || kind === 254 /* ImportDeclaration */
12574             || kind === 253 /* ImportEqualsDeclaration */
12575             || kind === 260 /* ExportDeclaration */
12576             || kind === 259 /* ExportAssignment */
12577             || kind === 252 /* NamespaceExportDeclaration */;
12578     }
12579     function isStatementKindButNotDeclarationKind(kind) {
12580         return kind === 234 /* BreakStatement */
12581             || kind === 233 /* ContinueStatement */
12582             || kind === 241 /* DebuggerStatement */
12583             || kind === 228 /* DoStatement */
12584             || kind === 226 /* ExpressionStatement */
12585             || kind === 224 /* EmptyStatement */
12586             || kind === 231 /* ForInStatement */
12587             || kind === 232 /* ForOfStatement */
12588             || kind === 230 /* ForStatement */
12589             || kind === 227 /* IfStatement */
12590             || kind === 238 /* LabeledStatement */
12591             || kind === 235 /* ReturnStatement */
12592             || kind === 237 /* SwitchStatement */
12593             || kind === 239 /* ThrowStatement */
12594             || kind === 240 /* TryStatement */
12595             || kind === 225 /* VariableStatement */
12596             || kind === 229 /* WhileStatement */
12597             || kind === 236 /* WithStatement */
12598             || kind === 325 /* NotEmittedStatement */
12599             || kind === 329 /* EndOfDeclarationMarker */
12600             || kind === 328 /* MergeDeclarationMarker */;
12601     }
12602     /* @internal */
12603     function isDeclaration(node) {
12604         if (node.kind === 155 /* TypeParameter */) {
12605             return (node.parent && node.parent.kind !== 321 /* JSDocTemplateTag */) || ts.isInJSFile(node);
12606         }
12607         return isDeclarationKind(node.kind);
12608     }
12609     ts.isDeclaration = isDeclaration;
12610     /* @internal */
12611     function isDeclarationStatement(node) {
12612         return isDeclarationStatementKind(node.kind);
12613     }
12614     ts.isDeclarationStatement = isDeclarationStatement;
12615     /**
12616      * Determines whether the node is a statement that is not also a declaration
12617      */
12618     /* @internal */
12619     function isStatementButNotDeclaration(node) {
12620         return isStatementKindButNotDeclarationKind(node.kind);
12621     }
12622     ts.isStatementButNotDeclaration = isStatementButNotDeclaration;
12623     /* @internal */
12624     function isStatement(node) {
12625         var kind = node.kind;
12626         return isStatementKindButNotDeclarationKind(kind)
12627             || isDeclarationStatementKind(kind)
12628             || isBlockStatement(node);
12629     }
12630     ts.isStatement = isStatement;
12631     function isBlockStatement(node) {
12632         if (node.kind !== 223 /* Block */)
12633             return false;
12634         if (node.parent !== undefined) {
12635             if (node.parent.kind === 240 /* TryStatement */ || node.parent.kind === 280 /* CatchClause */) {
12636                 return false;
12637             }
12638         }
12639         return !ts.isFunctionBlock(node);
12640     }
12641     // Module references
12642     /* @internal */
12643     function isModuleReference(node) {
12644         var kind = node.kind;
12645         return kind === 265 /* ExternalModuleReference */
12646             || kind === 153 /* QualifiedName */
12647             || kind === 75 /* Identifier */;
12648     }
12649     ts.isModuleReference = isModuleReference;
12650     // JSX
12651     /* @internal */
12652     function isJsxTagNameExpression(node) {
12653         var kind = node.kind;
12654         return kind === 104 /* ThisKeyword */
12655             || kind === 75 /* Identifier */
12656             || kind === 194 /* PropertyAccessExpression */;
12657     }
12658     ts.isJsxTagNameExpression = isJsxTagNameExpression;
12659     /* @internal */
12660     function isJsxChild(node) {
12661         var kind = node.kind;
12662         return kind === 266 /* JsxElement */
12663             || kind === 276 /* JsxExpression */
12664             || kind === 267 /* JsxSelfClosingElement */
12665             || kind === 11 /* JsxText */
12666             || kind === 270 /* JsxFragment */;
12667     }
12668     ts.isJsxChild = isJsxChild;
12669     /* @internal */
12670     function isJsxAttributeLike(node) {
12671         var kind = node.kind;
12672         return kind === 273 /* JsxAttribute */
12673             || kind === 275 /* JsxSpreadAttribute */;
12674     }
12675     ts.isJsxAttributeLike = isJsxAttributeLike;
12676     /* @internal */
12677     function isStringLiteralOrJsxExpression(node) {
12678         var kind = node.kind;
12679         return kind === 10 /* StringLiteral */
12680             || kind === 276 /* JsxExpression */;
12681     }
12682     ts.isStringLiteralOrJsxExpression = isStringLiteralOrJsxExpression;
12683     function isJsxOpeningLikeElement(node) {
12684         var kind = node.kind;
12685         return kind === 268 /* JsxOpeningElement */
12686             || kind === 267 /* JsxSelfClosingElement */;
12687     }
12688     ts.isJsxOpeningLikeElement = isJsxOpeningLikeElement;
12689     // Clauses
12690     function isCaseOrDefaultClause(node) {
12691         var kind = node.kind;
12692         return kind === 277 /* CaseClause */
12693             || kind === 278 /* DefaultClause */;
12694     }
12695     ts.isCaseOrDefaultClause = isCaseOrDefaultClause;
12696     // JSDoc
12697     /** True if node is of some JSDoc syntax kind. */
12698     /* @internal */
12699     function isJSDocNode(node) {
12700         return node.kind >= 294 /* FirstJSDocNode */ && node.kind <= 323 /* LastJSDocNode */;
12701     }
12702     ts.isJSDocNode = isJSDocNode;
12703     /** True if node is of a kind that may contain comment text. */
12704     function isJSDocCommentContainingNode(node) {
12705         return node.kind === 303 /* JSDocComment */ || node.kind === 302 /* JSDocNamepathType */ || isJSDocTag(node) || isJSDocTypeLiteral(node) || isJSDocSignature(node);
12706     }
12707     ts.isJSDocCommentContainingNode = isJSDocCommentContainingNode;
12708     // TODO: determine what this does before making it public.
12709     /* @internal */
12710     function isJSDocTag(node) {
12711         return node.kind >= 306 /* FirstJSDocTagNode */ && node.kind <= 323 /* LastJSDocTagNode */;
12712     }
12713     ts.isJSDocTag = isJSDocTag;
12714     function isSetAccessor(node) {
12715         return node.kind === 164 /* SetAccessor */;
12716     }
12717     ts.isSetAccessor = isSetAccessor;
12718     function isGetAccessor(node) {
12719         return node.kind === 163 /* GetAccessor */;
12720     }
12721     ts.isGetAccessor = isGetAccessor;
12722     /** True if has jsdoc nodes attached to it. */
12723     /* @internal */
12724     // TODO: GH#19856 Would like to return `node is Node & { jsDoc: JSDoc[] }` but it causes long compile times
12725     function hasJSDocNodes(node) {
12726         var jsDoc = node.jsDoc;
12727         return !!jsDoc && jsDoc.length > 0;
12728     }
12729     ts.hasJSDocNodes = hasJSDocNodes;
12730     /** True if has type node attached to it. */
12731     /* @internal */
12732     function hasType(node) {
12733         return !!node.type;
12734     }
12735     ts.hasType = hasType;
12736     /** True if has initializer node attached to it. */
12737     /* @internal */
12738     function hasInitializer(node) {
12739         return !!node.initializer;
12740     }
12741     ts.hasInitializer = hasInitializer;
12742     /** True if has initializer node attached to it. */
12743     function hasOnlyExpressionInitializer(node) {
12744         switch (node.kind) {
12745             case 242 /* VariableDeclaration */:
12746             case 156 /* Parameter */:
12747             case 191 /* BindingElement */:
12748             case 158 /* PropertySignature */:
12749             case 159 /* PropertyDeclaration */:
12750             case 281 /* PropertyAssignment */:
12751             case 284 /* EnumMember */:
12752                 return true;
12753             default:
12754                 return false;
12755         }
12756     }
12757     ts.hasOnlyExpressionInitializer = hasOnlyExpressionInitializer;
12758     function isObjectLiteralElement(node) {
12759         return node.kind === 273 /* JsxAttribute */ || node.kind === 275 /* JsxSpreadAttribute */ || isObjectLiteralElementLike(node);
12760     }
12761     ts.isObjectLiteralElement = isObjectLiteralElement;
12762     /* @internal */
12763     function isTypeReferenceType(node) {
12764         return node.kind === 169 /* TypeReference */ || node.kind === 216 /* ExpressionWithTypeArguments */;
12765     }
12766     ts.isTypeReferenceType = isTypeReferenceType;
12767     var MAX_SMI_X86 = 1073741823;
12768     /* @internal */
12769     function guessIndentation(lines) {
12770         var indentation = MAX_SMI_X86;
12771         for (var _i = 0, lines_1 = lines; _i < lines_1.length; _i++) {
12772             var line = lines_1[_i];
12773             if (!line.length) {
12774                 continue;
12775             }
12776             var i = 0;
12777             for (; i < line.length && i < indentation; i++) {
12778                 if (!ts.isWhiteSpaceLike(line.charCodeAt(i))) {
12779                     break;
12780                 }
12781             }
12782             if (i < indentation) {
12783                 indentation = i;
12784             }
12785             if (indentation === 0) {
12786                 return 0;
12787             }
12788         }
12789         return indentation === MAX_SMI_X86 ? undefined : indentation;
12790     }
12791     ts.guessIndentation = guessIndentation;
12792     function isStringLiteralLike(node) {
12793         return node.kind === 10 /* StringLiteral */ || node.kind === 14 /* NoSubstitutionTemplateLiteral */;
12794     }
12795     ts.isStringLiteralLike = isStringLiteralLike;
12796     // #endregion
12797 })(ts || (ts = {}));
12798 /* @internal */
12799 var ts;
12800 (function (ts) {
12801     ts.resolvingEmptyArray = [];
12802     ts.emptyMap = ts.createMap();
12803     ts.emptyUnderscoreEscapedMap = ts.emptyMap;
12804     ts.externalHelpersModuleNameText = "tslib";
12805     ts.defaultMaximumTruncationLength = 160;
12806     ts.noTruncationMaximumTruncationLength = 1000000;
12807     function getDeclarationOfKind(symbol, kind) {
12808         var declarations = symbol.declarations;
12809         if (declarations) {
12810             for (var _i = 0, declarations_1 = declarations; _i < declarations_1.length; _i++) {
12811                 var declaration = declarations_1[_i];
12812                 if (declaration.kind === kind) {
12813                     return declaration;
12814                 }
12815             }
12816         }
12817         return undefined;
12818     }
12819     ts.getDeclarationOfKind = getDeclarationOfKind;
12820     /** Create a new escaped identifier map. */
12821     function createUnderscoreEscapedMap() {
12822         return new ts.Map();
12823     }
12824     ts.createUnderscoreEscapedMap = createUnderscoreEscapedMap;
12825     function hasEntries(map) {
12826         return !!map && !!map.size;
12827     }
12828     ts.hasEntries = hasEntries;
12829     function createSymbolTable(symbols) {
12830         var result = ts.createMap();
12831         if (symbols) {
12832             for (var _i = 0, symbols_1 = symbols; _i < symbols_1.length; _i++) {
12833                 var symbol = symbols_1[_i];
12834                 result.set(symbol.escapedName, symbol);
12835             }
12836         }
12837         return result;
12838     }
12839     ts.createSymbolTable = createSymbolTable;
12840     function isTransientSymbol(symbol) {
12841         return (symbol.flags & 33554432 /* Transient */) !== 0;
12842     }
12843     ts.isTransientSymbol = isTransientSymbol;
12844     var stringWriter = createSingleLineStringWriter();
12845     function createSingleLineStringWriter() {
12846         var str = "";
12847         var writeText = function (text) { return str += text; };
12848         return {
12849             getText: function () { return str; },
12850             write: writeText,
12851             rawWrite: writeText,
12852             writeKeyword: writeText,
12853             writeOperator: writeText,
12854             writePunctuation: writeText,
12855             writeSpace: writeText,
12856             writeStringLiteral: writeText,
12857             writeLiteral: writeText,
12858             writeParameter: writeText,
12859             writeProperty: writeText,
12860             writeSymbol: function (s, _) { return writeText(s); },
12861             writeTrailingSemicolon: writeText,
12862             writeComment: writeText,
12863             getTextPos: function () { return str.length; },
12864             getLine: function () { return 0; },
12865             getColumn: function () { return 0; },
12866             getIndent: function () { return 0; },
12867             isAtStartOfLine: function () { return false; },
12868             hasTrailingComment: function () { return false; },
12869             hasTrailingWhitespace: function () { return !!str.length && ts.isWhiteSpaceLike(str.charCodeAt(str.length - 1)); },
12870             // Completely ignore indentation for string writers.  And map newlines to
12871             // a single space.
12872             writeLine: function () { return str += " "; },
12873             increaseIndent: ts.noop,
12874             decreaseIndent: ts.noop,
12875             clear: function () { return str = ""; },
12876             trackSymbol: ts.noop,
12877             reportInaccessibleThisError: ts.noop,
12878             reportInaccessibleUniqueSymbolError: ts.noop,
12879             reportPrivateInBaseOfClassExpression: ts.noop,
12880         };
12881     }
12882     function changesAffectModuleResolution(oldOptions, newOptions) {
12883         return oldOptions.configFilePath !== newOptions.configFilePath ||
12884             optionsHaveModuleResolutionChanges(oldOptions, newOptions);
12885     }
12886     ts.changesAffectModuleResolution = changesAffectModuleResolution;
12887     function optionsHaveModuleResolutionChanges(oldOptions, newOptions) {
12888         return ts.moduleResolutionOptionDeclarations.some(function (o) {
12889             return !isJsonEqual(getCompilerOptionValue(oldOptions, o), getCompilerOptionValue(newOptions, o));
12890         });
12891     }
12892     ts.optionsHaveModuleResolutionChanges = optionsHaveModuleResolutionChanges;
12893     function findAncestor(node, callback) {
12894         while (node) {
12895             var result = callback(node);
12896             if (result === "quit") {
12897                 return undefined;
12898             }
12899             else if (result) {
12900                 return node;
12901             }
12902             node = node.parent;
12903         }
12904         return undefined;
12905     }
12906     ts.findAncestor = findAncestor;
12907     function forEachAncestor(node, callback) {
12908         while (true) {
12909             var res = callback(node);
12910             if (res === "quit")
12911                 return undefined;
12912             if (res !== undefined)
12913                 return res;
12914             if (ts.isSourceFile(node))
12915                 return undefined;
12916             node = node.parent;
12917         }
12918     }
12919     ts.forEachAncestor = forEachAncestor;
12920     function forEachEntry(map, callback) {
12921         var iterator = map.entries();
12922         for (var iterResult = iterator.next(); !iterResult.done; iterResult = iterator.next()) {
12923             var _a = iterResult.value, key = _a[0], value = _a[1];
12924             var result = callback(value, key);
12925             if (result) {
12926                 return result;
12927             }
12928         }
12929         return undefined;
12930     }
12931     ts.forEachEntry = forEachEntry;
12932     function forEachKey(map, callback) {
12933         var iterator = map.keys();
12934         for (var iterResult = iterator.next(); !iterResult.done; iterResult = iterator.next()) {
12935             var result = callback(iterResult.value);
12936             if (result) {
12937                 return result;
12938             }
12939         }
12940         return undefined;
12941     }
12942     ts.forEachKey = forEachKey;
12943     function copyEntries(source, target) {
12944         source.forEach(function (value, key) {
12945             target.set(key, value);
12946         });
12947     }
12948     ts.copyEntries = copyEntries;
12949     function arrayToSet(array, makeKey) {
12950         return ts.arrayToMap(array, makeKey || (function (s) { return s; }), ts.returnTrue);
12951     }
12952     ts.arrayToSet = arrayToSet;
12953     function cloneMap(map) {
12954         var clone = ts.createMap();
12955         copyEntries(map, clone);
12956         return clone;
12957     }
12958     ts.cloneMap = cloneMap;
12959     function usingSingleLineStringWriter(action) {
12960         var oldString = stringWriter.getText();
12961         try {
12962             action(stringWriter);
12963             return stringWriter.getText();
12964         }
12965         finally {
12966             stringWriter.clear();
12967             stringWriter.writeKeyword(oldString);
12968         }
12969     }
12970     ts.usingSingleLineStringWriter = usingSingleLineStringWriter;
12971     function getFullWidth(node) {
12972         return node.end - node.pos;
12973     }
12974     ts.getFullWidth = getFullWidth;
12975     function getResolvedModule(sourceFile, moduleNameText) {
12976         return sourceFile && sourceFile.resolvedModules && sourceFile.resolvedModules.get(moduleNameText);
12977     }
12978     ts.getResolvedModule = getResolvedModule;
12979     function setResolvedModule(sourceFile, moduleNameText, resolvedModule) {
12980         if (!sourceFile.resolvedModules) {
12981             sourceFile.resolvedModules = ts.createMap();
12982         }
12983         sourceFile.resolvedModules.set(moduleNameText, resolvedModule);
12984     }
12985     ts.setResolvedModule = setResolvedModule;
12986     function setResolvedTypeReferenceDirective(sourceFile, typeReferenceDirectiveName, resolvedTypeReferenceDirective) {
12987         if (!sourceFile.resolvedTypeReferenceDirectiveNames) {
12988             sourceFile.resolvedTypeReferenceDirectiveNames = ts.createMap();
12989         }
12990         sourceFile.resolvedTypeReferenceDirectiveNames.set(typeReferenceDirectiveName, resolvedTypeReferenceDirective);
12991     }
12992     ts.setResolvedTypeReferenceDirective = setResolvedTypeReferenceDirective;
12993     function projectReferenceIsEqualTo(oldRef, newRef) {
12994         return oldRef.path === newRef.path &&
12995             !oldRef.prepend === !newRef.prepend &&
12996             !oldRef.circular === !newRef.circular;
12997     }
12998     ts.projectReferenceIsEqualTo = projectReferenceIsEqualTo;
12999     function moduleResolutionIsEqualTo(oldResolution, newResolution) {
13000         return oldResolution.isExternalLibraryImport === newResolution.isExternalLibraryImport &&
13001             oldResolution.extension === newResolution.extension &&
13002             oldResolution.resolvedFileName === newResolution.resolvedFileName &&
13003             oldResolution.originalPath === newResolution.originalPath &&
13004             packageIdIsEqual(oldResolution.packageId, newResolution.packageId);
13005     }
13006     ts.moduleResolutionIsEqualTo = moduleResolutionIsEqualTo;
13007     function packageIdIsEqual(a, b) {
13008         return a === b || !!a && !!b && a.name === b.name && a.subModuleName === b.subModuleName && a.version === b.version;
13009     }
13010     function packageIdToString(_a) {
13011         var name = _a.name, subModuleName = _a.subModuleName, version = _a.version;
13012         var fullName = subModuleName ? name + "/" + subModuleName : name;
13013         return fullName + "@" + version;
13014     }
13015     ts.packageIdToString = packageIdToString;
13016     function typeDirectiveIsEqualTo(oldResolution, newResolution) {
13017         return oldResolution.resolvedFileName === newResolution.resolvedFileName && oldResolution.primary === newResolution.primary;
13018     }
13019     ts.typeDirectiveIsEqualTo = typeDirectiveIsEqualTo;
13020     function hasChangesInResolutions(names, newResolutions, oldResolutions, comparer) {
13021         ts.Debug.assert(names.length === newResolutions.length);
13022         for (var i = 0; i < names.length; i++) {
13023             var newResolution = newResolutions[i];
13024             var oldResolution = oldResolutions && oldResolutions.get(names[i]);
13025             var changed = oldResolution
13026                 ? !newResolution || !comparer(oldResolution, newResolution)
13027                 : newResolution;
13028             if (changed) {
13029                 return true;
13030             }
13031         }
13032         return false;
13033     }
13034     ts.hasChangesInResolutions = hasChangesInResolutions;
13035     // Returns true if this node contains a parse error anywhere underneath it.
13036     function containsParseError(node) {
13037         aggregateChildData(node);
13038         return (node.flags & 262144 /* ThisNodeOrAnySubNodesHasError */) !== 0;
13039     }
13040     ts.containsParseError = containsParseError;
13041     function aggregateChildData(node) {
13042         if (!(node.flags & 524288 /* HasAggregatedChildData */)) {
13043             // A node is considered to contain a parse error if:
13044             //  a) the parser explicitly marked that it had an error
13045             //  b) any of it's children reported that it had an error.
13046             var thisNodeOrAnySubNodesHasError = ((node.flags & 65536 /* ThisNodeHasError */) !== 0) ||
13047                 ts.forEachChild(node, containsParseError);
13048             // If so, mark ourselves accordingly.
13049             if (thisNodeOrAnySubNodesHasError) {
13050                 node.flags |= 262144 /* ThisNodeOrAnySubNodesHasError */;
13051             }
13052             // Also mark that we've propagated the child information to this node.  This way we can
13053             // always consult the bit directly on this node without needing to check its children
13054             // again.
13055             node.flags |= 524288 /* HasAggregatedChildData */;
13056         }
13057     }
13058     function getSourceFileOfNode(node) {
13059         while (node && node.kind !== 290 /* SourceFile */) {
13060             node = node.parent;
13061         }
13062         return node;
13063     }
13064     ts.getSourceFileOfNode = getSourceFileOfNode;
13065     function isStatementWithLocals(node) {
13066         switch (node.kind) {
13067             case 223 /* Block */:
13068             case 251 /* CaseBlock */:
13069             case 230 /* ForStatement */:
13070             case 231 /* ForInStatement */:
13071             case 232 /* ForOfStatement */:
13072                 return true;
13073         }
13074         return false;
13075     }
13076     ts.isStatementWithLocals = isStatementWithLocals;
13077     function getStartPositionOfLine(line, sourceFile) {
13078         ts.Debug.assert(line >= 0);
13079         return ts.getLineStarts(sourceFile)[line];
13080     }
13081     ts.getStartPositionOfLine = getStartPositionOfLine;
13082     // This is a useful function for debugging purposes.
13083     function nodePosToString(node) {
13084         var file = getSourceFileOfNode(node);
13085         var loc = ts.getLineAndCharacterOfPosition(file, node.pos);
13086         return file.fileName + "(" + (loc.line + 1) + "," + (loc.character + 1) + ")";
13087     }
13088     ts.nodePosToString = nodePosToString;
13089     function getEndLinePosition(line, sourceFile) {
13090         ts.Debug.assert(line >= 0);
13091         var lineStarts = ts.getLineStarts(sourceFile);
13092         var lineIndex = line;
13093         var sourceText = sourceFile.text;
13094         if (lineIndex + 1 === lineStarts.length) {
13095             // last line - return EOF
13096             return sourceText.length - 1;
13097         }
13098         else {
13099             // current line start
13100             var start = lineStarts[lineIndex];
13101             // take the start position of the next line - 1 = it should be some line break
13102             var pos = lineStarts[lineIndex + 1] - 1;
13103             ts.Debug.assert(ts.isLineBreak(sourceText.charCodeAt(pos)));
13104             // walk backwards skipping line breaks, stop the the beginning of current line.
13105             // i.e:
13106             // <some text>
13107             // $ <- end of line for this position should match the start position
13108             while (start <= pos && ts.isLineBreak(sourceText.charCodeAt(pos))) {
13109                 pos--;
13110             }
13111             return pos;
13112         }
13113     }
13114     ts.getEndLinePosition = getEndLinePosition;
13115     /**
13116      * Returns a value indicating whether a name is unique globally or within the current file.
13117      * 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`.
13118      */
13119     function isFileLevelUniqueName(sourceFile, name, hasGlobalName) {
13120         return !(hasGlobalName && hasGlobalName(name)) && !sourceFile.identifiers.has(name);
13121     }
13122     ts.isFileLevelUniqueName = isFileLevelUniqueName;
13123     // Returns true if this node is missing from the actual source code. A 'missing' node is different
13124     // from 'undefined/defined'. When a node is undefined (which can happen for optional nodes
13125     // in the tree), it is definitely missing. However, a node may be defined, but still be
13126     // missing.  This happens whenever the parser knows it needs to parse something, but can't
13127     // get anything in the source code that it expects at that location. For example:
13128     //
13129     //          let a: ;
13130     //
13131     // Here, the Type in the Type-Annotation is not-optional (as there is a colon in the source
13132     // code). So the parser will attempt to parse out a type, and will create an actual node.
13133     // However, this node will be 'missing' in the sense that no actual source-code/tokens are
13134     // contained within it.
13135     function nodeIsMissing(node) {
13136         if (node === undefined) {
13137             return true;
13138         }
13139         return node.pos === node.end && node.pos >= 0 && node.kind !== 1 /* EndOfFileToken */;
13140     }
13141     ts.nodeIsMissing = nodeIsMissing;
13142     function nodeIsPresent(node) {
13143         return !nodeIsMissing(node);
13144     }
13145     ts.nodeIsPresent = nodeIsPresent;
13146     function insertStatementsAfterPrologue(to, from, isPrologueDirective) {
13147         if (from === undefined || from.length === 0)
13148             return to;
13149         var statementIndex = 0;
13150         // skip all prologue directives to insert at the correct position
13151         for (; statementIndex < to.length; ++statementIndex) {
13152             if (!isPrologueDirective(to[statementIndex])) {
13153                 break;
13154             }
13155         }
13156         to.splice.apply(to, __spreadArrays([statementIndex, 0], from));
13157         return to;
13158     }
13159     function insertStatementAfterPrologue(to, statement, isPrologueDirective) {
13160         if (statement === undefined)
13161             return to;
13162         var statementIndex = 0;
13163         // skip all prologue directives to insert at the correct position
13164         for (; statementIndex < to.length; ++statementIndex) {
13165             if (!isPrologueDirective(to[statementIndex])) {
13166                 break;
13167             }
13168         }
13169         to.splice(statementIndex, 0, statement);
13170         return to;
13171     }
13172     function isAnyPrologueDirective(node) {
13173         return isPrologueDirective(node) || !!(getEmitFlags(node) & 1048576 /* CustomPrologue */);
13174     }
13175     /**
13176      * Prepends statements to an array while taking care of prologue directives.
13177      */
13178     function insertStatementsAfterStandardPrologue(to, from) {
13179         return insertStatementsAfterPrologue(to, from, isPrologueDirective);
13180     }
13181     ts.insertStatementsAfterStandardPrologue = insertStatementsAfterStandardPrologue;
13182     function insertStatementsAfterCustomPrologue(to, from) {
13183         return insertStatementsAfterPrologue(to, from, isAnyPrologueDirective);
13184     }
13185     ts.insertStatementsAfterCustomPrologue = insertStatementsAfterCustomPrologue;
13186     /**
13187      * Prepends statements to an array while taking care of prologue directives.
13188      */
13189     function insertStatementAfterStandardPrologue(to, statement) {
13190         return insertStatementAfterPrologue(to, statement, isPrologueDirective);
13191     }
13192     ts.insertStatementAfterStandardPrologue = insertStatementAfterStandardPrologue;
13193     function insertStatementAfterCustomPrologue(to, statement) {
13194         return insertStatementAfterPrologue(to, statement, isAnyPrologueDirective);
13195     }
13196     ts.insertStatementAfterCustomPrologue = insertStatementAfterCustomPrologue;
13197     /**
13198      * Determine if the given comment is a triple-slash
13199      *
13200      * @return true if the comment is a triple-slash comment else false
13201      */
13202     function isRecognizedTripleSlashComment(text, commentPos, commentEnd) {
13203         // Verify this is /// comment, but do the regexp match only when we first can find /// in the comment text
13204         // so that we don't end up computing comment string and doing match for all // comments
13205         if (text.charCodeAt(commentPos + 1) === 47 /* slash */ &&
13206             commentPos + 2 < commentEnd &&
13207             text.charCodeAt(commentPos + 2) === 47 /* slash */) {
13208             var textSubStr = text.substring(commentPos, commentEnd);
13209             return textSubStr.match(ts.fullTripleSlashReferencePathRegEx) ||
13210                 textSubStr.match(ts.fullTripleSlashAMDReferencePathRegEx) ||
13211                 textSubStr.match(fullTripleSlashReferenceTypeReferenceDirectiveRegEx) ||
13212                 textSubStr.match(defaultLibReferenceRegEx) ?
13213                 true : false;
13214         }
13215         return false;
13216     }
13217     ts.isRecognizedTripleSlashComment = isRecognizedTripleSlashComment;
13218     function isPinnedComment(text, start) {
13219         return text.charCodeAt(start + 1) === 42 /* asterisk */ &&
13220             text.charCodeAt(start + 2) === 33 /* exclamation */;
13221     }
13222     ts.isPinnedComment = isPinnedComment;
13223     function createCommentDirectivesMap(sourceFile, commentDirectives) {
13224         var directivesByLine = ts.createMapFromEntries(commentDirectives.map(function (commentDirective) { return ([
13225             "" + ts.getLineAndCharacterOfPosition(sourceFile, commentDirective.range.end).line,
13226             commentDirective,
13227         ]); }));
13228         var usedLines = ts.createMap();
13229         return { getUnusedExpectations: getUnusedExpectations, markUsed: markUsed };
13230         function getUnusedExpectations() {
13231             return ts.arrayFrom(directivesByLine.entries())
13232                 .filter(function (_a) {
13233                 var line = _a[0], directive = _a[1];
13234                 return directive.type === 0 /* ExpectError */ && !usedLines.get(line);
13235             })
13236                 .map(function (_a) {
13237                 var _ = _a[0], directive = _a[1];
13238                 return directive;
13239             });
13240         }
13241         function markUsed(line) {
13242             if (!directivesByLine.has("" + line)) {
13243                 return false;
13244             }
13245             usedLines.set("" + line, true);
13246             return true;
13247         }
13248     }
13249     ts.createCommentDirectivesMap = createCommentDirectivesMap;
13250     function getTokenPosOfNode(node, sourceFile, includeJsDoc) {
13251         // With nodes that have no width (i.e. 'Missing' nodes), we actually *don't*
13252         // want to skip trivia because this will launch us forward to the next token.
13253         if (nodeIsMissing(node)) {
13254             return node.pos;
13255         }
13256         if (ts.isJSDocNode(node)) {
13257             return ts.skipTrivia((sourceFile || getSourceFileOfNode(node)).text, node.pos, /*stopAfterLineBreak*/ false, /*stopAtComments*/ true);
13258         }
13259         if (includeJsDoc && ts.hasJSDocNodes(node)) {
13260             return getTokenPosOfNode(node.jsDoc[0], sourceFile);
13261         }
13262         // For a syntax list, it is possible that one of its children has JSDocComment nodes, while
13263         // the syntax list itself considers them as normal trivia. Therefore if we simply skip
13264         // trivia for the list, we may have skipped the JSDocComment as well. So we should process its
13265         // first child to determine the actual position of its first token.
13266         if (node.kind === 324 /* SyntaxList */ && node._children.length > 0) {
13267             return getTokenPosOfNode(node._children[0], sourceFile, includeJsDoc);
13268         }
13269         return ts.skipTrivia((sourceFile || getSourceFileOfNode(node)).text, node.pos);
13270     }
13271     ts.getTokenPosOfNode = getTokenPosOfNode;
13272     function getNonDecoratorTokenPosOfNode(node, sourceFile) {
13273         if (nodeIsMissing(node) || !node.decorators) {
13274             return getTokenPosOfNode(node, sourceFile);
13275         }
13276         return ts.skipTrivia((sourceFile || getSourceFileOfNode(node)).text, node.decorators.end);
13277     }
13278     ts.getNonDecoratorTokenPosOfNode = getNonDecoratorTokenPosOfNode;
13279     function getSourceTextOfNodeFromSourceFile(sourceFile, node, includeTrivia) {
13280         if (includeTrivia === void 0) { includeTrivia = false; }
13281         return getTextOfNodeFromSourceText(sourceFile.text, node, includeTrivia);
13282     }
13283     ts.getSourceTextOfNodeFromSourceFile = getSourceTextOfNodeFromSourceFile;
13284     function isJSDocTypeExpressionOrChild(node) {
13285         return !!findAncestor(node, ts.isJSDocTypeExpression);
13286     }
13287     function getTextOfNodeFromSourceText(sourceText, node, includeTrivia) {
13288         if (includeTrivia === void 0) { includeTrivia = false; }
13289         if (nodeIsMissing(node)) {
13290             return "";
13291         }
13292         var text = sourceText.substring(includeTrivia ? node.pos : ts.skipTrivia(sourceText, node.pos), node.end);
13293         if (isJSDocTypeExpressionOrChild(node)) {
13294             // strip space + asterisk at line start
13295             text = text.replace(/(^|\r?\n|\r)\s*\*\s*/g, "$1");
13296         }
13297         return text;
13298     }
13299     ts.getTextOfNodeFromSourceText = getTextOfNodeFromSourceText;
13300     function getTextOfNode(node, includeTrivia) {
13301         if (includeTrivia === void 0) { includeTrivia = false; }
13302         return getSourceTextOfNodeFromSourceFile(getSourceFileOfNode(node), node, includeTrivia);
13303     }
13304     ts.getTextOfNode = getTextOfNode;
13305     function getPos(range) {
13306         return range.pos;
13307     }
13308     /**
13309      * Note: it is expected that the `nodeArray` and the `node` are within the same file.
13310      * For example, searching for a `SourceFile` in a `SourceFile[]` wouldn't work.
13311      */
13312     function indexOfNode(nodeArray, node) {
13313         return ts.binarySearch(nodeArray, node, getPos, ts.compareValues);
13314     }
13315     ts.indexOfNode = indexOfNode;
13316     /**
13317      * Gets flags that control emit behavior of a node.
13318      */
13319     function getEmitFlags(node) {
13320         var emitNode = node.emitNode;
13321         return emitNode && emitNode.flags || 0;
13322     }
13323     ts.getEmitFlags = getEmitFlags;
13324     function getLiteralText(node, sourceFile, neverAsciiEscape, jsxAttributeEscape) {
13325         // If we don't need to downlevel and we can reach the original source text using
13326         // the node's parent reference, then simply get the text as it was originally written.
13327         if (!nodeIsSynthesized(node) && node.parent && !((ts.isNumericLiteral(node) && node.numericLiteralFlags & 512 /* ContainsSeparator */) ||
13328             ts.isBigIntLiteral(node))) {
13329             return getSourceTextOfNodeFromSourceFile(sourceFile, node);
13330         }
13331         // If we can't reach the original source text, use the canonical form if it's a number,
13332         // or a (possibly escaped) quoted form of the original text if it's string-like.
13333         switch (node.kind) {
13334             case 10 /* StringLiteral */: {
13335                 var escapeText = jsxAttributeEscape ? escapeJsxAttributeString :
13336                     neverAsciiEscape || (getEmitFlags(node) & 16777216 /* NoAsciiEscaping */) ? escapeString :
13337                         escapeNonAsciiString;
13338                 if (node.singleQuote) {
13339                     return "'" + escapeText(node.text, 39 /* singleQuote */) + "'";
13340                 }
13341                 else {
13342                     return '"' + escapeText(node.text, 34 /* doubleQuote */) + '"';
13343                 }
13344             }
13345             case 14 /* NoSubstitutionTemplateLiteral */:
13346             case 15 /* TemplateHead */:
13347             case 16 /* TemplateMiddle */:
13348             case 17 /* TemplateTail */: {
13349                 // If a NoSubstitutionTemplateLiteral appears to have a substitution in it, the original text
13350                 // had to include a backslash: `not \${a} substitution`.
13351                 var escapeText = neverAsciiEscape || (getEmitFlags(node) & 16777216 /* NoAsciiEscaping */) ? escapeString :
13352                     escapeNonAsciiString;
13353                 var rawText = node.rawText || escapeTemplateSubstitution(escapeText(node.text, 96 /* backtick */));
13354                 switch (node.kind) {
13355                     case 14 /* NoSubstitutionTemplateLiteral */:
13356                         return "`" + rawText + "`";
13357                     case 15 /* TemplateHead */:
13358                         return "`" + rawText + "${";
13359                     case 16 /* TemplateMiddle */:
13360                         return "}" + rawText + "${";
13361                     case 17 /* TemplateTail */:
13362                         return "}" + rawText + "`";
13363                 }
13364                 break;
13365             }
13366             case 8 /* NumericLiteral */:
13367             case 9 /* BigIntLiteral */:
13368             case 13 /* RegularExpressionLiteral */:
13369                 return node.text;
13370         }
13371         return ts.Debug.fail("Literal kind '" + node.kind + "' not accounted for.");
13372     }
13373     ts.getLiteralText = getLiteralText;
13374     function getTextOfConstantValue(value) {
13375         return ts.isString(value) ? '"' + escapeNonAsciiString(value) + '"' : "" + value;
13376     }
13377     ts.getTextOfConstantValue = getTextOfConstantValue;
13378     // Make an identifier from an external module name by extracting the string after the last "/" and replacing
13379     // all non-alphanumeric characters with underscores
13380     function makeIdentifierFromModuleName(moduleName) {
13381         return ts.getBaseFileName(moduleName).replace(/^(\d)/, "_$1").replace(/\W/g, "_");
13382     }
13383     ts.makeIdentifierFromModuleName = makeIdentifierFromModuleName;
13384     function isBlockOrCatchScoped(declaration) {
13385         return (ts.getCombinedNodeFlags(declaration) & 3 /* BlockScoped */) !== 0 ||
13386             isCatchClauseVariableDeclarationOrBindingElement(declaration);
13387     }
13388     ts.isBlockOrCatchScoped = isBlockOrCatchScoped;
13389     function isCatchClauseVariableDeclarationOrBindingElement(declaration) {
13390         var node = getRootDeclaration(declaration);
13391         return node.kind === 242 /* VariableDeclaration */ && node.parent.kind === 280 /* CatchClause */;
13392     }
13393     ts.isCatchClauseVariableDeclarationOrBindingElement = isCatchClauseVariableDeclarationOrBindingElement;
13394     function isAmbientModule(node) {
13395         return ts.isModuleDeclaration(node) && (node.name.kind === 10 /* StringLiteral */ || isGlobalScopeAugmentation(node));
13396     }
13397     ts.isAmbientModule = isAmbientModule;
13398     function isModuleWithStringLiteralName(node) {
13399         return ts.isModuleDeclaration(node) && node.name.kind === 10 /* StringLiteral */;
13400     }
13401     ts.isModuleWithStringLiteralName = isModuleWithStringLiteralName;
13402     function isNonGlobalAmbientModule(node) {
13403         return ts.isModuleDeclaration(node) && ts.isStringLiteral(node.name);
13404     }
13405     ts.isNonGlobalAmbientModule = isNonGlobalAmbientModule;
13406     /**
13407      * An effective module (namespace) declaration is either
13408      * 1. An actual declaration: namespace X { ... }
13409      * 2. A Javascript declaration, which is:
13410      *    An identifier in a nested property access expression: Y in `X.Y.Z = { ... }`
13411      */
13412     function isEffectiveModuleDeclaration(node) {
13413         return ts.isModuleDeclaration(node) || ts.isIdentifier(node);
13414     }
13415     ts.isEffectiveModuleDeclaration = isEffectiveModuleDeclaration;
13416     /** Given a symbol for a module, checks that it is a shorthand ambient module. */
13417     function isShorthandAmbientModuleSymbol(moduleSymbol) {
13418         return isShorthandAmbientModule(moduleSymbol.valueDeclaration);
13419     }
13420     ts.isShorthandAmbientModuleSymbol = isShorthandAmbientModuleSymbol;
13421     function isShorthandAmbientModule(node) {
13422         // The only kind of module that can be missing a body is a shorthand ambient module.
13423         return node && node.kind === 249 /* ModuleDeclaration */ && (!node.body);
13424     }
13425     function isBlockScopedContainerTopLevel(node) {
13426         return node.kind === 290 /* SourceFile */ ||
13427             node.kind === 249 /* ModuleDeclaration */ ||
13428             ts.isFunctionLike(node);
13429     }
13430     ts.isBlockScopedContainerTopLevel = isBlockScopedContainerTopLevel;
13431     function isGlobalScopeAugmentation(module) {
13432         return !!(module.flags & 1024 /* GlobalAugmentation */);
13433     }
13434     ts.isGlobalScopeAugmentation = isGlobalScopeAugmentation;
13435     function isExternalModuleAugmentation(node) {
13436         return isAmbientModule(node) && isModuleAugmentationExternal(node);
13437     }
13438     ts.isExternalModuleAugmentation = isExternalModuleAugmentation;
13439     function isModuleAugmentationExternal(node) {
13440         // external module augmentation is a ambient module declaration that is either:
13441         // - defined in the top level scope and source file is an external module
13442         // - defined inside ambient module declaration located in the top level scope and source file not an external module
13443         switch (node.parent.kind) {
13444             case 290 /* SourceFile */:
13445                 return ts.isExternalModule(node.parent);
13446             case 250 /* ModuleBlock */:
13447                 return isAmbientModule(node.parent.parent) && ts.isSourceFile(node.parent.parent.parent) && !ts.isExternalModule(node.parent.parent.parent);
13448         }
13449         return false;
13450     }
13451     ts.isModuleAugmentationExternal = isModuleAugmentationExternal;
13452     function getNonAugmentationDeclaration(symbol) {
13453         return ts.find(symbol.declarations, function (d) { return !isExternalModuleAugmentation(d) && !(ts.isModuleDeclaration(d) && isGlobalScopeAugmentation(d)); });
13454     }
13455     ts.getNonAugmentationDeclaration = getNonAugmentationDeclaration;
13456     function isEffectiveExternalModule(node, compilerOptions) {
13457         return ts.isExternalModule(node) || compilerOptions.isolatedModules || ((getEmitModuleKind(compilerOptions) === ts.ModuleKind.CommonJS) && !!node.commonJsModuleIndicator);
13458     }
13459     ts.isEffectiveExternalModule = isEffectiveExternalModule;
13460     /**
13461      * Returns whether the source file will be treated as if it were in strict mode at runtime.
13462      */
13463     function isEffectiveStrictModeSourceFile(node, compilerOptions) {
13464         // We can only verify strict mode for JS/TS files
13465         switch (node.scriptKind) {
13466             case 1 /* JS */:
13467             case 3 /* TS */:
13468             case 2 /* JSX */:
13469             case 4 /* TSX */:
13470                 break;
13471             default:
13472                 return false;
13473         }
13474         // Strict mode does not matter for declaration files.
13475         if (node.isDeclarationFile) {
13476             return false;
13477         }
13478         // If `alwaysStrict` is set, then treat the file as strict.
13479         if (getStrictOptionValue(compilerOptions, "alwaysStrict")) {
13480             return true;
13481         }
13482         // Starting with a "use strict" directive indicates the file is strict.
13483         if (ts.startsWithUseStrict(node.statements)) {
13484             return true;
13485         }
13486         if (ts.isExternalModule(node) || compilerOptions.isolatedModules) {
13487             // ECMAScript Modules are always strict.
13488             if (getEmitModuleKind(compilerOptions) >= ts.ModuleKind.ES2015) {
13489                 return true;
13490             }
13491             // Other modules are strict unless otherwise specified.
13492             return !compilerOptions.noImplicitUseStrict;
13493         }
13494         return false;
13495     }
13496     ts.isEffectiveStrictModeSourceFile = isEffectiveStrictModeSourceFile;
13497     function isBlockScope(node, parentNode) {
13498         switch (node.kind) {
13499             case 290 /* SourceFile */:
13500             case 251 /* CaseBlock */:
13501             case 280 /* CatchClause */:
13502             case 249 /* ModuleDeclaration */:
13503             case 230 /* ForStatement */:
13504             case 231 /* ForInStatement */:
13505             case 232 /* ForOfStatement */:
13506             case 162 /* Constructor */:
13507             case 161 /* MethodDeclaration */:
13508             case 163 /* GetAccessor */:
13509             case 164 /* SetAccessor */:
13510             case 244 /* FunctionDeclaration */:
13511             case 201 /* FunctionExpression */:
13512             case 202 /* ArrowFunction */:
13513                 return true;
13514             case 223 /* Block */:
13515                 // function block is not considered block-scope container
13516                 // see comment in binder.ts: bind(...), case for SyntaxKind.Block
13517                 return !ts.isFunctionLike(parentNode);
13518         }
13519         return false;
13520     }
13521     ts.isBlockScope = isBlockScope;
13522     function isDeclarationWithTypeParameters(node) {
13523         switch (node.kind) {
13524             case 315 /* JSDocCallbackTag */:
13525             case 322 /* JSDocTypedefTag */:
13526             case 305 /* JSDocSignature */:
13527                 return true;
13528             default:
13529                 ts.assertType(node);
13530                 return isDeclarationWithTypeParameterChildren(node);
13531         }
13532     }
13533     ts.isDeclarationWithTypeParameters = isDeclarationWithTypeParameters;
13534     function isDeclarationWithTypeParameterChildren(node) {
13535         switch (node.kind) {
13536             case 165 /* CallSignature */:
13537             case 166 /* ConstructSignature */:
13538             case 160 /* MethodSignature */:
13539             case 167 /* IndexSignature */:
13540             case 170 /* FunctionType */:
13541             case 171 /* ConstructorType */:
13542             case 300 /* JSDocFunctionType */:
13543             case 245 /* ClassDeclaration */:
13544             case 214 /* ClassExpression */:
13545             case 246 /* InterfaceDeclaration */:
13546             case 247 /* TypeAliasDeclaration */:
13547             case 321 /* JSDocTemplateTag */:
13548             case 244 /* FunctionDeclaration */:
13549             case 161 /* MethodDeclaration */:
13550             case 162 /* Constructor */:
13551             case 163 /* GetAccessor */:
13552             case 164 /* SetAccessor */:
13553             case 201 /* FunctionExpression */:
13554             case 202 /* ArrowFunction */:
13555                 return true;
13556             default:
13557                 ts.assertType(node);
13558                 return false;
13559         }
13560     }
13561     ts.isDeclarationWithTypeParameterChildren = isDeclarationWithTypeParameterChildren;
13562     function isAnyImportSyntax(node) {
13563         switch (node.kind) {
13564             case 254 /* ImportDeclaration */:
13565             case 253 /* ImportEqualsDeclaration */:
13566                 return true;
13567             default:
13568                 return false;
13569         }
13570     }
13571     ts.isAnyImportSyntax = isAnyImportSyntax;
13572     function isLateVisibilityPaintedStatement(node) {
13573         switch (node.kind) {
13574             case 254 /* ImportDeclaration */:
13575             case 253 /* ImportEqualsDeclaration */:
13576             case 225 /* VariableStatement */:
13577             case 245 /* ClassDeclaration */:
13578             case 244 /* FunctionDeclaration */:
13579             case 249 /* ModuleDeclaration */:
13580             case 247 /* TypeAliasDeclaration */:
13581             case 246 /* InterfaceDeclaration */:
13582             case 248 /* EnumDeclaration */:
13583                 return true;
13584             default:
13585                 return false;
13586         }
13587     }
13588     ts.isLateVisibilityPaintedStatement = isLateVisibilityPaintedStatement;
13589     function isAnyImportOrReExport(node) {
13590         return isAnyImportSyntax(node) || ts.isExportDeclaration(node);
13591     }
13592     ts.isAnyImportOrReExport = isAnyImportOrReExport;
13593     // Gets the nearest enclosing block scope container that has the provided node
13594     // as a descendant, that is not the provided node.
13595     function getEnclosingBlockScopeContainer(node) {
13596         return findAncestor(node.parent, function (current) { return isBlockScope(current, current.parent); });
13597     }
13598     ts.getEnclosingBlockScopeContainer = getEnclosingBlockScopeContainer;
13599     // Return display name of an identifier
13600     // Computed property names will just be emitted as "[<expr>]", where <expr> is the source
13601     // text of the expression in the computed property.
13602     function declarationNameToString(name) {
13603         return !name || getFullWidth(name) === 0 ? "(Missing)" : getTextOfNode(name);
13604     }
13605     ts.declarationNameToString = declarationNameToString;
13606     function getNameFromIndexInfo(info) {
13607         return info.declaration ? declarationNameToString(info.declaration.parameters[0].name) : undefined;
13608     }
13609     ts.getNameFromIndexInfo = getNameFromIndexInfo;
13610     function isComputedNonLiteralName(name) {
13611         return name.kind === 154 /* ComputedPropertyName */ && !isStringOrNumericLiteralLike(name.expression);
13612     }
13613     ts.isComputedNonLiteralName = isComputedNonLiteralName;
13614     function getTextOfPropertyName(name) {
13615         switch (name.kind) {
13616             case 75 /* Identifier */:
13617             case 76 /* PrivateIdentifier */:
13618                 return name.escapedText;
13619             case 10 /* StringLiteral */:
13620             case 8 /* NumericLiteral */:
13621             case 14 /* NoSubstitutionTemplateLiteral */:
13622                 return ts.escapeLeadingUnderscores(name.text);
13623             case 154 /* ComputedPropertyName */:
13624                 if (isStringOrNumericLiteralLike(name.expression))
13625                     return ts.escapeLeadingUnderscores(name.expression.text);
13626                 return ts.Debug.fail("Text of property name cannot be read from non-literal-valued ComputedPropertyNames");
13627             default:
13628                 return ts.Debug.assertNever(name);
13629         }
13630     }
13631     ts.getTextOfPropertyName = getTextOfPropertyName;
13632     function entityNameToString(name) {
13633         switch (name.kind) {
13634             case 104 /* ThisKeyword */:
13635                 return "this";
13636             case 76 /* PrivateIdentifier */:
13637             case 75 /* Identifier */:
13638                 return getFullWidth(name) === 0 ? ts.idText(name) : getTextOfNode(name);
13639             case 153 /* QualifiedName */:
13640                 return entityNameToString(name.left) + "." + entityNameToString(name.right);
13641             case 194 /* PropertyAccessExpression */:
13642                 if (ts.isIdentifier(name.name) || ts.isPrivateIdentifier(name.name)) {
13643                     return entityNameToString(name.expression) + "." + entityNameToString(name.name);
13644                 }
13645                 else {
13646                     return ts.Debug.assertNever(name.name);
13647                 }
13648             default:
13649                 return ts.Debug.assertNever(name);
13650         }
13651     }
13652     ts.entityNameToString = entityNameToString;
13653     function createDiagnosticForNode(node, message, arg0, arg1, arg2, arg3) {
13654         var sourceFile = getSourceFileOfNode(node);
13655         return createDiagnosticForNodeInSourceFile(sourceFile, node, message, arg0, arg1, arg2, arg3);
13656     }
13657     ts.createDiagnosticForNode = createDiagnosticForNode;
13658     function createDiagnosticForNodeArray(sourceFile, nodes, message, arg0, arg1, arg2, arg3) {
13659         var start = ts.skipTrivia(sourceFile.text, nodes.pos);
13660         return createFileDiagnostic(sourceFile, start, nodes.end - start, message, arg0, arg1, arg2, arg3);
13661     }
13662     ts.createDiagnosticForNodeArray = createDiagnosticForNodeArray;
13663     function createDiagnosticForNodeInSourceFile(sourceFile, node, message, arg0, arg1, arg2, arg3) {
13664         var span = getErrorSpanForNode(sourceFile, node);
13665         return createFileDiagnostic(sourceFile, span.start, span.length, message, arg0, arg1, arg2, arg3);
13666     }
13667     ts.createDiagnosticForNodeInSourceFile = createDiagnosticForNodeInSourceFile;
13668     function createDiagnosticForNodeFromMessageChain(node, messageChain, relatedInformation) {
13669         var sourceFile = getSourceFileOfNode(node);
13670         var span = getErrorSpanForNode(sourceFile, node);
13671         return {
13672             file: sourceFile,
13673             start: span.start,
13674             length: span.length,
13675             code: messageChain.code,
13676             category: messageChain.category,
13677             messageText: messageChain.next ? messageChain : messageChain.messageText,
13678             relatedInformation: relatedInformation
13679         };
13680     }
13681     ts.createDiagnosticForNodeFromMessageChain = createDiagnosticForNodeFromMessageChain;
13682     function createDiagnosticForRange(sourceFile, range, message) {
13683         return {
13684             file: sourceFile,
13685             start: range.pos,
13686             length: range.end - range.pos,
13687             code: message.code,
13688             category: message.category,
13689             messageText: message.message,
13690         };
13691     }
13692     ts.createDiagnosticForRange = createDiagnosticForRange;
13693     function getSpanOfTokenAtPosition(sourceFile, pos) {
13694         var scanner = ts.createScanner(sourceFile.languageVersion, /*skipTrivia*/ true, sourceFile.languageVariant, sourceFile.text, /*onError:*/ undefined, pos);
13695         scanner.scan();
13696         var start = scanner.getTokenPos();
13697         return ts.createTextSpanFromBounds(start, scanner.getTextPos());
13698     }
13699     ts.getSpanOfTokenAtPosition = getSpanOfTokenAtPosition;
13700     function getErrorSpanForArrowFunction(sourceFile, node) {
13701         var pos = ts.skipTrivia(sourceFile.text, node.pos);
13702         if (node.body && node.body.kind === 223 /* Block */) {
13703             var startLine = ts.getLineAndCharacterOfPosition(sourceFile, node.body.pos).line;
13704             var endLine = ts.getLineAndCharacterOfPosition(sourceFile, node.body.end).line;
13705             if (startLine < endLine) {
13706                 // The arrow function spans multiple lines,
13707                 // make the error span be the first line, inclusive.
13708                 return ts.createTextSpan(pos, getEndLinePosition(startLine, sourceFile) - pos + 1);
13709             }
13710         }
13711         return ts.createTextSpanFromBounds(pos, node.end);
13712     }
13713     function getErrorSpanForNode(sourceFile, node) {
13714         var errorNode = node;
13715         switch (node.kind) {
13716             case 290 /* SourceFile */:
13717                 var pos_1 = ts.skipTrivia(sourceFile.text, 0, /*stopAfterLineBreak*/ false);
13718                 if (pos_1 === sourceFile.text.length) {
13719                     // file is empty - return span for the beginning of the file
13720                     return ts.createTextSpan(0, 0);
13721                 }
13722                 return getSpanOfTokenAtPosition(sourceFile, pos_1);
13723             // This list is a work in progress. Add missing node kinds to improve their error
13724             // spans.
13725             case 242 /* VariableDeclaration */:
13726             case 191 /* BindingElement */:
13727             case 245 /* ClassDeclaration */:
13728             case 214 /* ClassExpression */:
13729             case 246 /* InterfaceDeclaration */:
13730             case 249 /* ModuleDeclaration */:
13731             case 248 /* EnumDeclaration */:
13732             case 284 /* EnumMember */:
13733             case 244 /* FunctionDeclaration */:
13734             case 201 /* FunctionExpression */:
13735             case 161 /* MethodDeclaration */:
13736             case 163 /* GetAccessor */:
13737             case 164 /* SetAccessor */:
13738             case 247 /* TypeAliasDeclaration */:
13739             case 159 /* PropertyDeclaration */:
13740             case 158 /* PropertySignature */:
13741                 errorNode = node.name;
13742                 break;
13743             case 202 /* ArrowFunction */:
13744                 return getErrorSpanForArrowFunction(sourceFile, node);
13745             case 277 /* CaseClause */:
13746             case 278 /* DefaultClause */:
13747                 var start = ts.skipTrivia(sourceFile.text, node.pos);
13748                 var end = node.statements.length > 0 ? node.statements[0].pos : node.end;
13749                 return ts.createTextSpanFromBounds(start, end);
13750         }
13751         if (errorNode === undefined) {
13752             // If we don't have a better node, then just set the error on the first token of
13753             // construct.
13754             return getSpanOfTokenAtPosition(sourceFile, node.pos);
13755         }
13756         ts.Debug.assert(!ts.isJSDoc(errorNode));
13757         var isMissing = nodeIsMissing(errorNode);
13758         var pos = isMissing || ts.isJsxText(node)
13759             ? errorNode.pos
13760             : ts.skipTrivia(sourceFile.text, errorNode.pos);
13761         // These asserts should all be satisfied for a properly constructed `errorNode`.
13762         if (isMissing) {
13763             ts.Debug.assert(pos === errorNode.pos, "This failure could trigger https://github.com/Microsoft/TypeScript/issues/20809");
13764             ts.Debug.assert(pos === errorNode.end, "This failure could trigger https://github.com/Microsoft/TypeScript/issues/20809");
13765         }
13766         else {
13767             ts.Debug.assert(pos >= errorNode.pos, "This failure could trigger https://github.com/Microsoft/TypeScript/issues/20809");
13768             ts.Debug.assert(pos <= errorNode.end, "This failure could trigger https://github.com/Microsoft/TypeScript/issues/20809");
13769         }
13770         return ts.createTextSpanFromBounds(pos, errorNode.end);
13771     }
13772     ts.getErrorSpanForNode = getErrorSpanForNode;
13773     function isExternalOrCommonJsModule(file) {
13774         return (file.externalModuleIndicator || file.commonJsModuleIndicator) !== undefined;
13775     }
13776     ts.isExternalOrCommonJsModule = isExternalOrCommonJsModule;
13777     function isJsonSourceFile(file) {
13778         return file.scriptKind === 6 /* JSON */;
13779     }
13780     ts.isJsonSourceFile = isJsonSourceFile;
13781     function isEnumConst(node) {
13782         return !!(ts.getCombinedModifierFlags(node) & 2048 /* Const */);
13783     }
13784     ts.isEnumConst = isEnumConst;
13785     function isDeclarationReadonly(declaration) {
13786         return !!(ts.getCombinedModifierFlags(declaration) & 64 /* Readonly */ && !ts.isParameterPropertyDeclaration(declaration, declaration.parent));
13787     }
13788     ts.isDeclarationReadonly = isDeclarationReadonly;
13789     function isVarConst(node) {
13790         return !!(ts.getCombinedNodeFlags(node) & 2 /* Const */);
13791     }
13792     ts.isVarConst = isVarConst;
13793     function isLet(node) {
13794         return !!(ts.getCombinedNodeFlags(node) & 1 /* Let */);
13795     }
13796     ts.isLet = isLet;
13797     function isSuperCall(n) {
13798         return n.kind === 196 /* CallExpression */ && n.expression.kind === 102 /* SuperKeyword */;
13799     }
13800     ts.isSuperCall = isSuperCall;
13801     function isImportCall(n) {
13802         return n.kind === 196 /* CallExpression */ && n.expression.kind === 96 /* ImportKeyword */;
13803     }
13804     ts.isImportCall = isImportCall;
13805     function isImportMeta(n) {
13806         return ts.isMetaProperty(n)
13807             && n.keywordToken === 96 /* ImportKeyword */
13808             && n.name.escapedText === "meta";
13809     }
13810     ts.isImportMeta = isImportMeta;
13811     function isLiteralImportTypeNode(n) {
13812         return ts.isImportTypeNode(n) && ts.isLiteralTypeNode(n.argument) && ts.isStringLiteral(n.argument.literal);
13813     }
13814     ts.isLiteralImportTypeNode = isLiteralImportTypeNode;
13815     function isPrologueDirective(node) {
13816         return node.kind === 226 /* ExpressionStatement */
13817             && node.expression.kind === 10 /* StringLiteral */;
13818     }
13819     ts.isPrologueDirective = isPrologueDirective;
13820     function isCustomPrologue(node) {
13821         return !!(getEmitFlags(node) & 1048576 /* CustomPrologue */);
13822     }
13823     ts.isCustomPrologue = isCustomPrologue;
13824     function isHoistedFunction(node) {
13825         return isCustomPrologue(node)
13826             && ts.isFunctionDeclaration(node);
13827     }
13828     ts.isHoistedFunction = isHoistedFunction;
13829     function isHoistedVariable(node) {
13830         return ts.isIdentifier(node.name)
13831             && !node.initializer;
13832     }
13833     function isHoistedVariableStatement(node) {
13834         return isCustomPrologue(node)
13835             && ts.isVariableStatement(node)
13836             && ts.every(node.declarationList.declarations, isHoistedVariable);
13837     }
13838     ts.isHoistedVariableStatement = isHoistedVariableStatement;
13839     function getLeadingCommentRangesOfNode(node, sourceFileOfNode) {
13840         return node.kind !== 11 /* JsxText */ ? ts.getLeadingCommentRanges(sourceFileOfNode.text, node.pos) : undefined;
13841     }
13842     ts.getLeadingCommentRangesOfNode = getLeadingCommentRangesOfNode;
13843     function getJSDocCommentRanges(node, text) {
13844         var commentRanges = (node.kind === 156 /* Parameter */ ||
13845             node.kind === 155 /* TypeParameter */ ||
13846             node.kind === 201 /* FunctionExpression */ ||
13847             node.kind === 202 /* ArrowFunction */ ||
13848             node.kind === 200 /* ParenthesizedExpression */) ?
13849             ts.concatenate(ts.getTrailingCommentRanges(text, node.pos), ts.getLeadingCommentRanges(text, node.pos)) :
13850             ts.getLeadingCommentRanges(text, node.pos);
13851         // True if the comment starts with '/**' but not if it is '/**/'
13852         return ts.filter(commentRanges, function (comment) {
13853             return text.charCodeAt(comment.pos + 1) === 42 /* asterisk */ &&
13854                 text.charCodeAt(comment.pos + 2) === 42 /* asterisk */ &&
13855                 text.charCodeAt(comment.pos + 3) !== 47 /* slash */;
13856         });
13857     }
13858     ts.getJSDocCommentRanges = getJSDocCommentRanges;
13859     ts.fullTripleSlashReferencePathRegEx = /^(\/\/\/\s*<reference\s+path\s*=\s*)('|")(.+?)\2.*?\/>/;
13860     var fullTripleSlashReferenceTypeReferenceDirectiveRegEx = /^(\/\/\/\s*<reference\s+types\s*=\s*)('|")(.+?)\2.*?\/>/;
13861     ts.fullTripleSlashAMDReferencePathRegEx = /^(\/\/\/\s*<amd-dependency\s+path\s*=\s*)('|")(.+?)\2.*?\/>/;
13862     var defaultLibReferenceRegEx = /^(\/\/\/\s*<reference\s+no-default-lib\s*=\s*)('|")(.+?)\2\s*\/>/;
13863     function isPartOfTypeNode(node) {
13864         if (168 /* FirstTypeNode */ <= node.kind && node.kind <= 188 /* LastTypeNode */) {
13865             return true;
13866         }
13867         switch (node.kind) {
13868             case 125 /* AnyKeyword */:
13869             case 148 /* UnknownKeyword */:
13870             case 140 /* NumberKeyword */:
13871             case 151 /* BigIntKeyword */:
13872             case 143 /* StringKeyword */:
13873             case 128 /* BooleanKeyword */:
13874             case 144 /* SymbolKeyword */:
13875             case 141 /* ObjectKeyword */:
13876             case 146 /* UndefinedKeyword */:
13877             case 137 /* NeverKeyword */:
13878                 return true;
13879             case 110 /* VoidKeyword */:
13880                 return node.parent.kind !== 205 /* VoidExpression */;
13881             case 216 /* ExpressionWithTypeArguments */:
13882                 return !isExpressionWithTypeArgumentsInClassExtendsClause(node);
13883             case 155 /* TypeParameter */:
13884                 return node.parent.kind === 186 /* MappedType */ || node.parent.kind === 181 /* InferType */;
13885             // Identifiers and qualified names may be type nodes, depending on their context. Climb
13886             // above them to find the lowest container
13887             case 75 /* Identifier */:
13888                 // If the identifier is the RHS of a qualified name, then it's a type iff its parent is.
13889                 if (node.parent.kind === 153 /* QualifiedName */ && node.parent.right === node) {
13890                     node = node.parent;
13891                 }
13892                 else if (node.parent.kind === 194 /* PropertyAccessExpression */ && node.parent.name === node) {
13893                     node = node.parent;
13894                 }
13895                 // At this point, node is either a qualified name or an identifier
13896                 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'.");
13897             // falls through
13898             case 153 /* QualifiedName */:
13899             case 194 /* PropertyAccessExpression */:
13900             case 104 /* ThisKeyword */: {
13901                 var parent = node.parent;
13902                 if (parent.kind === 172 /* TypeQuery */) {
13903                     return false;
13904                 }
13905                 if (parent.kind === 188 /* ImportType */) {
13906                     return !parent.isTypeOf;
13907                 }
13908                 // Do not recursively call isPartOfTypeNode on the parent. In the example:
13909                 //
13910                 //     let a: A.B.C;
13911                 //
13912                 // Calling isPartOfTypeNode would consider the qualified name A.B a type node.
13913                 // Only C and A.B.C are type nodes.
13914                 if (168 /* FirstTypeNode */ <= parent.kind && parent.kind <= 188 /* LastTypeNode */) {
13915                     return true;
13916                 }
13917                 switch (parent.kind) {
13918                     case 216 /* ExpressionWithTypeArguments */:
13919                         return !isExpressionWithTypeArgumentsInClassExtendsClause(parent);
13920                     case 155 /* TypeParameter */:
13921                         return node === parent.constraint;
13922                     case 321 /* JSDocTemplateTag */:
13923                         return node === parent.constraint;
13924                     case 159 /* PropertyDeclaration */:
13925                     case 158 /* PropertySignature */:
13926                     case 156 /* Parameter */:
13927                     case 242 /* VariableDeclaration */:
13928                         return node === parent.type;
13929                     case 244 /* FunctionDeclaration */:
13930                     case 201 /* FunctionExpression */:
13931                     case 202 /* ArrowFunction */:
13932                     case 162 /* Constructor */:
13933                     case 161 /* MethodDeclaration */:
13934                     case 160 /* MethodSignature */:
13935                     case 163 /* GetAccessor */:
13936                     case 164 /* SetAccessor */:
13937                         return node === parent.type;
13938                     case 165 /* CallSignature */:
13939                     case 166 /* ConstructSignature */:
13940                     case 167 /* IndexSignature */:
13941                         return node === parent.type;
13942                     case 199 /* TypeAssertionExpression */:
13943                         return node === parent.type;
13944                     case 196 /* CallExpression */:
13945                     case 197 /* NewExpression */:
13946                         return ts.contains(parent.typeArguments, node);
13947                     case 198 /* TaggedTemplateExpression */:
13948                         // TODO (drosen): TaggedTemplateExpressions may eventually support type arguments.
13949                         return false;
13950                 }
13951             }
13952         }
13953         return false;
13954     }
13955     ts.isPartOfTypeNode = isPartOfTypeNode;
13956     function isChildOfNodeWithKind(node, kind) {
13957         while (node) {
13958             if (node.kind === kind) {
13959                 return true;
13960             }
13961             node = node.parent;
13962         }
13963         return false;
13964     }
13965     ts.isChildOfNodeWithKind = isChildOfNodeWithKind;
13966     // Warning: This has the same semantics as the forEach family of functions,
13967     //          in that traversal terminates in the event that 'visitor' supplies a truthy value.
13968     function forEachReturnStatement(body, visitor) {
13969         return traverse(body);
13970         function traverse(node) {
13971             switch (node.kind) {
13972                 case 235 /* ReturnStatement */:
13973                     return visitor(node);
13974                 case 251 /* CaseBlock */:
13975                 case 223 /* Block */:
13976                 case 227 /* IfStatement */:
13977                 case 228 /* DoStatement */:
13978                 case 229 /* WhileStatement */:
13979                 case 230 /* ForStatement */:
13980                 case 231 /* ForInStatement */:
13981                 case 232 /* ForOfStatement */:
13982                 case 236 /* WithStatement */:
13983                 case 237 /* SwitchStatement */:
13984                 case 277 /* CaseClause */:
13985                 case 278 /* DefaultClause */:
13986                 case 238 /* LabeledStatement */:
13987                 case 240 /* TryStatement */:
13988                 case 280 /* CatchClause */:
13989                     return ts.forEachChild(node, traverse);
13990             }
13991         }
13992     }
13993     ts.forEachReturnStatement = forEachReturnStatement;
13994     function forEachYieldExpression(body, visitor) {
13995         return traverse(body);
13996         function traverse(node) {
13997             switch (node.kind) {
13998                 case 212 /* YieldExpression */:
13999                     visitor(node);
14000                     var operand = node.expression;
14001                     if (operand) {
14002                         traverse(operand);
14003                     }
14004                     return;
14005                 case 248 /* EnumDeclaration */:
14006                 case 246 /* InterfaceDeclaration */:
14007                 case 249 /* ModuleDeclaration */:
14008                 case 247 /* TypeAliasDeclaration */:
14009                     // These are not allowed inside a generator now, but eventually they may be allowed
14010                     // as local types. Regardless, skip them to avoid the work.
14011                     return;
14012                 default:
14013                     if (ts.isFunctionLike(node)) {
14014                         if (node.name && node.name.kind === 154 /* ComputedPropertyName */) {
14015                             // Note that we will not include methods/accessors of a class because they would require
14016                             // first descending into the class. This is by design.
14017                             traverse(node.name.expression);
14018                             return;
14019                         }
14020                     }
14021                     else if (!isPartOfTypeNode(node)) {
14022                         // This is the general case, which should include mostly expressions and statements.
14023                         // Also includes NodeArrays.
14024                         ts.forEachChild(node, traverse);
14025                     }
14026             }
14027         }
14028     }
14029     ts.forEachYieldExpression = forEachYieldExpression;
14030     /**
14031      * Gets the most likely element type for a TypeNode. This is not an exhaustive test
14032      * as it assumes a rest argument can only be an array type (either T[], or Array<T>).
14033      *
14034      * @param node The type node.
14035      */
14036     function getRestParameterElementType(node) {
14037         if (node && node.kind === 174 /* ArrayType */) {
14038             return node.elementType;
14039         }
14040         else if (node && node.kind === 169 /* TypeReference */) {
14041             return ts.singleOrUndefined(node.typeArguments);
14042         }
14043         else {
14044             return undefined;
14045         }
14046     }
14047     ts.getRestParameterElementType = getRestParameterElementType;
14048     function getMembersOfDeclaration(node) {
14049         switch (node.kind) {
14050             case 246 /* InterfaceDeclaration */:
14051             case 245 /* ClassDeclaration */:
14052             case 214 /* ClassExpression */:
14053             case 173 /* TypeLiteral */:
14054                 return node.members;
14055             case 193 /* ObjectLiteralExpression */:
14056                 return node.properties;
14057         }
14058     }
14059     ts.getMembersOfDeclaration = getMembersOfDeclaration;
14060     function isVariableLike(node) {
14061         if (node) {
14062             switch (node.kind) {
14063                 case 191 /* BindingElement */:
14064                 case 284 /* EnumMember */:
14065                 case 156 /* Parameter */:
14066                 case 281 /* PropertyAssignment */:
14067                 case 159 /* PropertyDeclaration */:
14068                 case 158 /* PropertySignature */:
14069                 case 282 /* ShorthandPropertyAssignment */:
14070                 case 242 /* VariableDeclaration */:
14071                     return true;
14072             }
14073         }
14074         return false;
14075     }
14076     ts.isVariableLike = isVariableLike;
14077     function isVariableLikeOrAccessor(node) {
14078         return isVariableLike(node) || ts.isAccessor(node);
14079     }
14080     ts.isVariableLikeOrAccessor = isVariableLikeOrAccessor;
14081     function isVariableDeclarationInVariableStatement(node) {
14082         return node.parent.kind === 243 /* VariableDeclarationList */
14083             && node.parent.parent.kind === 225 /* VariableStatement */;
14084     }
14085     ts.isVariableDeclarationInVariableStatement = isVariableDeclarationInVariableStatement;
14086     function isValidESSymbolDeclaration(node) {
14087         return ts.isVariableDeclaration(node) ? isVarConst(node) && ts.isIdentifier(node.name) && isVariableDeclarationInVariableStatement(node) :
14088             ts.isPropertyDeclaration(node) ? hasReadonlyModifier(node) && hasStaticModifier(node) :
14089                 ts.isPropertySignature(node) && hasReadonlyModifier(node);
14090     }
14091     ts.isValidESSymbolDeclaration = isValidESSymbolDeclaration;
14092     function introducesArgumentsExoticObject(node) {
14093         switch (node.kind) {
14094             case 161 /* MethodDeclaration */:
14095             case 160 /* MethodSignature */:
14096             case 162 /* Constructor */:
14097             case 163 /* GetAccessor */:
14098             case 164 /* SetAccessor */:
14099             case 244 /* FunctionDeclaration */:
14100             case 201 /* FunctionExpression */:
14101                 return true;
14102         }
14103         return false;
14104     }
14105     ts.introducesArgumentsExoticObject = introducesArgumentsExoticObject;
14106     function unwrapInnermostStatementOfLabel(node, beforeUnwrapLabelCallback) {
14107         while (true) {
14108             if (beforeUnwrapLabelCallback) {
14109                 beforeUnwrapLabelCallback(node);
14110             }
14111             if (node.statement.kind !== 238 /* LabeledStatement */) {
14112                 return node.statement;
14113             }
14114             node = node.statement;
14115         }
14116     }
14117     ts.unwrapInnermostStatementOfLabel = unwrapInnermostStatementOfLabel;
14118     function isFunctionBlock(node) {
14119         return node && node.kind === 223 /* Block */ && ts.isFunctionLike(node.parent);
14120     }
14121     ts.isFunctionBlock = isFunctionBlock;
14122     function isObjectLiteralMethod(node) {
14123         return node && node.kind === 161 /* MethodDeclaration */ && node.parent.kind === 193 /* ObjectLiteralExpression */;
14124     }
14125     ts.isObjectLiteralMethod = isObjectLiteralMethod;
14126     function isObjectLiteralOrClassExpressionMethod(node) {
14127         return node.kind === 161 /* MethodDeclaration */ &&
14128             (node.parent.kind === 193 /* ObjectLiteralExpression */ ||
14129                 node.parent.kind === 214 /* ClassExpression */);
14130     }
14131     ts.isObjectLiteralOrClassExpressionMethod = isObjectLiteralOrClassExpressionMethod;
14132     function isIdentifierTypePredicate(predicate) {
14133         return predicate && predicate.kind === 1 /* Identifier */;
14134     }
14135     ts.isIdentifierTypePredicate = isIdentifierTypePredicate;
14136     function isThisTypePredicate(predicate) {
14137         return predicate && predicate.kind === 0 /* This */;
14138     }
14139     ts.isThisTypePredicate = isThisTypePredicate;
14140     function getPropertyAssignment(objectLiteral, key, key2) {
14141         return objectLiteral.properties.filter(function (property) {
14142             if (property.kind === 281 /* PropertyAssignment */) {
14143                 var propName = getTextOfPropertyName(property.name);
14144                 return key === propName || (!!key2 && key2 === propName);
14145             }
14146             return false;
14147         });
14148     }
14149     ts.getPropertyAssignment = getPropertyAssignment;
14150     function getTsConfigObjectLiteralExpression(tsConfigSourceFile) {
14151         if (tsConfigSourceFile && tsConfigSourceFile.statements.length) {
14152             var expression = tsConfigSourceFile.statements[0].expression;
14153             return ts.tryCast(expression, ts.isObjectLiteralExpression);
14154         }
14155     }
14156     ts.getTsConfigObjectLiteralExpression = getTsConfigObjectLiteralExpression;
14157     function getTsConfigPropArrayElementValue(tsConfigSourceFile, propKey, elementValue) {
14158         return ts.firstDefined(getTsConfigPropArray(tsConfigSourceFile, propKey), function (property) {
14159             return ts.isArrayLiteralExpression(property.initializer) ?
14160                 ts.find(property.initializer.elements, function (element) { return ts.isStringLiteral(element) && element.text === elementValue; }) :
14161                 undefined;
14162         });
14163     }
14164     ts.getTsConfigPropArrayElementValue = getTsConfigPropArrayElementValue;
14165     function getTsConfigPropArray(tsConfigSourceFile, propKey) {
14166         var jsonObjectLiteral = getTsConfigObjectLiteralExpression(tsConfigSourceFile);
14167         return jsonObjectLiteral ? getPropertyAssignment(jsonObjectLiteral, propKey) : ts.emptyArray;
14168     }
14169     ts.getTsConfigPropArray = getTsConfigPropArray;
14170     function getContainingFunction(node) {
14171         return findAncestor(node.parent, ts.isFunctionLike);
14172     }
14173     ts.getContainingFunction = getContainingFunction;
14174     function getContainingFunctionDeclaration(node) {
14175         return findAncestor(node.parent, ts.isFunctionLikeDeclaration);
14176     }
14177     ts.getContainingFunctionDeclaration = getContainingFunctionDeclaration;
14178     function getContainingClass(node) {
14179         return findAncestor(node.parent, ts.isClassLike);
14180     }
14181     ts.getContainingClass = getContainingClass;
14182     function getThisContainer(node, includeArrowFunctions) {
14183         ts.Debug.assert(node.kind !== 290 /* SourceFile */);
14184         while (true) {
14185             node = node.parent;
14186             if (!node) {
14187                 return ts.Debug.fail(); // If we never pass in a SourceFile, this should be unreachable, since we'll stop when we reach that.
14188             }
14189             switch (node.kind) {
14190                 case 154 /* ComputedPropertyName */:
14191                     // If the grandparent node is an object literal (as opposed to a class),
14192                     // then the computed property is not a 'this' container.
14193                     // A computed property name in a class needs to be a this container
14194                     // so that we can error on it.
14195                     if (ts.isClassLike(node.parent.parent)) {
14196                         return node;
14197                     }
14198                     // If this is a computed property, then the parent should not
14199                     // make it a this container. The parent might be a property
14200                     // in an object literal, like a method or accessor. But in order for
14201                     // such a parent to be a this container, the reference must be in
14202                     // the *body* of the container.
14203                     node = node.parent;
14204                     break;
14205                 case 157 /* Decorator */:
14206                     // Decorators are always applied outside of the body of a class or method.
14207                     if (node.parent.kind === 156 /* Parameter */ && ts.isClassElement(node.parent.parent)) {
14208                         // If the decorator's parent is a Parameter, we resolve the this container from
14209                         // the grandparent class declaration.
14210                         node = node.parent.parent;
14211                     }
14212                     else if (ts.isClassElement(node.parent)) {
14213                         // If the decorator's parent is a class element, we resolve the 'this' container
14214                         // from the parent class declaration.
14215                         node = node.parent;
14216                     }
14217                     break;
14218                 case 202 /* ArrowFunction */:
14219                     if (!includeArrowFunctions) {
14220                         continue;
14221                     }
14222                 // falls through
14223                 case 244 /* FunctionDeclaration */:
14224                 case 201 /* FunctionExpression */:
14225                 case 249 /* ModuleDeclaration */:
14226                 case 159 /* PropertyDeclaration */:
14227                 case 158 /* PropertySignature */:
14228                 case 161 /* MethodDeclaration */:
14229                 case 160 /* MethodSignature */:
14230                 case 162 /* Constructor */:
14231                 case 163 /* GetAccessor */:
14232                 case 164 /* SetAccessor */:
14233                 case 165 /* CallSignature */:
14234                 case 166 /* ConstructSignature */:
14235                 case 167 /* IndexSignature */:
14236                 case 248 /* EnumDeclaration */:
14237                 case 290 /* SourceFile */:
14238                     return node;
14239             }
14240         }
14241     }
14242     ts.getThisContainer = getThisContainer;
14243     function getNewTargetContainer(node) {
14244         var container = getThisContainer(node, /*includeArrowFunctions*/ false);
14245         if (container) {
14246             switch (container.kind) {
14247                 case 162 /* Constructor */:
14248                 case 244 /* FunctionDeclaration */:
14249                 case 201 /* FunctionExpression */:
14250                     return container;
14251             }
14252         }
14253         return undefined;
14254     }
14255     ts.getNewTargetContainer = getNewTargetContainer;
14256     /**
14257      * Given an super call/property node, returns the closest node where
14258      * - a super call/property access is legal in the node and not legal in the parent node the node.
14259      *   i.e. super call is legal in constructor but not legal in the class body.
14260      * - the container is an arrow function (so caller might need to call getSuperContainer again in case it needs to climb higher)
14261      * - a super call/property is definitely illegal in the container (but might be legal in some subnode)
14262      *   i.e. super property access is illegal in function declaration but can be legal in the statement list
14263      */
14264     function getSuperContainer(node, stopOnFunctions) {
14265         while (true) {
14266             node = node.parent;
14267             if (!node) {
14268                 return node;
14269             }
14270             switch (node.kind) {
14271                 case 154 /* ComputedPropertyName */:
14272                     node = node.parent;
14273                     break;
14274                 case 244 /* FunctionDeclaration */:
14275                 case 201 /* FunctionExpression */:
14276                 case 202 /* ArrowFunction */:
14277                     if (!stopOnFunctions) {
14278                         continue;
14279                     }
14280                 // falls through
14281                 case 159 /* PropertyDeclaration */:
14282                 case 158 /* PropertySignature */:
14283                 case 161 /* MethodDeclaration */:
14284                 case 160 /* MethodSignature */:
14285                 case 162 /* Constructor */:
14286                 case 163 /* GetAccessor */:
14287                 case 164 /* SetAccessor */:
14288                     return node;
14289                 case 157 /* Decorator */:
14290                     // Decorators are always applied outside of the body of a class or method.
14291                     if (node.parent.kind === 156 /* Parameter */ && ts.isClassElement(node.parent.parent)) {
14292                         // If the decorator's parent is a Parameter, we resolve the this container from
14293                         // the grandparent class declaration.
14294                         node = node.parent.parent;
14295                     }
14296                     else if (ts.isClassElement(node.parent)) {
14297                         // If the decorator's parent is a class element, we resolve the 'this' container
14298                         // from the parent class declaration.
14299                         node = node.parent;
14300                     }
14301                     break;
14302             }
14303         }
14304     }
14305     ts.getSuperContainer = getSuperContainer;
14306     function getImmediatelyInvokedFunctionExpression(func) {
14307         if (func.kind === 201 /* FunctionExpression */ || func.kind === 202 /* ArrowFunction */) {
14308             var prev = func;
14309             var parent = func.parent;
14310             while (parent.kind === 200 /* ParenthesizedExpression */) {
14311                 prev = parent;
14312                 parent = parent.parent;
14313             }
14314             if (parent.kind === 196 /* CallExpression */ && parent.expression === prev) {
14315                 return parent;
14316             }
14317         }
14318     }
14319     ts.getImmediatelyInvokedFunctionExpression = getImmediatelyInvokedFunctionExpression;
14320     function isSuperOrSuperProperty(node) {
14321         return node.kind === 102 /* SuperKeyword */
14322             || isSuperProperty(node);
14323     }
14324     ts.isSuperOrSuperProperty = isSuperOrSuperProperty;
14325     /**
14326      * Determines whether a node is a property or element access expression for `super`.
14327      */
14328     function isSuperProperty(node) {
14329         var kind = node.kind;
14330         return (kind === 194 /* PropertyAccessExpression */ || kind === 195 /* ElementAccessExpression */)
14331             && node.expression.kind === 102 /* SuperKeyword */;
14332     }
14333     ts.isSuperProperty = isSuperProperty;
14334     /**
14335      * Determines whether a node is a property or element access expression for `this`.
14336      */
14337     function isThisProperty(node) {
14338         var kind = node.kind;
14339         return (kind === 194 /* PropertyAccessExpression */ || kind === 195 /* ElementAccessExpression */)
14340             && node.expression.kind === 104 /* ThisKeyword */;
14341     }
14342     ts.isThisProperty = isThisProperty;
14343     function getEntityNameFromTypeNode(node) {
14344         switch (node.kind) {
14345             case 169 /* TypeReference */:
14346                 return node.typeName;
14347             case 216 /* ExpressionWithTypeArguments */:
14348                 return isEntityNameExpression(node.expression)
14349                     ? node.expression
14350                     : undefined;
14351             case 75 /* Identifier */:
14352             case 153 /* QualifiedName */:
14353                 return node;
14354         }
14355         return undefined;
14356     }
14357     ts.getEntityNameFromTypeNode = getEntityNameFromTypeNode;
14358     function getInvokedExpression(node) {
14359         switch (node.kind) {
14360             case 198 /* TaggedTemplateExpression */:
14361                 return node.tag;
14362             case 268 /* JsxOpeningElement */:
14363             case 267 /* JsxSelfClosingElement */:
14364                 return node.tagName;
14365             default:
14366                 return node.expression;
14367         }
14368     }
14369     ts.getInvokedExpression = getInvokedExpression;
14370     function nodeCanBeDecorated(node, parent, grandparent) {
14371         // private names cannot be used with decorators yet
14372         if (ts.isNamedDeclaration(node) && ts.isPrivateIdentifier(node.name)) {
14373             return false;
14374         }
14375         switch (node.kind) {
14376             case 245 /* ClassDeclaration */:
14377                 // classes are valid targets
14378                 return true;
14379             case 159 /* PropertyDeclaration */:
14380                 // property declarations are valid if their parent is a class declaration.
14381                 return parent.kind === 245 /* ClassDeclaration */;
14382             case 163 /* GetAccessor */:
14383             case 164 /* SetAccessor */:
14384             case 161 /* MethodDeclaration */:
14385                 // if this method has a body and its parent is a class declaration, this is a valid target.
14386                 return node.body !== undefined
14387                     && parent.kind === 245 /* ClassDeclaration */;
14388             case 156 /* Parameter */:
14389                 // if the parameter's parent has a body and its grandparent is a class declaration, this is a valid target;
14390                 return parent.body !== undefined
14391                     && (parent.kind === 162 /* Constructor */
14392                         || parent.kind === 161 /* MethodDeclaration */
14393                         || parent.kind === 164 /* SetAccessor */)
14394                     && grandparent.kind === 245 /* ClassDeclaration */;
14395         }
14396         return false;
14397     }
14398     ts.nodeCanBeDecorated = nodeCanBeDecorated;
14399     function nodeIsDecorated(node, parent, grandparent) {
14400         return node.decorators !== undefined
14401             && nodeCanBeDecorated(node, parent, grandparent); // TODO: GH#18217
14402     }
14403     ts.nodeIsDecorated = nodeIsDecorated;
14404     function nodeOrChildIsDecorated(node, parent, grandparent) {
14405         return nodeIsDecorated(node, parent, grandparent) || childIsDecorated(node, parent); // TODO: GH#18217
14406     }
14407     ts.nodeOrChildIsDecorated = nodeOrChildIsDecorated;
14408     function childIsDecorated(node, parent) {
14409         switch (node.kind) {
14410             case 245 /* ClassDeclaration */:
14411                 return ts.some(node.members, function (m) { return nodeOrChildIsDecorated(m, node, parent); }); // TODO: GH#18217
14412             case 161 /* MethodDeclaration */:
14413             case 164 /* SetAccessor */:
14414                 return ts.some(node.parameters, function (p) { return nodeIsDecorated(p, node, parent); }); // TODO: GH#18217
14415             default:
14416                 return false;
14417         }
14418     }
14419     ts.childIsDecorated = childIsDecorated;
14420     function isJSXTagName(node) {
14421         var parent = node.parent;
14422         if (parent.kind === 268 /* JsxOpeningElement */ ||
14423             parent.kind === 267 /* JsxSelfClosingElement */ ||
14424             parent.kind === 269 /* JsxClosingElement */) {
14425             return parent.tagName === node;
14426         }
14427         return false;
14428     }
14429     ts.isJSXTagName = isJSXTagName;
14430     function isExpressionNode(node) {
14431         switch (node.kind) {
14432             case 102 /* SuperKeyword */:
14433             case 100 /* NullKeyword */:
14434             case 106 /* TrueKeyword */:
14435             case 91 /* FalseKeyword */:
14436             case 13 /* RegularExpressionLiteral */:
14437             case 192 /* ArrayLiteralExpression */:
14438             case 193 /* ObjectLiteralExpression */:
14439             case 194 /* PropertyAccessExpression */:
14440             case 195 /* ElementAccessExpression */:
14441             case 196 /* CallExpression */:
14442             case 197 /* NewExpression */:
14443             case 198 /* TaggedTemplateExpression */:
14444             case 217 /* AsExpression */:
14445             case 199 /* TypeAssertionExpression */:
14446             case 218 /* NonNullExpression */:
14447             case 200 /* ParenthesizedExpression */:
14448             case 201 /* FunctionExpression */:
14449             case 214 /* ClassExpression */:
14450             case 202 /* ArrowFunction */:
14451             case 205 /* VoidExpression */:
14452             case 203 /* DeleteExpression */:
14453             case 204 /* TypeOfExpression */:
14454             case 207 /* PrefixUnaryExpression */:
14455             case 208 /* PostfixUnaryExpression */:
14456             case 209 /* BinaryExpression */:
14457             case 210 /* ConditionalExpression */:
14458             case 213 /* SpreadElement */:
14459             case 211 /* TemplateExpression */:
14460             case 215 /* OmittedExpression */:
14461             case 266 /* JsxElement */:
14462             case 267 /* JsxSelfClosingElement */:
14463             case 270 /* JsxFragment */:
14464             case 212 /* YieldExpression */:
14465             case 206 /* AwaitExpression */:
14466             case 219 /* MetaProperty */:
14467                 return true;
14468             case 153 /* QualifiedName */:
14469                 while (node.parent.kind === 153 /* QualifiedName */) {
14470                     node = node.parent;
14471                 }
14472                 return node.parent.kind === 172 /* TypeQuery */ || isJSXTagName(node);
14473             case 75 /* Identifier */:
14474                 if (node.parent.kind === 172 /* TypeQuery */ || isJSXTagName(node)) {
14475                     return true;
14476                 }
14477             // falls through
14478             case 8 /* NumericLiteral */:
14479             case 9 /* BigIntLiteral */:
14480             case 10 /* StringLiteral */:
14481             case 14 /* NoSubstitutionTemplateLiteral */:
14482             case 104 /* ThisKeyword */:
14483                 return isInExpressionContext(node);
14484             default:
14485                 return false;
14486         }
14487     }
14488     ts.isExpressionNode = isExpressionNode;
14489     function isInExpressionContext(node) {
14490         var parent = node.parent;
14491         switch (parent.kind) {
14492             case 242 /* VariableDeclaration */:
14493             case 156 /* Parameter */:
14494             case 159 /* PropertyDeclaration */:
14495             case 158 /* PropertySignature */:
14496             case 284 /* EnumMember */:
14497             case 281 /* PropertyAssignment */:
14498             case 191 /* BindingElement */:
14499                 return parent.initializer === node;
14500             case 226 /* ExpressionStatement */:
14501             case 227 /* IfStatement */:
14502             case 228 /* DoStatement */:
14503             case 229 /* WhileStatement */:
14504             case 235 /* ReturnStatement */:
14505             case 236 /* WithStatement */:
14506             case 237 /* SwitchStatement */:
14507             case 277 /* CaseClause */:
14508             case 239 /* ThrowStatement */:
14509                 return parent.expression === node;
14510             case 230 /* ForStatement */:
14511                 var forStatement = parent;
14512                 return (forStatement.initializer === node && forStatement.initializer.kind !== 243 /* VariableDeclarationList */) ||
14513                     forStatement.condition === node ||
14514                     forStatement.incrementor === node;
14515             case 231 /* ForInStatement */:
14516             case 232 /* ForOfStatement */:
14517                 var forInStatement = parent;
14518                 return (forInStatement.initializer === node && forInStatement.initializer.kind !== 243 /* VariableDeclarationList */) ||
14519                     forInStatement.expression === node;
14520             case 199 /* TypeAssertionExpression */:
14521             case 217 /* AsExpression */:
14522                 return node === parent.expression;
14523             case 221 /* TemplateSpan */:
14524                 return node === parent.expression;
14525             case 154 /* ComputedPropertyName */:
14526                 return node === parent.expression;
14527             case 157 /* Decorator */:
14528             case 276 /* JsxExpression */:
14529             case 275 /* JsxSpreadAttribute */:
14530             case 283 /* SpreadAssignment */:
14531                 return true;
14532             case 216 /* ExpressionWithTypeArguments */:
14533                 return parent.expression === node && isExpressionWithTypeArgumentsInClassExtendsClause(parent);
14534             case 282 /* ShorthandPropertyAssignment */:
14535                 return parent.objectAssignmentInitializer === node;
14536             default:
14537                 return isExpressionNode(parent);
14538         }
14539     }
14540     ts.isInExpressionContext = isInExpressionContext;
14541     function isPartOfTypeQuery(node) {
14542         while (node.kind === 153 /* QualifiedName */ || node.kind === 75 /* Identifier */) {
14543             node = node.parent;
14544         }
14545         return node.kind === 172 /* TypeQuery */;
14546     }
14547     ts.isPartOfTypeQuery = isPartOfTypeQuery;
14548     function isExternalModuleImportEqualsDeclaration(node) {
14549         return node.kind === 253 /* ImportEqualsDeclaration */ && node.moduleReference.kind === 265 /* ExternalModuleReference */;
14550     }
14551     ts.isExternalModuleImportEqualsDeclaration = isExternalModuleImportEqualsDeclaration;
14552     function getExternalModuleImportEqualsDeclarationExpression(node) {
14553         ts.Debug.assert(isExternalModuleImportEqualsDeclaration(node));
14554         return node.moduleReference.expression;
14555     }
14556     ts.getExternalModuleImportEqualsDeclarationExpression = getExternalModuleImportEqualsDeclarationExpression;
14557     function isInternalModuleImportEqualsDeclaration(node) {
14558         return node.kind === 253 /* ImportEqualsDeclaration */ && node.moduleReference.kind !== 265 /* ExternalModuleReference */;
14559     }
14560     ts.isInternalModuleImportEqualsDeclaration = isInternalModuleImportEqualsDeclaration;
14561     function isSourceFileJS(file) {
14562         return isInJSFile(file);
14563     }
14564     ts.isSourceFileJS = isSourceFileJS;
14565     function isSourceFileNotJS(file) {
14566         return !isInJSFile(file);
14567     }
14568     ts.isSourceFileNotJS = isSourceFileNotJS;
14569     function isInJSFile(node) {
14570         return !!node && !!(node.flags & 131072 /* JavaScriptFile */);
14571     }
14572     ts.isInJSFile = isInJSFile;
14573     function isInJsonFile(node) {
14574         return !!node && !!(node.flags & 33554432 /* JsonFile */);
14575     }
14576     ts.isInJsonFile = isInJsonFile;
14577     function isSourceFileNotJson(file) {
14578         return !isJsonSourceFile(file);
14579     }
14580     ts.isSourceFileNotJson = isSourceFileNotJson;
14581     function isInJSDoc(node) {
14582         return !!node && !!(node.flags & 4194304 /* JSDoc */);
14583     }
14584     ts.isInJSDoc = isInJSDoc;
14585     function isJSDocIndexSignature(node) {
14586         return ts.isTypeReferenceNode(node) &&
14587             ts.isIdentifier(node.typeName) &&
14588             node.typeName.escapedText === "Object" &&
14589             node.typeArguments && node.typeArguments.length === 2 &&
14590             (node.typeArguments[0].kind === 143 /* StringKeyword */ || node.typeArguments[0].kind === 140 /* NumberKeyword */);
14591     }
14592     ts.isJSDocIndexSignature = isJSDocIndexSignature;
14593     function isRequireCall(callExpression, requireStringLiteralLikeArgument) {
14594         if (callExpression.kind !== 196 /* CallExpression */) {
14595             return false;
14596         }
14597         var _a = callExpression, expression = _a.expression, args = _a.arguments;
14598         if (expression.kind !== 75 /* Identifier */ || expression.escapedText !== "require") {
14599             return false;
14600         }
14601         if (args.length !== 1) {
14602             return false;
14603         }
14604         var arg = args[0];
14605         return !requireStringLiteralLikeArgument || ts.isStringLiteralLike(arg);
14606     }
14607     ts.isRequireCall = isRequireCall;
14608     function isRequireVariableDeclaration(node, requireStringLiteralLikeArgument) {
14609         return ts.isVariableDeclaration(node) && !!node.initializer && isRequireCall(node.initializer, requireStringLiteralLikeArgument);
14610     }
14611     ts.isRequireVariableDeclaration = isRequireVariableDeclaration;
14612     function isRequireVariableDeclarationStatement(node, requireStringLiteralLikeArgument) {
14613         if (requireStringLiteralLikeArgument === void 0) { requireStringLiteralLikeArgument = true; }
14614         return ts.isVariableStatement(node) && ts.every(node.declarationList.declarations, function (decl) { return isRequireVariableDeclaration(decl, requireStringLiteralLikeArgument); });
14615     }
14616     ts.isRequireVariableDeclarationStatement = isRequireVariableDeclarationStatement;
14617     function isSingleOrDoubleQuote(charCode) {
14618         return charCode === 39 /* singleQuote */ || charCode === 34 /* doubleQuote */;
14619     }
14620     ts.isSingleOrDoubleQuote = isSingleOrDoubleQuote;
14621     function isStringDoubleQuoted(str, sourceFile) {
14622         return getSourceTextOfNodeFromSourceFile(sourceFile, str).charCodeAt(0) === 34 /* doubleQuote */;
14623     }
14624     ts.isStringDoubleQuoted = isStringDoubleQuoted;
14625     function getDeclarationOfExpando(node) {
14626         if (!node.parent) {
14627             return undefined;
14628         }
14629         var name;
14630         var decl;
14631         if (ts.isVariableDeclaration(node.parent) && node.parent.initializer === node) {
14632             if (!isInJSFile(node) && !isVarConst(node.parent)) {
14633                 return undefined;
14634             }
14635             name = node.parent.name;
14636             decl = node.parent;
14637         }
14638         else if (ts.isBinaryExpression(node.parent)) {
14639             var parentNode = node.parent;
14640             var parentNodeOperator = node.parent.operatorToken.kind;
14641             if (parentNodeOperator === 62 /* EqualsToken */ && parentNode.right === node) {
14642                 name = parentNode.left;
14643                 decl = name;
14644             }
14645             else if (parentNodeOperator === 56 /* BarBarToken */ || parentNodeOperator === 60 /* QuestionQuestionToken */) {
14646                 if (ts.isVariableDeclaration(parentNode.parent) && parentNode.parent.initializer === parentNode) {
14647                     name = parentNode.parent.name;
14648                     decl = parentNode.parent;
14649                 }
14650                 else if (ts.isBinaryExpression(parentNode.parent) && parentNode.parent.operatorToken.kind === 62 /* EqualsToken */ && parentNode.parent.right === parentNode) {
14651                     name = parentNode.parent.left;
14652                     decl = name;
14653                 }
14654                 if (!name || !isBindableStaticNameExpression(name) || !isSameEntityName(name, parentNode.left)) {
14655                     return undefined;
14656                 }
14657             }
14658         }
14659         if (!name || !getExpandoInitializer(node, isPrototypeAccess(name))) {
14660             return undefined;
14661         }
14662         return decl;
14663     }
14664     ts.getDeclarationOfExpando = getDeclarationOfExpando;
14665     function isAssignmentDeclaration(decl) {
14666         return ts.isBinaryExpression(decl) || isAccessExpression(decl) || ts.isIdentifier(decl) || ts.isCallExpression(decl);
14667     }
14668     ts.isAssignmentDeclaration = isAssignmentDeclaration;
14669     /** Get the initializer, taking into account defaulted Javascript initializers */
14670     function getEffectiveInitializer(node) {
14671         if (isInJSFile(node) && node.initializer &&
14672             ts.isBinaryExpression(node.initializer) &&
14673             (node.initializer.operatorToken.kind === 56 /* BarBarToken */ || node.initializer.operatorToken.kind === 60 /* QuestionQuestionToken */) &&
14674             node.name && isEntityNameExpression(node.name) && isSameEntityName(node.name, node.initializer.left)) {
14675             return node.initializer.right;
14676         }
14677         return node.initializer;
14678     }
14679     ts.getEffectiveInitializer = getEffectiveInitializer;
14680     /** Get the declaration initializer when it is container-like (See getExpandoInitializer). */
14681     function getDeclaredExpandoInitializer(node) {
14682         var init = getEffectiveInitializer(node);
14683         return init && getExpandoInitializer(init, isPrototypeAccess(node.name));
14684     }
14685     ts.getDeclaredExpandoInitializer = getDeclaredExpandoInitializer;
14686     function hasExpandoValueProperty(node, isPrototypeAssignment) {
14687         return ts.forEach(node.properties, function (p) {
14688             return ts.isPropertyAssignment(p) &&
14689                 ts.isIdentifier(p.name) &&
14690                 p.name.escapedText === "value" &&
14691                 p.initializer &&
14692                 getExpandoInitializer(p.initializer, isPrototypeAssignment);
14693         });
14694     }
14695     /**
14696      * Get the assignment 'initializer' -- the righthand side-- when the initializer is container-like (See getExpandoInitializer).
14697      * We treat the right hand side of assignments with container-like initalizers as declarations.
14698      */
14699     function getAssignedExpandoInitializer(node) {
14700         if (node && node.parent && ts.isBinaryExpression(node.parent) && node.parent.operatorToken.kind === 62 /* EqualsToken */) {
14701             var isPrototypeAssignment = isPrototypeAccess(node.parent.left);
14702             return getExpandoInitializer(node.parent.right, isPrototypeAssignment) ||
14703                 getDefaultedExpandoInitializer(node.parent.left, node.parent.right, isPrototypeAssignment);
14704         }
14705         if (node && ts.isCallExpression(node) && isBindableObjectDefinePropertyCall(node)) {
14706             var result = hasExpandoValueProperty(node.arguments[2], node.arguments[1].text === "prototype");
14707             if (result) {
14708                 return result;
14709             }
14710         }
14711     }
14712     ts.getAssignedExpandoInitializer = getAssignedExpandoInitializer;
14713     /**
14714      * Recognized expando initializers are:
14715      * 1. (function() {})() -- IIFEs
14716      * 2. function() { } -- Function expressions
14717      * 3. class { } -- Class expressions
14718      * 4. {} -- Empty object literals
14719      * 5. { ... } -- Non-empty object literals, when used to initialize a prototype, like `C.prototype = { m() { } }`
14720      *
14721      * This function returns the provided initializer, or undefined if it is not valid.
14722      */
14723     function getExpandoInitializer(initializer, isPrototypeAssignment) {
14724         if (ts.isCallExpression(initializer)) {
14725             var e = skipParentheses(initializer.expression);
14726             return e.kind === 201 /* FunctionExpression */ || e.kind === 202 /* ArrowFunction */ ? initializer : undefined;
14727         }
14728         if (initializer.kind === 201 /* FunctionExpression */ ||
14729             initializer.kind === 214 /* ClassExpression */ ||
14730             initializer.kind === 202 /* ArrowFunction */) {
14731             return initializer;
14732         }
14733         if (ts.isObjectLiteralExpression(initializer) && (initializer.properties.length === 0 || isPrototypeAssignment)) {
14734             return initializer;
14735         }
14736     }
14737     ts.getExpandoInitializer = getExpandoInitializer;
14738     /**
14739      * A defaulted expando initializer matches the pattern
14740      * `Lhs = Lhs || ExpandoInitializer`
14741      * or `var Lhs = Lhs || ExpandoInitializer`
14742      *
14743      * The second Lhs is required to be the same as the first except that it may be prefixed with
14744      * 'window.', 'global.' or 'self.' The second Lhs is otherwise ignored by the binder and checker.
14745      */
14746     function getDefaultedExpandoInitializer(name, initializer, isPrototypeAssignment) {
14747         var e = ts.isBinaryExpression(initializer)
14748             && (initializer.operatorToken.kind === 56 /* BarBarToken */ || initializer.operatorToken.kind === 60 /* QuestionQuestionToken */)
14749             && getExpandoInitializer(initializer.right, isPrototypeAssignment);
14750         if (e && isSameEntityName(name, initializer.left)) {
14751             return e;
14752         }
14753     }
14754     function isDefaultedExpandoInitializer(node) {
14755         var name = ts.isVariableDeclaration(node.parent) ? node.parent.name :
14756             ts.isBinaryExpression(node.parent) && node.parent.operatorToken.kind === 62 /* EqualsToken */ ? node.parent.left :
14757                 undefined;
14758         return name && getExpandoInitializer(node.right, isPrototypeAccess(name)) && isEntityNameExpression(name) && isSameEntityName(name, node.left);
14759     }
14760     ts.isDefaultedExpandoInitializer = isDefaultedExpandoInitializer;
14761     /** Given an expando initializer, return its declaration name, or the left-hand side of the assignment if it's part of an assignment declaration. */
14762     function getNameOfExpando(node) {
14763         if (ts.isBinaryExpression(node.parent)) {
14764             var parent = ((node.parent.operatorToken.kind === 56 /* BarBarToken */ || node.parent.operatorToken.kind === 60 /* QuestionQuestionToken */) && ts.isBinaryExpression(node.parent.parent)) ? node.parent.parent : node.parent;
14765             if (parent.operatorToken.kind === 62 /* EqualsToken */ && ts.isIdentifier(parent.left)) {
14766                 return parent.left;
14767             }
14768         }
14769         else if (ts.isVariableDeclaration(node.parent)) {
14770             return node.parent.name;
14771         }
14772     }
14773     ts.getNameOfExpando = getNameOfExpando;
14774     /**
14775      * Is the 'declared' name the same as the one in the initializer?
14776      * @return true for identical entity names, as well as ones where the initializer is prefixed with
14777      * 'window', 'self' or 'global'. For example:
14778      *
14779      * var my = my || {}
14780      * var min = window.min || {}
14781      * my.app = self.my.app || class { }
14782      */
14783     function isSameEntityName(name, initializer) {
14784         if (isPropertyNameLiteral(name) && isPropertyNameLiteral(initializer)) {
14785             return getTextOfIdentifierOrLiteral(name) === getTextOfIdentifierOrLiteral(name);
14786         }
14787         if (ts.isIdentifier(name) && isLiteralLikeAccess(initializer) &&
14788             (initializer.expression.kind === 104 /* ThisKeyword */ ||
14789                 ts.isIdentifier(initializer.expression) &&
14790                     (initializer.expression.escapedText === "window" ||
14791                         initializer.expression.escapedText === "self" ||
14792                         initializer.expression.escapedText === "global"))) {
14793             var nameOrArgument = getNameOrArgument(initializer);
14794             if (ts.isPrivateIdentifier(nameOrArgument)) {
14795                 ts.Debug.fail("Unexpected PrivateIdentifier in name expression with literal-like access.");
14796             }
14797             return isSameEntityName(name, nameOrArgument);
14798         }
14799         if (isLiteralLikeAccess(name) && isLiteralLikeAccess(initializer)) {
14800             return getElementOrPropertyAccessName(name) === getElementOrPropertyAccessName(initializer)
14801                 && isSameEntityName(name.expression, initializer.expression);
14802         }
14803         return false;
14804     }
14805     function getRightMostAssignedExpression(node) {
14806         while (isAssignmentExpression(node, /*excludeCompoundAssignments*/ true)) {
14807             node = node.right;
14808         }
14809         return node;
14810     }
14811     ts.getRightMostAssignedExpression = getRightMostAssignedExpression;
14812     function isExportsIdentifier(node) {
14813         return ts.isIdentifier(node) && node.escapedText === "exports";
14814     }
14815     ts.isExportsIdentifier = isExportsIdentifier;
14816     function isModuleIdentifier(node) {
14817         return ts.isIdentifier(node) && node.escapedText === "module";
14818     }
14819     ts.isModuleIdentifier = isModuleIdentifier;
14820     function isModuleExportsAccessExpression(node) {
14821         return (ts.isPropertyAccessExpression(node) || isLiteralLikeElementAccess(node))
14822             && isModuleIdentifier(node.expression)
14823             && getElementOrPropertyAccessName(node) === "exports";
14824     }
14825     ts.isModuleExportsAccessExpression = isModuleExportsAccessExpression;
14826     /// Given a BinaryExpression, returns SpecialPropertyAssignmentKind for the various kinds of property
14827     /// assignments we treat as special in the binder
14828     function getAssignmentDeclarationKind(expr) {
14829         var special = getAssignmentDeclarationKindWorker(expr);
14830         return special === 5 /* Property */ || isInJSFile(expr) ? special : 0 /* None */;
14831     }
14832     ts.getAssignmentDeclarationKind = getAssignmentDeclarationKind;
14833     function isBindableObjectDefinePropertyCall(expr) {
14834         return ts.length(expr.arguments) === 3 &&
14835             ts.isPropertyAccessExpression(expr.expression) &&
14836             ts.isIdentifier(expr.expression.expression) &&
14837             ts.idText(expr.expression.expression) === "Object" &&
14838             ts.idText(expr.expression.name) === "defineProperty" &&
14839             isStringOrNumericLiteralLike(expr.arguments[1]) &&
14840             isBindableStaticNameExpression(expr.arguments[0], /*excludeThisKeyword*/ true);
14841     }
14842     ts.isBindableObjectDefinePropertyCall = isBindableObjectDefinePropertyCall;
14843     /** x.y OR x[0] */
14844     function isLiteralLikeAccess(node) {
14845         return ts.isPropertyAccessExpression(node) || isLiteralLikeElementAccess(node);
14846     }
14847     ts.isLiteralLikeAccess = isLiteralLikeAccess;
14848     /** x[0] OR x['a'] OR x[Symbol.y] */
14849     function isLiteralLikeElementAccess(node) {
14850         return ts.isElementAccessExpression(node) && (isStringOrNumericLiteralLike(node.argumentExpression) ||
14851             isWellKnownSymbolSyntactically(node.argumentExpression));
14852     }
14853     ts.isLiteralLikeElementAccess = isLiteralLikeElementAccess;
14854     /** Any series of property and element accesses. */
14855     function isBindableStaticAccessExpression(node, excludeThisKeyword) {
14856         return ts.isPropertyAccessExpression(node) && (!excludeThisKeyword && node.expression.kind === 104 /* ThisKeyword */ || ts.isIdentifier(node.name) && isBindableStaticNameExpression(node.expression, /*excludeThisKeyword*/ true))
14857             || isBindableStaticElementAccessExpression(node, excludeThisKeyword);
14858     }
14859     ts.isBindableStaticAccessExpression = isBindableStaticAccessExpression;
14860     /** Any series of property and element accesses, ending in a literal element access */
14861     function isBindableStaticElementAccessExpression(node, excludeThisKeyword) {
14862         return isLiteralLikeElementAccess(node)
14863             && ((!excludeThisKeyword && node.expression.kind === 104 /* ThisKeyword */) ||
14864                 isEntityNameExpression(node.expression) ||
14865                 isBindableStaticAccessExpression(node.expression, /*excludeThisKeyword*/ true));
14866     }
14867     ts.isBindableStaticElementAccessExpression = isBindableStaticElementAccessExpression;
14868     function isBindableStaticNameExpression(node, excludeThisKeyword) {
14869         return isEntityNameExpression(node) || isBindableStaticAccessExpression(node, excludeThisKeyword);
14870     }
14871     ts.isBindableStaticNameExpression = isBindableStaticNameExpression;
14872     function getNameOrArgument(expr) {
14873         if (ts.isPropertyAccessExpression(expr)) {
14874             return expr.name;
14875         }
14876         return expr.argumentExpression;
14877     }
14878     ts.getNameOrArgument = getNameOrArgument;
14879     function getAssignmentDeclarationKindWorker(expr) {
14880         if (ts.isCallExpression(expr)) {
14881             if (!isBindableObjectDefinePropertyCall(expr)) {
14882                 return 0 /* None */;
14883             }
14884             var entityName = expr.arguments[0];
14885             if (isExportsIdentifier(entityName) || isModuleExportsAccessExpression(entityName)) {
14886                 return 8 /* ObjectDefinePropertyExports */;
14887             }
14888             if (isBindableStaticAccessExpression(entityName) && getElementOrPropertyAccessName(entityName) === "prototype") {
14889                 return 9 /* ObjectDefinePrototypeProperty */;
14890             }
14891             return 7 /* ObjectDefinePropertyValue */;
14892         }
14893         if (expr.operatorToken.kind !== 62 /* EqualsToken */ || !isAccessExpression(expr.left)) {
14894             return 0 /* None */;
14895         }
14896         if (isBindableStaticNameExpression(expr.left.expression, /*excludeThisKeyword*/ true) && getElementOrPropertyAccessName(expr.left) === "prototype" && ts.isObjectLiteralExpression(getInitializerOfBinaryExpression(expr))) {
14897             // F.prototype = { ... }
14898             return 6 /* Prototype */;
14899         }
14900         return getAssignmentDeclarationPropertyAccessKind(expr.left);
14901     }
14902     /**
14903      * Does not handle signed numeric names like `a[+0]` - handling those would require handling prefix unary expressions
14904      * throughout late binding handling as well, which is awkward (but ultimately probably doable if there is demand)
14905      */
14906     /* @internal */
14907     function getElementOrPropertyAccessArgumentExpressionOrName(node) {
14908         if (ts.isPropertyAccessExpression(node)) {
14909             return node.name;
14910         }
14911         var arg = skipParentheses(node.argumentExpression);
14912         if (ts.isNumericLiteral(arg) || ts.isStringLiteralLike(arg)) {
14913             return arg;
14914         }
14915         return node;
14916     }
14917     ts.getElementOrPropertyAccessArgumentExpressionOrName = getElementOrPropertyAccessArgumentExpressionOrName;
14918     function getElementOrPropertyAccessName(node) {
14919         var name = getElementOrPropertyAccessArgumentExpressionOrName(node);
14920         if (name) {
14921             if (ts.isIdentifier(name)) {
14922                 return name.escapedText;
14923             }
14924             if (ts.isStringLiteralLike(name) || ts.isNumericLiteral(name)) {
14925                 return ts.escapeLeadingUnderscores(name.text);
14926             }
14927         }
14928         if (ts.isElementAccessExpression(node) && isWellKnownSymbolSyntactically(node.argumentExpression)) {
14929             return getPropertyNameForKnownSymbolName(ts.idText(node.argumentExpression.name));
14930         }
14931         return undefined;
14932     }
14933     ts.getElementOrPropertyAccessName = getElementOrPropertyAccessName;
14934     function getAssignmentDeclarationPropertyAccessKind(lhs) {
14935         if (lhs.expression.kind === 104 /* ThisKeyword */) {
14936             return 4 /* ThisProperty */;
14937         }
14938         else if (isModuleExportsAccessExpression(lhs)) {
14939             // module.exports = expr
14940             return 2 /* ModuleExports */;
14941         }
14942         else if (isBindableStaticNameExpression(lhs.expression, /*excludeThisKeyword*/ true)) {
14943             if (isPrototypeAccess(lhs.expression)) {
14944                 // F.G....prototype.x = expr
14945                 return 3 /* PrototypeProperty */;
14946             }
14947             var nextToLast = lhs;
14948             while (!ts.isIdentifier(nextToLast.expression)) {
14949                 nextToLast = nextToLast.expression;
14950             }
14951             var id = nextToLast.expression;
14952             if ((id.escapedText === "exports" ||
14953                 id.escapedText === "module" && getElementOrPropertyAccessName(nextToLast) === "exports") &&
14954                 // ExportsProperty does not support binding with computed names
14955                 isBindableStaticAccessExpression(lhs)) {
14956                 // exports.name = expr OR module.exports.name = expr OR exports["name"] = expr ...
14957                 return 1 /* ExportsProperty */;
14958             }
14959             if (isBindableStaticNameExpression(lhs, /*excludeThisKeyword*/ true) || (ts.isElementAccessExpression(lhs) && isDynamicName(lhs))) {
14960                 // F.G...x = expr
14961                 return 5 /* Property */;
14962             }
14963         }
14964         return 0 /* None */;
14965     }
14966     ts.getAssignmentDeclarationPropertyAccessKind = getAssignmentDeclarationPropertyAccessKind;
14967     function getInitializerOfBinaryExpression(expr) {
14968         while (ts.isBinaryExpression(expr.right)) {
14969             expr = expr.right;
14970         }
14971         return expr.right;
14972     }
14973     ts.getInitializerOfBinaryExpression = getInitializerOfBinaryExpression;
14974     function isPrototypePropertyAssignment(node) {
14975         return ts.isBinaryExpression(node) && getAssignmentDeclarationKind(node) === 3 /* PrototypeProperty */;
14976     }
14977     ts.isPrototypePropertyAssignment = isPrototypePropertyAssignment;
14978     function isSpecialPropertyDeclaration(expr) {
14979         return isInJSFile(expr) &&
14980             expr.parent && expr.parent.kind === 226 /* ExpressionStatement */ &&
14981             (!ts.isElementAccessExpression(expr) || isLiteralLikeElementAccess(expr)) &&
14982             !!ts.getJSDocTypeTag(expr.parent);
14983     }
14984     ts.isSpecialPropertyDeclaration = isSpecialPropertyDeclaration;
14985     function setValueDeclaration(symbol, node) {
14986         var valueDeclaration = symbol.valueDeclaration;
14987         if (!valueDeclaration ||
14988             !(node.flags & 8388608 /* Ambient */ && !(valueDeclaration.flags & 8388608 /* Ambient */)) &&
14989                 (isAssignmentDeclaration(valueDeclaration) && !isAssignmentDeclaration(node)) ||
14990             (valueDeclaration.kind !== node.kind && isEffectiveModuleDeclaration(valueDeclaration))) {
14991             // other kinds of value declarations take precedence over modules and assignment declarations
14992             symbol.valueDeclaration = node;
14993         }
14994     }
14995     ts.setValueDeclaration = setValueDeclaration;
14996     function isFunctionSymbol(symbol) {
14997         if (!symbol || !symbol.valueDeclaration) {
14998             return false;
14999         }
15000         var decl = symbol.valueDeclaration;
15001         return decl.kind === 244 /* FunctionDeclaration */ || ts.isVariableDeclaration(decl) && decl.initializer && ts.isFunctionLike(decl.initializer);
15002     }
15003     ts.isFunctionSymbol = isFunctionSymbol;
15004     function importFromModuleSpecifier(node) {
15005         return tryGetImportFromModuleSpecifier(node) || ts.Debug.failBadSyntaxKind(node.parent);
15006     }
15007     ts.importFromModuleSpecifier = importFromModuleSpecifier;
15008     function tryGetImportFromModuleSpecifier(node) {
15009         switch (node.parent.kind) {
15010             case 254 /* ImportDeclaration */:
15011             case 260 /* ExportDeclaration */:
15012                 return node.parent;
15013             case 265 /* ExternalModuleReference */:
15014                 return node.parent.parent;
15015             case 196 /* CallExpression */:
15016                 return isImportCall(node.parent) || isRequireCall(node.parent, /*checkArg*/ false) ? node.parent : undefined;
15017             case 187 /* LiteralType */:
15018                 ts.Debug.assert(ts.isStringLiteral(node));
15019                 return ts.tryCast(node.parent.parent, ts.isImportTypeNode);
15020             default:
15021                 return undefined;
15022         }
15023     }
15024     ts.tryGetImportFromModuleSpecifier = tryGetImportFromModuleSpecifier;
15025     function getExternalModuleName(node) {
15026         switch (node.kind) {
15027             case 254 /* ImportDeclaration */:
15028             case 260 /* ExportDeclaration */:
15029                 return node.moduleSpecifier;
15030             case 253 /* ImportEqualsDeclaration */:
15031                 return node.moduleReference.kind === 265 /* ExternalModuleReference */ ? node.moduleReference.expression : undefined;
15032             case 188 /* ImportType */:
15033                 return isLiteralImportTypeNode(node) ? node.argument.literal : undefined;
15034             default:
15035                 return ts.Debug.assertNever(node);
15036         }
15037     }
15038     ts.getExternalModuleName = getExternalModuleName;
15039     function getNamespaceDeclarationNode(node) {
15040         switch (node.kind) {
15041             case 254 /* ImportDeclaration */:
15042                 return node.importClause && ts.tryCast(node.importClause.namedBindings, ts.isNamespaceImport);
15043             case 253 /* ImportEqualsDeclaration */:
15044                 return node;
15045             case 260 /* ExportDeclaration */:
15046                 return node.exportClause && ts.tryCast(node.exportClause, ts.isNamespaceExport);
15047             default:
15048                 return ts.Debug.assertNever(node);
15049         }
15050     }
15051     ts.getNamespaceDeclarationNode = getNamespaceDeclarationNode;
15052     function isDefaultImport(node) {
15053         return node.kind === 254 /* ImportDeclaration */ && !!node.importClause && !!node.importClause.name;
15054     }
15055     ts.isDefaultImport = isDefaultImport;
15056     function forEachImportClauseDeclaration(node, action) {
15057         if (node.name) {
15058             var result = action(node);
15059             if (result)
15060                 return result;
15061         }
15062         if (node.namedBindings) {
15063             var result = ts.isNamespaceImport(node.namedBindings)
15064                 ? action(node.namedBindings)
15065                 : ts.forEach(node.namedBindings.elements, action);
15066             if (result)
15067                 return result;
15068         }
15069     }
15070     ts.forEachImportClauseDeclaration = forEachImportClauseDeclaration;
15071     function hasQuestionToken(node) {
15072         if (node) {
15073             switch (node.kind) {
15074                 case 156 /* Parameter */:
15075                 case 161 /* MethodDeclaration */:
15076                 case 160 /* MethodSignature */:
15077                 case 282 /* ShorthandPropertyAssignment */:
15078                 case 281 /* PropertyAssignment */:
15079                 case 159 /* PropertyDeclaration */:
15080                 case 158 /* PropertySignature */:
15081                     return node.questionToken !== undefined;
15082             }
15083         }
15084         return false;
15085     }
15086     ts.hasQuestionToken = hasQuestionToken;
15087     function isJSDocConstructSignature(node) {
15088         var param = ts.isJSDocFunctionType(node) ? ts.firstOrUndefined(node.parameters) : undefined;
15089         var name = ts.tryCast(param && param.name, ts.isIdentifier);
15090         return !!name && name.escapedText === "new";
15091     }
15092     ts.isJSDocConstructSignature = isJSDocConstructSignature;
15093     function isJSDocTypeAlias(node) {
15094         return node.kind === 322 /* JSDocTypedefTag */ || node.kind === 315 /* JSDocCallbackTag */ || node.kind === 316 /* JSDocEnumTag */;
15095     }
15096     ts.isJSDocTypeAlias = isJSDocTypeAlias;
15097     function isTypeAlias(node) {
15098         return isJSDocTypeAlias(node) || ts.isTypeAliasDeclaration(node);
15099     }
15100     ts.isTypeAlias = isTypeAlias;
15101     function getSourceOfAssignment(node) {
15102         return ts.isExpressionStatement(node) &&
15103             ts.isBinaryExpression(node.expression) &&
15104             node.expression.operatorToken.kind === 62 /* EqualsToken */
15105             ? getRightMostAssignedExpression(node.expression)
15106             : undefined;
15107     }
15108     function getSourceOfDefaultedAssignment(node) {
15109         return ts.isExpressionStatement(node) &&
15110             ts.isBinaryExpression(node.expression) &&
15111             getAssignmentDeclarationKind(node.expression) !== 0 /* None */ &&
15112             ts.isBinaryExpression(node.expression.right) &&
15113             (node.expression.right.operatorToken.kind === 56 /* BarBarToken */ || node.expression.right.operatorToken.kind === 60 /* QuestionQuestionToken */)
15114             ? node.expression.right.right
15115             : undefined;
15116     }
15117     function getSingleInitializerOfVariableStatementOrPropertyDeclaration(node) {
15118         switch (node.kind) {
15119             case 225 /* VariableStatement */:
15120                 var v = getSingleVariableOfVariableStatement(node);
15121                 return v && v.initializer;
15122             case 159 /* PropertyDeclaration */:
15123                 return node.initializer;
15124             case 281 /* PropertyAssignment */:
15125                 return node.initializer;
15126         }
15127     }
15128     ts.getSingleInitializerOfVariableStatementOrPropertyDeclaration = getSingleInitializerOfVariableStatementOrPropertyDeclaration;
15129     function getSingleVariableOfVariableStatement(node) {
15130         return ts.isVariableStatement(node) ? ts.firstOrUndefined(node.declarationList.declarations) : undefined;
15131     }
15132     function getNestedModuleDeclaration(node) {
15133         return ts.isModuleDeclaration(node) &&
15134             node.body &&
15135             node.body.kind === 249 /* ModuleDeclaration */
15136             ? node.body
15137             : undefined;
15138     }
15139     function getJSDocCommentsAndTags(hostNode) {
15140         var result;
15141         // Pull parameter comments from declaring function as well
15142         if (isVariableLike(hostNode) && ts.hasInitializer(hostNode) && ts.hasJSDocNodes(hostNode.initializer)) {
15143             result = ts.append(result, ts.last(hostNode.initializer.jsDoc));
15144         }
15145         var node = hostNode;
15146         while (node && node.parent) {
15147             if (ts.hasJSDocNodes(node)) {
15148                 result = ts.append(result, ts.last(node.jsDoc));
15149             }
15150             if (node.kind === 156 /* Parameter */) {
15151                 result = ts.addRange(result, ts.getJSDocParameterTags(node));
15152                 break;
15153             }
15154             if (node.kind === 155 /* TypeParameter */) {
15155                 result = ts.addRange(result, ts.getJSDocTypeParameterTags(node));
15156                 break;
15157             }
15158             node = getNextJSDocCommentLocation(node);
15159         }
15160         return result || ts.emptyArray;
15161     }
15162     ts.getJSDocCommentsAndTags = getJSDocCommentsAndTags;
15163     function getNextJSDocCommentLocation(node) {
15164         var parent = node.parent;
15165         if (parent.kind === 281 /* PropertyAssignment */ ||
15166             parent.kind === 259 /* ExportAssignment */ ||
15167             parent.kind === 159 /* PropertyDeclaration */ ||
15168             parent.kind === 226 /* ExpressionStatement */ && node.kind === 194 /* PropertyAccessExpression */ ||
15169             getNestedModuleDeclaration(parent) ||
15170             ts.isBinaryExpression(node) && node.operatorToken.kind === 62 /* EqualsToken */) {
15171             return parent;
15172         }
15173         // Try to recognize this pattern when node is initializer of variable declaration and JSDoc comments are on containing variable statement.
15174         // /**
15175         //   * @param {number} name
15176         //   * @returns {number}
15177         //   */
15178         // var x = function(name) { return name.length; }
15179         else if (parent.parent &&
15180             (getSingleVariableOfVariableStatement(parent.parent) === node ||
15181                 ts.isBinaryExpression(parent) && parent.operatorToken.kind === 62 /* EqualsToken */)) {
15182             return parent.parent;
15183         }
15184         else if (parent.parent && parent.parent.parent &&
15185             (getSingleVariableOfVariableStatement(parent.parent.parent) ||
15186                 getSingleInitializerOfVariableStatementOrPropertyDeclaration(parent.parent.parent) === node ||
15187                 getSourceOfDefaultedAssignment(parent.parent.parent))) {
15188             return parent.parent.parent;
15189         }
15190     }
15191     /** Does the opposite of `getJSDocParameterTags`: given a JSDoc parameter, finds the parameter corresponding to it. */
15192     function getParameterSymbolFromJSDoc(node) {
15193         if (node.symbol) {
15194             return node.symbol;
15195         }
15196         if (!ts.isIdentifier(node.name)) {
15197             return undefined;
15198         }
15199         var name = node.name.escapedText;
15200         var decl = getHostSignatureFromJSDoc(node);
15201         if (!decl) {
15202             return undefined;
15203         }
15204         var parameter = ts.find(decl.parameters, function (p) { return p.name.kind === 75 /* Identifier */ && p.name.escapedText === name; });
15205         return parameter && parameter.symbol;
15206     }
15207     ts.getParameterSymbolFromJSDoc = getParameterSymbolFromJSDoc;
15208     function getHostSignatureFromJSDoc(node) {
15209         var host = getEffectiveJSDocHost(node);
15210         return host && ts.isFunctionLike(host) ? host : undefined;
15211     }
15212     ts.getHostSignatureFromJSDoc = getHostSignatureFromJSDoc;
15213     function getEffectiveJSDocHost(node) {
15214         var host = getJSDocHost(node);
15215         var decl = getSourceOfDefaultedAssignment(host) ||
15216             getSourceOfAssignment(host) ||
15217             getSingleInitializerOfVariableStatementOrPropertyDeclaration(host) ||
15218             getSingleVariableOfVariableStatement(host) ||
15219             getNestedModuleDeclaration(host) ||
15220             host;
15221         return decl;
15222     }
15223     ts.getEffectiveJSDocHost = getEffectiveJSDocHost;
15224     /** Use getEffectiveJSDocHost if you additionally need to look for jsdoc on parent nodes, like assignments.  */
15225     function getJSDocHost(node) {
15226         return ts.Debug.checkDefined(findAncestor(node.parent, ts.isJSDoc)).parent;
15227     }
15228     ts.getJSDocHost = getJSDocHost;
15229     function getTypeParameterFromJsDoc(node) {
15230         var name = node.name.escapedText;
15231         var typeParameters = node.parent.parent.parent.typeParameters;
15232         return typeParameters && ts.find(typeParameters, function (p) { return p.name.escapedText === name; });
15233     }
15234     ts.getTypeParameterFromJsDoc = getTypeParameterFromJsDoc;
15235     function hasRestParameter(s) {
15236         var last = ts.lastOrUndefined(s.parameters);
15237         return !!last && isRestParameter(last);
15238     }
15239     ts.hasRestParameter = hasRestParameter;
15240     function isRestParameter(node) {
15241         var type = ts.isJSDocParameterTag(node) ? (node.typeExpression && node.typeExpression.type) : node.type;
15242         return node.dotDotDotToken !== undefined || !!type && type.kind === 301 /* JSDocVariadicType */;
15243     }
15244     ts.isRestParameter = isRestParameter;
15245     function hasTypeArguments(node) {
15246         return !!node.typeArguments;
15247     }
15248     ts.hasTypeArguments = hasTypeArguments;
15249     var AssignmentKind;
15250     (function (AssignmentKind) {
15251         AssignmentKind[AssignmentKind["None"] = 0] = "None";
15252         AssignmentKind[AssignmentKind["Definite"] = 1] = "Definite";
15253         AssignmentKind[AssignmentKind["Compound"] = 2] = "Compound";
15254     })(AssignmentKind = ts.AssignmentKind || (ts.AssignmentKind = {}));
15255     function getAssignmentTargetKind(node) {
15256         var parent = node.parent;
15257         while (true) {
15258             switch (parent.kind) {
15259                 case 209 /* BinaryExpression */:
15260                     var binaryOperator = parent.operatorToken.kind;
15261                     return isAssignmentOperator(binaryOperator) && parent.left === node ?
15262                         binaryOperator === 62 /* EqualsToken */ ? 1 /* Definite */ : 2 /* Compound */ :
15263                         0 /* None */;
15264                 case 207 /* PrefixUnaryExpression */:
15265                 case 208 /* PostfixUnaryExpression */:
15266                     var unaryOperator = parent.operator;
15267                     return unaryOperator === 45 /* PlusPlusToken */ || unaryOperator === 46 /* MinusMinusToken */ ? 2 /* Compound */ : 0 /* None */;
15268                 case 231 /* ForInStatement */:
15269                 case 232 /* ForOfStatement */:
15270                     return parent.initializer === node ? 1 /* Definite */ : 0 /* None */;
15271                 case 200 /* ParenthesizedExpression */:
15272                 case 192 /* ArrayLiteralExpression */:
15273                 case 213 /* SpreadElement */:
15274                 case 218 /* NonNullExpression */:
15275                     node = parent;
15276                     break;
15277                 case 282 /* ShorthandPropertyAssignment */:
15278                     if (parent.name !== node) {
15279                         return 0 /* None */;
15280                     }
15281                     node = parent.parent;
15282                     break;
15283                 case 281 /* PropertyAssignment */:
15284                     if (parent.name === node) {
15285                         return 0 /* None */;
15286                     }
15287                     node = parent.parent;
15288                     break;
15289                 default:
15290                     return 0 /* None */;
15291             }
15292             parent = node.parent;
15293         }
15294     }
15295     ts.getAssignmentTargetKind = getAssignmentTargetKind;
15296     // A node is an assignment target if it is on the left hand side of an '=' token, if it is parented by a property
15297     // assignment in an object literal that is an assignment target, or if it is parented by an array literal that is
15298     // an assignment target. Examples include 'a = xxx', '{ p: a } = xxx', '[{ a }] = xxx'.
15299     // (Note that `p` is not a target in the above examples, only `a`.)
15300     function isAssignmentTarget(node) {
15301         return getAssignmentTargetKind(node) !== 0 /* None */;
15302     }
15303     ts.isAssignmentTarget = isAssignmentTarget;
15304     /**
15305      * Indicates whether a node could contain a `var` VariableDeclarationList that contributes to
15306      * the same `var` declaration scope as the node's parent.
15307      */
15308     function isNodeWithPossibleHoistedDeclaration(node) {
15309         switch (node.kind) {
15310             case 223 /* Block */:
15311             case 225 /* VariableStatement */:
15312             case 236 /* WithStatement */:
15313             case 227 /* IfStatement */:
15314             case 237 /* SwitchStatement */:
15315             case 251 /* CaseBlock */:
15316             case 277 /* CaseClause */:
15317             case 278 /* DefaultClause */:
15318             case 238 /* LabeledStatement */:
15319             case 230 /* ForStatement */:
15320             case 231 /* ForInStatement */:
15321             case 232 /* ForOfStatement */:
15322             case 228 /* DoStatement */:
15323             case 229 /* WhileStatement */:
15324             case 240 /* TryStatement */:
15325             case 280 /* CatchClause */:
15326                 return true;
15327         }
15328         return false;
15329     }
15330     ts.isNodeWithPossibleHoistedDeclaration = isNodeWithPossibleHoistedDeclaration;
15331     function isValueSignatureDeclaration(node) {
15332         return ts.isFunctionExpression(node) || ts.isArrowFunction(node) || ts.isMethodOrAccessor(node) || ts.isFunctionDeclaration(node) || ts.isConstructorDeclaration(node);
15333     }
15334     ts.isValueSignatureDeclaration = isValueSignatureDeclaration;
15335     function walkUp(node, kind) {
15336         while (node && node.kind === kind) {
15337             node = node.parent;
15338         }
15339         return node;
15340     }
15341     function walkUpParenthesizedTypes(node) {
15342         return walkUp(node, 182 /* ParenthesizedType */);
15343     }
15344     ts.walkUpParenthesizedTypes = walkUpParenthesizedTypes;
15345     function walkUpParenthesizedExpressions(node) {
15346         return walkUp(node, 200 /* ParenthesizedExpression */);
15347     }
15348     ts.walkUpParenthesizedExpressions = walkUpParenthesizedExpressions;
15349     function skipParentheses(node) {
15350         return ts.skipOuterExpressions(node, 1 /* Parentheses */);
15351     }
15352     ts.skipParentheses = skipParentheses;
15353     function skipParenthesesUp(node) {
15354         while (node.kind === 200 /* ParenthesizedExpression */) {
15355             node = node.parent;
15356         }
15357         return node;
15358     }
15359     // a node is delete target iff. it is PropertyAccessExpression/ElementAccessExpression with parentheses skipped
15360     function isDeleteTarget(node) {
15361         if (node.kind !== 194 /* PropertyAccessExpression */ && node.kind !== 195 /* ElementAccessExpression */) {
15362             return false;
15363         }
15364         node = walkUpParenthesizedExpressions(node.parent);
15365         return node && node.kind === 203 /* DeleteExpression */;
15366     }
15367     ts.isDeleteTarget = isDeleteTarget;
15368     function isNodeDescendantOf(node, ancestor) {
15369         while (node) {
15370             if (node === ancestor)
15371                 return true;
15372             node = node.parent;
15373         }
15374         return false;
15375     }
15376     ts.isNodeDescendantOf = isNodeDescendantOf;
15377     // True if `name` is the name of a declaration node
15378     function isDeclarationName(name) {
15379         return !ts.isSourceFile(name) && !ts.isBindingPattern(name) && ts.isDeclaration(name.parent) && name.parent.name === name;
15380     }
15381     ts.isDeclarationName = isDeclarationName;
15382     // See GH#16030
15383     function getDeclarationFromName(name) {
15384         var parent = name.parent;
15385         switch (name.kind) {
15386             case 10 /* StringLiteral */:
15387             case 14 /* NoSubstitutionTemplateLiteral */:
15388             case 8 /* NumericLiteral */:
15389                 if (ts.isComputedPropertyName(parent))
15390                     return parent.parent;
15391             // falls through
15392             case 75 /* Identifier */:
15393                 if (ts.isDeclaration(parent)) {
15394                     return parent.name === name ? parent : undefined;
15395                 }
15396                 else if (ts.isQualifiedName(parent)) {
15397                     var tag = parent.parent;
15398                     return ts.isJSDocParameterTag(tag) && tag.name === parent ? tag : undefined;
15399                 }
15400                 else {
15401                     var binExp = parent.parent;
15402                     return ts.isBinaryExpression(binExp) &&
15403                         getAssignmentDeclarationKind(binExp) !== 0 /* None */ &&
15404                         (binExp.left.symbol || binExp.symbol) &&
15405                         ts.getNameOfDeclaration(binExp) === name
15406                         ? binExp
15407                         : undefined;
15408                 }
15409             case 76 /* PrivateIdentifier */:
15410                 return ts.isDeclaration(parent) && parent.name === name ? parent : undefined;
15411             default:
15412                 return undefined;
15413         }
15414     }
15415     ts.getDeclarationFromName = getDeclarationFromName;
15416     function isLiteralComputedPropertyDeclarationName(node) {
15417         return isStringOrNumericLiteralLike(node) &&
15418             node.parent.kind === 154 /* ComputedPropertyName */ &&
15419             ts.isDeclaration(node.parent.parent);
15420     }
15421     ts.isLiteralComputedPropertyDeclarationName = isLiteralComputedPropertyDeclarationName;
15422     // Return true if the given identifier is classified as an IdentifierName
15423     function isIdentifierName(node) {
15424         var parent = node.parent;
15425         switch (parent.kind) {
15426             case 159 /* PropertyDeclaration */:
15427             case 158 /* PropertySignature */:
15428             case 161 /* MethodDeclaration */:
15429             case 160 /* MethodSignature */:
15430             case 163 /* GetAccessor */:
15431             case 164 /* SetAccessor */:
15432             case 284 /* EnumMember */:
15433             case 281 /* PropertyAssignment */:
15434             case 194 /* PropertyAccessExpression */:
15435                 // Name in member declaration or property name in property access
15436                 return parent.name === node;
15437             case 153 /* QualifiedName */:
15438                 // Name on right hand side of dot in a type query or type reference
15439                 if (parent.right === node) {
15440                     while (parent.kind === 153 /* QualifiedName */) {
15441                         parent = parent.parent;
15442                     }
15443                     return parent.kind === 172 /* TypeQuery */ || parent.kind === 169 /* TypeReference */;
15444                 }
15445                 return false;
15446             case 191 /* BindingElement */:
15447             case 258 /* ImportSpecifier */:
15448                 // Property name in binding element or import specifier
15449                 return parent.propertyName === node;
15450             case 263 /* ExportSpecifier */:
15451             case 273 /* JsxAttribute */:
15452                 // Any name in an export specifier or JSX Attribute
15453                 return true;
15454         }
15455         return false;
15456     }
15457     ts.isIdentifierName = isIdentifierName;
15458     // An alias symbol is created by one of the following declarations:
15459     // import <symbol> = ...
15460     // import <symbol> from ...
15461     // import * as <symbol> from ...
15462     // import { x as <symbol> } from ...
15463     // export { x as <symbol> } from ...
15464     // export * as ns <symbol> from ...
15465     // export = <EntityNameExpression>
15466     // export default <EntityNameExpression>
15467     // module.exports = <EntityNameExpression>
15468     // {<Identifier>}
15469     // {name: <EntityNameExpression>}
15470     function isAliasSymbolDeclaration(node) {
15471         return node.kind === 253 /* ImportEqualsDeclaration */ ||
15472             node.kind === 252 /* NamespaceExportDeclaration */ ||
15473             node.kind === 255 /* ImportClause */ && !!node.name ||
15474             node.kind === 256 /* NamespaceImport */ ||
15475             node.kind === 262 /* NamespaceExport */ ||
15476             node.kind === 258 /* ImportSpecifier */ ||
15477             node.kind === 263 /* ExportSpecifier */ ||
15478             node.kind === 259 /* ExportAssignment */ && exportAssignmentIsAlias(node) ||
15479             ts.isBinaryExpression(node) && getAssignmentDeclarationKind(node) === 2 /* ModuleExports */ && exportAssignmentIsAlias(node) ||
15480             ts.isPropertyAccessExpression(node) && ts.isBinaryExpression(node.parent) && node.parent.left === node && node.parent.operatorToken.kind === 62 /* EqualsToken */ && isAliasableExpression(node.parent.right) ||
15481             node.kind === 282 /* ShorthandPropertyAssignment */ ||
15482             node.kind === 281 /* PropertyAssignment */ && isAliasableExpression(node.initializer);
15483     }
15484     ts.isAliasSymbolDeclaration = isAliasSymbolDeclaration;
15485     function getAliasDeclarationFromName(node) {
15486         switch (node.parent.kind) {
15487             case 255 /* ImportClause */:
15488             case 258 /* ImportSpecifier */:
15489             case 256 /* NamespaceImport */:
15490             case 263 /* ExportSpecifier */:
15491             case 259 /* ExportAssignment */:
15492             case 253 /* ImportEqualsDeclaration */:
15493                 return node.parent;
15494             case 153 /* QualifiedName */:
15495                 do {
15496                     node = node.parent;
15497                 } while (node.parent.kind === 153 /* QualifiedName */);
15498                 return getAliasDeclarationFromName(node);
15499         }
15500     }
15501     ts.getAliasDeclarationFromName = getAliasDeclarationFromName;
15502     function isAliasableExpression(e) {
15503         return isEntityNameExpression(e) || ts.isClassExpression(e);
15504     }
15505     ts.isAliasableExpression = isAliasableExpression;
15506     function exportAssignmentIsAlias(node) {
15507         var e = getExportAssignmentExpression(node);
15508         return isAliasableExpression(e);
15509     }
15510     ts.exportAssignmentIsAlias = exportAssignmentIsAlias;
15511     function getExportAssignmentExpression(node) {
15512         return ts.isExportAssignment(node) ? node.expression : node.right;
15513     }
15514     ts.getExportAssignmentExpression = getExportAssignmentExpression;
15515     function getPropertyAssignmentAliasLikeExpression(node) {
15516         return node.kind === 282 /* ShorthandPropertyAssignment */ ? node.name : node.kind === 281 /* PropertyAssignment */ ? node.initializer :
15517             node.parent.right;
15518     }
15519     ts.getPropertyAssignmentAliasLikeExpression = getPropertyAssignmentAliasLikeExpression;
15520     function getEffectiveBaseTypeNode(node) {
15521         var baseType = getClassExtendsHeritageElement(node);
15522         if (baseType && isInJSFile(node)) {
15523             // Prefer an @augments tag because it may have type parameters.
15524             var tag = ts.getJSDocAugmentsTag(node);
15525             if (tag) {
15526                 return tag.class;
15527             }
15528         }
15529         return baseType;
15530     }
15531     ts.getEffectiveBaseTypeNode = getEffectiveBaseTypeNode;
15532     function getClassExtendsHeritageElement(node) {
15533         var heritageClause = getHeritageClause(node.heritageClauses, 90 /* ExtendsKeyword */);
15534         return heritageClause && heritageClause.types.length > 0 ? heritageClause.types[0] : undefined;
15535     }
15536     ts.getClassExtendsHeritageElement = getClassExtendsHeritageElement;
15537     function getEffectiveImplementsTypeNodes(node) {
15538         if (isInJSFile(node)) {
15539             return ts.getJSDocImplementsTags(node).map(function (n) { return n.class; });
15540         }
15541         else {
15542             var heritageClause = getHeritageClause(node.heritageClauses, 113 /* ImplementsKeyword */);
15543             return heritageClause === null || heritageClause === void 0 ? void 0 : heritageClause.types;
15544         }
15545     }
15546     ts.getEffectiveImplementsTypeNodes = getEffectiveImplementsTypeNodes;
15547     /** Returns the node in an `extends` or `implements` clause of a class or interface. */
15548     function getAllSuperTypeNodes(node) {
15549         return ts.isInterfaceDeclaration(node) ? getInterfaceBaseTypeNodes(node) || ts.emptyArray :
15550             ts.isClassLike(node) ? ts.concatenate(ts.singleElementArray(getEffectiveBaseTypeNode(node)), getEffectiveImplementsTypeNodes(node)) || ts.emptyArray :
15551                 ts.emptyArray;
15552     }
15553     ts.getAllSuperTypeNodes = getAllSuperTypeNodes;
15554     function getInterfaceBaseTypeNodes(node) {
15555         var heritageClause = getHeritageClause(node.heritageClauses, 90 /* ExtendsKeyword */);
15556         return heritageClause ? heritageClause.types : undefined;
15557     }
15558     ts.getInterfaceBaseTypeNodes = getInterfaceBaseTypeNodes;
15559     function getHeritageClause(clauses, kind) {
15560         if (clauses) {
15561             for (var _i = 0, clauses_1 = clauses; _i < clauses_1.length; _i++) {
15562                 var clause = clauses_1[_i];
15563                 if (clause.token === kind) {
15564                     return clause;
15565                 }
15566             }
15567         }
15568         return undefined;
15569     }
15570     ts.getHeritageClause = getHeritageClause;
15571     function getAncestor(node, kind) {
15572         while (node) {
15573             if (node.kind === kind) {
15574                 return node;
15575             }
15576             node = node.parent;
15577         }
15578         return undefined;
15579     }
15580     ts.getAncestor = getAncestor;
15581     function isKeyword(token) {
15582         return 77 /* FirstKeyword */ <= token && token <= 152 /* LastKeyword */;
15583     }
15584     ts.isKeyword = isKeyword;
15585     function isContextualKeyword(token) {
15586         return 122 /* FirstContextualKeyword */ <= token && token <= 152 /* LastContextualKeyword */;
15587     }
15588     ts.isContextualKeyword = isContextualKeyword;
15589     function isNonContextualKeyword(token) {
15590         return isKeyword(token) && !isContextualKeyword(token);
15591     }
15592     ts.isNonContextualKeyword = isNonContextualKeyword;
15593     function isFutureReservedKeyword(token) {
15594         return 113 /* FirstFutureReservedWord */ <= token && token <= 121 /* LastFutureReservedWord */;
15595     }
15596     ts.isFutureReservedKeyword = isFutureReservedKeyword;
15597     function isStringANonContextualKeyword(name) {
15598         var token = ts.stringToToken(name);
15599         return token !== undefined && isNonContextualKeyword(token);
15600     }
15601     ts.isStringANonContextualKeyword = isStringANonContextualKeyword;
15602     function isStringAKeyword(name) {
15603         var token = ts.stringToToken(name);
15604         return token !== undefined && isKeyword(token);
15605     }
15606     ts.isStringAKeyword = isStringAKeyword;
15607     function isIdentifierANonContextualKeyword(_a) {
15608         var originalKeywordKind = _a.originalKeywordKind;
15609         return !!originalKeywordKind && !isContextualKeyword(originalKeywordKind);
15610     }
15611     ts.isIdentifierANonContextualKeyword = isIdentifierANonContextualKeyword;
15612     function isTrivia(token) {
15613         return 2 /* FirstTriviaToken */ <= token && token <= 7 /* LastTriviaToken */;
15614     }
15615     ts.isTrivia = isTrivia;
15616     var FunctionFlags;
15617     (function (FunctionFlags) {
15618         FunctionFlags[FunctionFlags["Normal"] = 0] = "Normal";
15619         FunctionFlags[FunctionFlags["Generator"] = 1] = "Generator";
15620         FunctionFlags[FunctionFlags["Async"] = 2] = "Async";
15621         FunctionFlags[FunctionFlags["Invalid"] = 4] = "Invalid";
15622         FunctionFlags[FunctionFlags["AsyncGenerator"] = 3] = "AsyncGenerator";
15623     })(FunctionFlags = ts.FunctionFlags || (ts.FunctionFlags = {}));
15624     function getFunctionFlags(node) {
15625         if (!node) {
15626             return 4 /* Invalid */;
15627         }
15628         var flags = 0 /* Normal */;
15629         switch (node.kind) {
15630             case 244 /* FunctionDeclaration */:
15631             case 201 /* FunctionExpression */:
15632             case 161 /* MethodDeclaration */:
15633                 if (node.asteriskToken) {
15634                     flags |= 1 /* Generator */;
15635                 }
15636             // falls through
15637             case 202 /* ArrowFunction */:
15638                 if (hasModifier(node, 256 /* Async */)) {
15639                     flags |= 2 /* Async */;
15640                 }
15641                 break;
15642         }
15643         if (!node.body) {
15644             flags |= 4 /* Invalid */;
15645         }
15646         return flags;
15647     }
15648     ts.getFunctionFlags = getFunctionFlags;
15649     function isAsyncFunction(node) {
15650         switch (node.kind) {
15651             case 244 /* FunctionDeclaration */:
15652             case 201 /* FunctionExpression */:
15653             case 202 /* ArrowFunction */:
15654             case 161 /* MethodDeclaration */:
15655                 return node.body !== undefined
15656                     && node.asteriskToken === undefined
15657                     && hasModifier(node, 256 /* Async */);
15658         }
15659         return false;
15660     }
15661     ts.isAsyncFunction = isAsyncFunction;
15662     function isStringOrNumericLiteralLike(node) {
15663         return ts.isStringLiteralLike(node) || ts.isNumericLiteral(node);
15664     }
15665     ts.isStringOrNumericLiteralLike = isStringOrNumericLiteralLike;
15666     function isSignedNumericLiteral(node) {
15667         return ts.isPrefixUnaryExpression(node) && (node.operator === 39 /* PlusToken */ || node.operator === 40 /* MinusToken */) && ts.isNumericLiteral(node.operand);
15668     }
15669     ts.isSignedNumericLiteral = isSignedNumericLiteral;
15670     /**
15671      * A declaration has a dynamic name if all of the following are true:
15672      *   1. The declaration has a computed property name.
15673      *   2. The computed name is *not* expressed as a StringLiteral.
15674      *   3. The computed name is *not* expressed as a NumericLiteral.
15675      *   4. The computed name is *not* expressed as a PlusToken or MinusToken
15676      *      immediately followed by a NumericLiteral.
15677      *   5. The computed name is *not* expressed as `Symbol.<name>`, where `<name>`
15678      *      is a property of the Symbol constructor that denotes a built-in
15679      *      Symbol.
15680      */
15681     function hasDynamicName(declaration) {
15682         var name = ts.getNameOfDeclaration(declaration);
15683         return !!name && isDynamicName(name);
15684     }
15685     ts.hasDynamicName = hasDynamicName;
15686     function isDynamicName(name) {
15687         if (!(name.kind === 154 /* ComputedPropertyName */ || name.kind === 195 /* ElementAccessExpression */)) {
15688             return false;
15689         }
15690         var expr = ts.isElementAccessExpression(name) ? skipParentheses(name.argumentExpression) : name.expression;
15691         return !isStringOrNumericLiteralLike(expr) &&
15692             !isSignedNumericLiteral(expr) &&
15693             !isWellKnownSymbolSyntactically(expr);
15694     }
15695     ts.isDynamicName = isDynamicName;
15696     /**
15697      * Checks if the expression is of the form:
15698      *    Symbol.name
15699      * where Symbol is literally the word "Symbol", and name is any identifierName
15700      */
15701     function isWellKnownSymbolSyntactically(node) {
15702         return ts.isPropertyAccessExpression(node) && isESSymbolIdentifier(node.expression);
15703     }
15704     ts.isWellKnownSymbolSyntactically = isWellKnownSymbolSyntactically;
15705     function getPropertyNameForPropertyNameNode(name) {
15706         switch (name.kind) {
15707             case 75 /* Identifier */:
15708             case 76 /* PrivateIdentifier */:
15709                 return name.escapedText;
15710             case 10 /* StringLiteral */:
15711             case 8 /* NumericLiteral */:
15712                 return ts.escapeLeadingUnderscores(name.text);
15713             case 154 /* ComputedPropertyName */:
15714                 var nameExpression = name.expression;
15715                 if (isWellKnownSymbolSyntactically(nameExpression)) {
15716                     return getPropertyNameForKnownSymbolName(ts.idText(nameExpression.name));
15717                 }
15718                 else if (isStringOrNumericLiteralLike(nameExpression)) {
15719                     return ts.escapeLeadingUnderscores(nameExpression.text);
15720                 }
15721                 return undefined;
15722             default:
15723                 return ts.Debug.assertNever(name);
15724         }
15725     }
15726     ts.getPropertyNameForPropertyNameNode = getPropertyNameForPropertyNameNode;
15727     function isPropertyNameLiteral(node) {
15728         switch (node.kind) {
15729             case 75 /* Identifier */:
15730             case 10 /* StringLiteral */:
15731             case 14 /* NoSubstitutionTemplateLiteral */:
15732             case 8 /* NumericLiteral */:
15733                 return true;
15734             default:
15735                 return false;
15736         }
15737     }
15738     ts.isPropertyNameLiteral = isPropertyNameLiteral;
15739     function getTextOfIdentifierOrLiteral(node) {
15740         return ts.isIdentifierOrPrivateIdentifier(node) ? ts.idText(node) : node.text;
15741     }
15742     ts.getTextOfIdentifierOrLiteral = getTextOfIdentifierOrLiteral;
15743     function getEscapedTextOfIdentifierOrLiteral(node) {
15744         return ts.isIdentifierOrPrivateIdentifier(node) ? node.escapedText : ts.escapeLeadingUnderscores(node.text);
15745     }
15746     ts.getEscapedTextOfIdentifierOrLiteral = getEscapedTextOfIdentifierOrLiteral;
15747     function getPropertyNameForUniqueESSymbol(symbol) {
15748         return "__@" + ts.getSymbolId(symbol) + "@" + symbol.escapedName;
15749     }
15750     ts.getPropertyNameForUniqueESSymbol = getPropertyNameForUniqueESSymbol;
15751     function getPropertyNameForKnownSymbolName(symbolName) {
15752         return "__@" + symbolName;
15753     }
15754     ts.getPropertyNameForKnownSymbolName = getPropertyNameForKnownSymbolName;
15755     function getSymbolNameForPrivateIdentifier(containingClassSymbol, description) {
15756         return "__#" + ts.getSymbolId(containingClassSymbol) + "@" + description;
15757     }
15758     ts.getSymbolNameForPrivateIdentifier = getSymbolNameForPrivateIdentifier;
15759     function isKnownSymbol(symbol) {
15760         return ts.startsWith(symbol.escapedName, "__@");
15761     }
15762     ts.isKnownSymbol = isKnownSymbol;
15763     /**
15764      * Includes the word "Symbol" with unicode escapes
15765      */
15766     function isESSymbolIdentifier(node) {
15767         return node.kind === 75 /* Identifier */ && node.escapedText === "Symbol";
15768     }
15769     ts.isESSymbolIdentifier = isESSymbolIdentifier;
15770     function isPushOrUnshiftIdentifier(node) {
15771         return node.escapedText === "push" || node.escapedText === "unshift";
15772     }
15773     ts.isPushOrUnshiftIdentifier = isPushOrUnshiftIdentifier;
15774     function isParameterDeclaration(node) {
15775         var root = getRootDeclaration(node);
15776         return root.kind === 156 /* Parameter */;
15777     }
15778     ts.isParameterDeclaration = isParameterDeclaration;
15779     function getRootDeclaration(node) {
15780         while (node.kind === 191 /* BindingElement */) {
15781             node = node.parent.parent;
15782         }
15783         return node;
15784     }
15785     ts.getRootDeclaration = getRootDeclaration;
15786     function nodeStartsNewLexicalEnvironment(node) {
15787         var kind = node.kind;
15788         return kind === 162 /* Constructor */
15789             || kind === 201 /* FunctionExpression */
15790             || kind === 244 /* FunctionDeclaration */
15791             || kind === 202 /* ArrowFunction */
15792             || kind === 161 /* MethodDeclaration */
15793             || kind === 163 /* GetAccessor */
15794             || kind === 164 /* SetAccessor */
15795             || kind === 249 /* ModuleDeclaration */
15796             || kind === 290 /* SourceFile */;
15797     }
15798     ts.nodeStartsNewLexicalEnvironment = nodeStartsNewLexicalEnvironment;
15799     function nodeIsSynthesized(range) {
15800         return positionIsSynthesized(range.pos)
15801             || positionIsSynthesized(range.end);
15802     }
15803     ts.nodeIsSynthesized = nodeIsSynthesized;
15804     function getOriginalSourceFile(sourceFile) {
15805         return ts.getParseTreeNode(sourceFile, ts.isSourceFile) || sourceFile;
15806     }
15807     ts.getOriginalSourceFile = getOriginalSourceFile;
15808     var Associativity;
15809     (function (Associativity) {
15810         Associativity[Associativity["Left"] = 0] = "Left";
15811         Associativity[Associativity["Right"] = 1] = "Right";
15812     })(Associativity = ts.Associativity || (ts.Associativity = {}));
15813     function getExpressionAssociativity(expression) {
15814         var operator = getOperator(expression);
15815         var hasArguments = expression.kind === 197 /* NewExpression */ && expression.arguments !== undefined;
15816         return getOperatorAssociativity(expression.kind, operator, hasArguments);
15817     }
15818     ts.getExpressionAssociativity = getExpressionAssociativity;
15819     function getOperatorAssociativity(kind, operator, hasArguments) {
15820         switch (kind) {
15821             case 197 /* NewExpression */:
15822                 return hasArguments ? 0 /* Left */ : 1 /* Right */;
15823             case 207 /* PrefixUnaryExpression */:
15824             case 204 /* TypeOfExpression */:
15825             case 205 /* VoidExpression */:
15826             case 203 /* DeleteExpression */:
15827             case 206 /* AwaitExpression */:
15828             case 210 /* ConditionalExpression */:
15829             case 212 /* YieldExpression */:
15830                 return 1 /* Right */;
15831             case 209 /* BinaryExpression */:
15832                 switch (operator) {
15833                     case 42 /* AsteriskAsteriskToken */:
15834                     case 62 /* EqualsToken */:
15835                     case 63 /* PlusEqualsToken */:
15836                     case 64 /* MinusEqualsToken */:
15837                     case 66 /* AsteriskAsteriskEqualsToken */:
15838                     case 65 /* AsteriskEqualsToken */:
15839                     case 67 /* SlashEqualsToken */:
15840                     case 68 /* PercentEqualsToken */:
15841                     case 69 /* LessThanLessThanEqualsToken */:
15842                     case 70 /* GreaterThanGreaterThanEqualsToken */:
15843                     case 71 /* GreaterThanGreaterThanGreaterThanEqualsToken */:
15844                     case 72 /* AmpersandEqualsToken */:
15845                     case 74 /* CaretEqualsToken */:
15846                     case 73 /* BarEqualsToken */:
15847                         return 1 /* Right */;
15848                 }
15849         }
15850         return 0 /* Left */;
15851     }
15852     ts.getOperatorAssociativity = getOperatorAssociativity;
15853     function getExpressionPrecedence(expression) {
15854         var operator = getOperator(expression);
15855         var hasArguments = expression.kind === 197 /* NewExpression */ && expression.arguments !== undefined;
15856         return getOperatorPrecedence(expression.kind, operator, hasArguments);
15857     }
15858     ts.getExpressionPrecedence = getExpressionPrecedence;
15859     function getOperator(expression) {
15860         if (expression.kind === 209 /* BinaryExpression */) {
15861             return expression.operatorToken.kind;
15862         }
15863         else if (expression.kind === 207 /* PrefixUnaryExpression */ || expression.kind === 208 /* PostfixUnaryExpression */) {
15864             return expression.operator;
15865         }
15866         else {
15867             return expression.kind;
15868         }
15869     }
15870     ts.getOperator = getOperator;
15871     function getOperatorPrecedence(nodeKind, operatorKind, hasArguments) {
15872         switch (nodeKind) {
15873             case 327 /* CommaListExpression */:
15874                 return 0;
15875             case 213 /* SpreadElement */:
15876                 return 1;
15877             case 212 /* YieldExpression */:
15878                 return 2;
15879             case 210 /* ConditionalExpression */:
15880                 return 4;
15881             case 209 /* BinaryExpression */:
15882                 switch (operatorKind) {
15883                     case 27 /* CommaToken */:
15884                         return 0;
15885                     case 62 /* EqualsToken */:
15886                     case 63 /* PlusEqualsToken */:
15887                     case 64 /* MinusEqualsToken */:
15888                     case 66 /* AsteriskAsteriskEqualsToken */:
15889                     case 65 /* AsteriskEqualsToken */:
15890                     case 67 /* SlashEqualsToken */:
15891                     case 68 /* PercentEqualsToken */:
15892                     case 69 /* LessThanLessThanEqualsToken */:
15893                     case 70 /* GreaterThanGreaterThanEqualsToken */:
15894                     case 71 /* GreaterThanGreaterThanGreaterThanEqualsToken */:
15895                     case 72 /* AmpersandEqualsToken */:
15896                     case 74 /* CaretEqualsToken */:
15897                     case 73 /* BarEqualsToken */:
15898                         return 3;
15899                     default:
15900                         return getBinaryOperatorPrecedence(operatorKind);
15901                 }
15902             case 207 /* PrefixUnaryExpression */:
15903             case 204 /* TypeOfExpression */:
15904             case 205 /* VoidExpression */:
15905             case 203 /* DeleteExpression */:
15906             case 206 /* AwaitExpression */:
15907                 return 16;
15908             case 208 /* PostfixUnaryExpression */:
15909                 return 17;
15910             case 196 /* CallExpression */:
15911                 return 18;
15912             case 197 /* NewExpression */:
15913                 return hasArguments ? 19 : 18;
15914             case 198 /* TaggedTemplateExpression */:
15915             case 194 /* PropertyAccessExpression */:
15916             case 195 /* ElementAccessExpression */:
15917                 return 19;
15918             case 104 /* ThisKeyword */:
15919             case 102 /* SuperKeyword */:
15920             case 75 /* Identifier */:
15921             case 100 /* NullKeyword */:
15922             case 106 /* TrueKeyword */:
15923             case 91 /* FalseKeyword */:
15924             case 8 /* NumericLiteral */:
15925             case 9 /* BigIntLiteral */:
15926             case 10 /* StringLiteral */:
15927             case 192 /* ArrayLiteralExpression */:
15928             case 193 /* ObjectLiteralExpression */:
15929             case 201 /* FunctionExpression */:
15930             case 202 /* ArrowFunction */:
15931             case 214 /* ClassExpression */:
15932             case 266 /* JsxElement */:
15933             case 267 /* JsxSelfClosingElement */:
15934             case 270 /* JsxFragment */:
15935             case 13 /* RegularExpressionLiteral */:
15936             case 14 /* NoSubstitutionTemplateLiteral */:
15937             case 211 /* TemplateExpression */:
15938             case 200 /* ParenthesizedExpression */:
15939             case 215 /* OmittedExpression */:
15940                 return 20;
15941             default:
15942                 return -1;
15943         }
15944     }
15945     ts.getOperatorPrecedence = getOperatorPrecedence;
15946     function getBinaryOperatorPrecedence(kind) {
15947         switch (kind) {
15948             case 60 /* QuestionQuestionToken */:
15949                 return 4;
15950             case 56 /* BarBarToken */:
15951                 return 5;
15952             case 55 /* AmpersandAmpersandToken */:
15953                 return 6;
15954             case 51 /* BarToken */:
15955                 return 7;
15956             case 52 /* CaretToken */:
15957                 return 8;
15958             case 50 /* AmpersandToken */:
15959                 return 9;
15960             case 34 /* EqualsEqualsToken */:
15961             case 35 /* ExclamationEqualsToken */:
15962             case 36 /* EqualsEqualsEqualsToken */:
15963             case 37 /* ExclamationEqualsEqualsToken */:
15964                 return 10;
15965             case 29 /* LessThanToken */:
15966             case 31 /* GreaterThanToken */:
15967             case 32 /* LessThanEqualsToken */:
15968             case 33 /* GreaterThanEqualsToken */:
15969             case 98 /* InstanceOfKeyword */:
15970             case 97 /* InKeyword */:
15971             case 123 /* AsKeyword */:
15972                 return 11;
15973             case 47 /* LessThanLessThanToken */:
15974             case 48 /* GreaterThanGreaterThanToken */:
15975             case 49 /* GreaterThanGreaterThanGreaterThanToken */:
15976                 return 12;
15977             case 39 /* PlusToken */:
15978             case 40 /* MinusToken */:
15979                 return 13;
15980             case 41 /* AsteriskToken */:
15981             case 43 /* SlashToken */:
15982             case 44 /* PercentToken */:
15983                 return 14;
15984             case 42 /* AsteriskAsteriskToken */:
15985                 return 15;
15986         }
15987         // -1 is lower than all other precedences.  Returning it will cause binary expression
15988         // parsing to stop.
15989         return -1;
15990     }
15991     ts.getBinaryOperatorPrecedence = getBinaryOperatorPrecedence;
15992     function createDiagnosticCollection() {
15993         var nonFileDiagnostics = []; // See GH#19873
15994         var filesWithDiagnostics = [];
15995         var fileDiagnostics = ts.createMap();
15996         var hasReadNonFileDiagnostics = false;
15997         return {
15998             add: add,
15999             lookup: lookup,
16000             getGlobalDiagnostics: getGlobalDiagnostics,
16001             getDiagnostics: getDiagnostics,
16002             reattachFileDiagnostics: reattachFileDiagnostics
16003         };
16004         function reattachFileDiagnostics(newFile) {
16005             ts.forEach(fileDiagnostics.get(newFile.fileName), function (diagnostic) { return diagnostic.file = newFile; });
16006         }
16007         function lookup(diagnostic) {
16008             var diagnostics;
16009             if (diagnostic.file) {
16010                 diagnostics = fileDiagnostics.get(diagnostic.file.fileName);
16011             }
16012             else {
16013                 diagnostics = nonFileDiagnostics;
16014             }
16015             if (!diagnostics) {
16016                 return undefined;
16017             }
16018             var result = ts.binarySearch(diagnostics, diagnostic, ts.identity, compareDiagnosticsSkipRelatedInformation);
16019             if (result >= 0) {
16020                 return diagnostics[result];
16021             }
16022             return undefined;
16023         }
16024         function add(diagnostic) {
16025             var diagnostics;
16026             if (diagnostic.file) {
16027                 diagnostics = fileDiagnostics.get(diagnostic.file.fileName);
16028                 if (!diagnostics) {
16029                     diagnostics = []; // See GH#19873
16030                     fileDiagnostics.set(diagnostic.file.fileName, diagnostics);
16031                     ts.insertSorted(filesWithDiagnostics, diagnostic.file.fileName, ts.compareStringsCaseSensitive);
16032                 }
16033             }
16034             else {
16035                 // If we've already read the non-file diagnostics, do not modify the existing array.
16036                 if (hasReadNonFileDiagnostics) {
16037                     hasReadNonFileDiagnostics = false;
16038                     nonFileDiagnostics = nonFileDiagnostics.slice();
16039                 }
16040                 diagnostics = nonFileDiagnostics;
16041             }
16042             ts.insertSorted(diagnostics, diagnostic, compareDiagnostics);
16043         }
16044         function getGlobalDiagnostics() {
16045             hasReadNonFileDiagnostics = true;
16046             return nonFileDiagnostics;
16047         }
16048         function getDiagnostics(fileName) {
16049             if (fileName) {
16050                 return fileDiagnostics.get(fileName) || [];
16051             }
16052             var fileDiags = ts.flatMapToMutable(filesWithDiagnostics, function (f) { return fileDiagnostics.get(f); });
16053             if (!nonFileDiagnostics.length) {
16054                 return fileDiags;
16055             }
16056             fileDiags.unshift.apply(fileDiags, nonFileDiagnostics);
16057             return fileDiags;
16058         }
16059     }
16060     ts.createDiagnosticCollection = createDiagnosticCollection;
16061     var templateSubstitutionRegExp = /\$\{/g;
16062     function escapeTemplateSubstitution(str) {
16063         return str.replace(templateSubstitutionRegExp, "\\${");
16064     }
16065     /** @internal */
16066     function hasInvalidEscape(template) {
16067         return template && !!(ts.isNoSubstitutionTemplateLiteral(template)
16068             ? template.templateFlags
16069             : (template.head.templateFlags || ts.some(template.templateSpans, function (span) { return !!span.literal.templateFlags; })));
16070     }
16071     ts.hasInvalidEscape = hasInvalidEscape;
16072     // This consists of the first 19 unprintable ASCII characters, canonical escapes, lineSeparator,
16073     // paragraphSeparator, and nextLine. The latter three are just desirable to suppress new lines in
16074     // the language service. These characters should be escaped when printing, and if any characters are added,
16075     // the map below must be updated. Note that this regexp *does not* include the 'delete' character.
16076     // There is no reason for this other than that JSON.stringify does not handle it either.
16077     var doubleQuoteEscapedCharsRegExp = /[\\\"\u0000-\u001f\t\v\f\b\r\n\u2028\u2029\u0085]/g;
16078     var singleQuoteEscapedCharsRegExp = /[\\\'\u0000-\u001f\t\v\f\b\r\n\u2028\u2029\u0085]/g;
16079     // Template strings should be preserved as much as possible
16080     var backtickQuoteEscapedCharsRegExp = /[\\`]/g;
16081     var escapedCharsMap = ts.createMapFromTemplate({
16082         "\t": "\\t",
16083         "\v": "\\v",
16084         "\f": "\\f",
16085         "\b": "\\b",
16086         "\r": "\\r",
16087         "\n": "\\n",
16088         "\\": "\\\\",
16089         "\"": "\\\"",
16090         "\'": "\\\'",
16091         "\`": "\\\`",
16092         "\u2028": "\\u2028",
16093         "\u2029": "\\u2029",
16094         "\u0085": "\\u0085" // nextLine
16095     });
16096     function encodeUtf16EscapeSequence(charCode) {
16097         var hexCharCode = charCode.toString(16).toUpperCase();
16098         var paddedHexCode = ("0000" + hexCharCode).slice(-4);
16099         return "\\u" + paddedHexCode;
16100     }
16101     function getReplacement(c, offset, input) {
16102         if (c.charCodeAt(0) === 0 /* nullCharacter */) {
16103             var lookAhead = input.charCodeAt(offset + c.length);
16104             if (lookAhead >= 48 /* _0 */ && lookAhead <= 57 /* _9 */) {
16105                 // 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)
16106                 return "\\x00";
16107             }
16108             // Otherwise, keep printing a literal \0 for the null character
16109             return "\\0";
16110         }
16111         return escapedCharsMap.get(c) || encodeUtf16EscapeSequence(c.charCodeAt(0));
16112     }
16113     /**
16114      * Based heavily on the abstract 'Quote'/'QuoteJSONString' operation from ECMA-262 (24.3.2.2),
16115      * but augmented for a few select characters (e.g. lineSeparator, paragraphSeparator, nextLine)
16116      * Note that this doesn't actually wrap the input in double quotes.
16117      */
16118     function escapeString(s, quoteChar) {
16119         var escapedCharsRegExp = quoteChar === 96 /* backtick */ ? backtickQuoteEscapedCharsRegExp :
16120             quoteChar === 39 /* singleQuote */ ? singleQuoteEscapedCharsRegExp :
16121                 doubleQuoteEscapedCharsRegExp;
16122         return s.replace(escapedCharsRegExp, getReplacement);
16123     }
16124     ts.escapeString = escapeString;
16125     var nonAsciiCharacters = /[^\u0000-\u007F]/g;
16126     function escapeNonAsciiString(s, quoteChar) {
16127         s = escapeString(s, quoteChar);
16128         // Replace non-ASCII characters with '\uNNNN' escapes if any exist.
16129         // Otherwise just return the original string.
16130         return nonAsciiCharacters.test(s) ?
16131             s.replace(nonAsciiCharacters, function (c) { return encodeUtf16EscapeSequence(c.charCodeAt(0)); }) :
16132             s;
16133     }
16134     ts.escapeNonAsciiString = escapeNonAsciiString;
16135     // This consists of the first 19 unprintable ASCII characters, JSX canonical escapes, lineSeparator,
16136     // paragraphSeparator, and nextLine. The latter three are just desirable to suppress new lines in
16137     // the language service. These characters should be escaped when printing, and if any characters are added,
16138     // the map below must be updated.
16139     var jsxDoubleQuoteEscapedCharsRegExp = /[\"\u0000-\u001f\u2028\u2029\u0085]/g;
16140     var jsxSingleQuoteEscapedCharsRegExp = /[\'\u0000-\u001f\u2028\u2029\u0085]/g;
16141     var jsxEscapedCharsMap = ts.createMapFromTemplate({
16142         "\"": "&quot;",
16143         "\'": "&apos;"
16144     });
16145     function encodeJsxCharacterEntity(charCode) {
16146         var hexCharCode = charCode.toString(16).toUpperCase();
16147         return "&#x" + hexCharCode + ";";
16148     }
16149     function getJsxAttributeStringReplacement(c) {
16150         if (c.charCodeAt(0) === 0 /* nullCharacter */) {
16151             return "&#0;";
16152         }
16153         return jsxEscapedCharsMap.get(c) || encodeJsxCharacterEntity(c.charCodeAt(0));
16154     }
16155     function escapeJsxAttributeString(s, quoteChar) {
16156         var escapedCharsRegExp = quoteChar === 39 /* singleQuote */ ? jsxSingleQuoteEscapedCharsRegExp :
16157             jsxDoubleQuoteEscapedCharsRegExp;
16158         return s.replace(escapedCharsRegExp, getJsxAttributeStringReplacement);
16159     }
16160     ts.escapeJsxAttributeString = escapeJsxAttributeString;
16161     /**
16162      * Strip off existed surrounding single quotes, double quotes, or backticks from a given string
16163      *
16164      * @return non-quoted string
16165      */
16166     function stripQuotes(name) {
16167         var length = name.length;
16168         if (length >= 2 && name.charCodeAt(0) === name.charCodeAt(length - 1) && isQuoteOrBacktick(name.charCodeAt(0))) {
16169             return name.substring(1, length - 1);
16170         }
16171         return name;
16172     }
16173     ts.stripQuotes = stripQuotes;
16174     function isQuoteOrBacktick(charCode) {
16175         return charCode === 39 /* singleQuote */ ||
16176             charCode === 34 /* doubleQuote */ ||
16177             charCode === 96 /* backtick */;
16178     }
16179     function isIntrinsicJsxName(name) {
16180         var ch = name.charCodeAt(0);
16181         return (ch >= 97 /* a */ && ch <= 122 /* z */) || ts.stringContains(name, "-");
16182     }
16183     ts.isIntrinsicJsxName = isIntrinsicJsxName;
16184     var indentStrings = ["", "    "];
16185     function getIndentString(level) {
16186         if (indentStrings[level] === undefined) {
16187             indentStrings[level] = getIndentString(level - 1) + indentStrings[1];
16188         }
16189         return indentStrings[level];
16190     }
16191     ts.getIndentString = getIndentString;
16192     function getIndentSize() {
16193         return indentStrings[1].length;
16194     }
16195     ts.getIndentSize = getIndentSize;
16196     function createTextWriter(newLine) {
16197         var output;
16198         var indent;
16199         var lineStart;
16200         var lineCount;
16201         var linePos;
16202         var hasTrailingComment = false;
16203         function updateLineCountAndPosFor(s) {
16204             var lineStartsOfS = ts.computeLineStarts(s);
16205             if (lineStartsOfS.length > 1) {
16206                 lineCount = lineCount + lineStartsOfS.length - 1;
16207                 linePos = output.length - s.length + ts.last(lineStartsOfS);
16208                 lineStart = (linePos - output.length) === 0;
16209             }
16210             else {
16211                 lineStart = false;
16212             }
16213         }
16214         function writeText(s) {
16215             if (s && s.length) {
16216                 if (lineStart) {
16217                     s = getIndentString(indent) + s;
16218                     lineStart = false;
16219                 }
16220                 output += s;
16221                 updateLineCountAndPosFor(s);
16222             }
16223         }
16224         function write(s) {
16225             if (s)
16226                 hasTrailingComment = false;
16227             writeText(s);
16228         }
16229         function writeComment(s) {
16230             if (s)
16231                 hasTrailingComment = true;
16232             writeText(s);
16233         }
16234         function reset() {
16235             output = "";
16236             indent = 0;
16237             lineStart = true;
16238             lineCount = 0;
16239             linePos = 0;
16240             hasTrailingComment = false;
16241         }
16242         function rawWrite(s) {
16243             if (s !== undefined) {
16244                 output += s;
16245                 updateLineCountAndPosFor(s);
16246                 hasTrailingComment = false;
16247             }
16248         }
16249         function writeLiteral(s) {
16250             if (s && s.length) {
16251                 write(s);
16252             }
16253         }
16254         function writeLine(force) {
16255             if (!lineStart || force) {
16256                 output += newLine;
16257                 lineCount++;
16258                 linePos = output.length;
16259                 lineStart = true;
16260                 hasTrailingComment = false;
16261             }
16262         }
16263         function getTextPosWithWriteLine() {
16264             return lineStart ? output.length : (output.length + newLine.length);
16265         }
16266         reset();
16267         return {
16268             write: write,
16269             rawWrite: rawWrite,
16270             writeLiteral: writeLiteral,
16271             writeLine: writeLine,
16272             increaseIndent: function () { indent++; },
16273             decreaseIndent: function () { indent--; },
16274             getIndent: function () { return indent; },
16275             getTextPos: function () { return output.length; },
16276             getLine: function () { return lineCount; },
16277             getColumn: function () { return lineStart ? indent * getIndentSize() : output.length - linePos; },
16278             getText: function () { return output; },
16279             isAtStartOfLine: function () { return lineStart; },
16280             hasTrailingComment: function () { return hasTrailingComment; },
16281             hasTrailingWhitespace: function () { return !!output.length && ts.isWhiteSpaceLike(output.charCodeAt(output.length - 1)); },
16282             clear: reset,
16283             reportInaccessibleThisError: ts.noop,
16284             reportPrivateInBaseOfClassExpression: ts.noop,
16285             reportInaccessibleUniqueSymbolError: ts.noop,
16286             trackSymbol: ts.noop,
16287             writeKeyword: write,
16288             writeOperator: write,
16289             writeParameter: write,
16290             writeProperty: write,
16291             writePunctuation: write,
16292             writeSpace: write,
16293             writeStringLiteral: write,
16294             writeSymbol: function (s, _) { return write(s); },
16295             writeTrailingSemicolon: write,
16296             writeComment: writeComment,
16297             getTextPosWithWriteLine: getTextPosWithWriteLine
16298         };
16299     }
16300     ts.createTextWriter = createTextWriter;
16301     function getTrailingSemicolonDeferringWriter(writer) {
16302         var pendingTrailingSemicolon = false;
16303         function commitPendingTrailingSemicolon() {
16304             if (pendingTrailingSemicolon) {
16305                 writer.writeTrailingSemicolon(";");
16306                 pendingTrailingSemicolon = false;
16307             }
16308         }
16309         return __assign(__assign({}, writer), { writeTrailingSemicolon: function () {
16310                 pendingTrailingSemicolon = true;
16311             },
16312             writeLiteral: function (s) {
16313                 commitPendingTrailingSemicolon();
16314                 writer.writeLiteral(s);
16315             },
16316             writeStringLiteral: function (s) {
16317                 commitPendingTrailingSemicolon();
16318                 writer.writeStringLiteral(s);
16319             },
16320             writeSymbol: function (s, sym) {
16321                 commitPendingTrailingSemicolon();
16322                 writer.writeSymbol(s, sym);
16323             },
16324             writePunctuation: function (s) {
16325                 commitPendingTrailingSemicolon();
16326                 writer.writePunctuation(s);
16327             },
16328             writeKeyword: function (s) {
16329                 commitPendingTrailingSemicolon();
16330                 writer.writeKeyword(s);
16331             },
16332             writeOperator: function (s) {
16333                 commitPendingTrailingSemicolon();
16334                 writer.writeOperator(s);
16335             },
16336             writeParameter: function (s) {
16337                 commitPendingTrailingSemicolon();
16338                 writer.writeParameter(s);
16339             },
16340             writeSpace: function (s) {
16341                 commitPendingTrailingSemicolon();
16342                 writer.writeSpace(s);
16343             },
16344             writeProperty: function (s) {
16345                 commitPendingTrailingSemicolon();
16346                 writer.writeProperty(s);
16347             },
16348             writeComment: function (s) {
16349                 commitPendingTrailingSemicolon();
16350                 writer.writeComment(s);
16351             },
16352             writeLine: function () {
16353                 commitPendingTrailingSemicolon();
16354                 writer.writeLine();
16355             },
16356             increaseIndent: function () {
16357                 commitPendingTrailingSemicolon();
16358                 writer.increaseIndent();
16359             },
16360             decreaseIndent: function () {
16361                 commitPendingTrailingSemicolon();
16362                 writer.decreaseIndent();
16363             } });
16364     }
16365     ts.getTrailingSemicolonDeferringWriter = getTrailingSemicolonDeferringWriter;
16366     function hostUsesCaseSensitiveFileNames(host) {
16367         return host.useCaseSensitiveFileNames ? host.useCaseSensitiveFileNames() : false;
16368     }
16369     ts.hostUsesCaseSensitiveFileNames = hostUsesCaseSensitiveFileNames;
16370     function hostGetCanonicalFileName(host) {
16371         return ts.createGetCanonicalFileName(hostUsesCaseSensitiveFileNames(host));
16372     }
16373     ts.hostGetCanonicalFileName = hostGetCanonicalFileName;
16374     function getResolvedExternalModuleName(host, file, referenceFile) {
16375         return file.moduleName || getExternalModuleNameFromPath(host, file.fileName, referenceFile && referenceFile.fileName);
16376     }
16377     ts.getResolvedExternalModuleName = getResolvedExternalModuleName;
16378     function getExternalModuleNameFromDeclaration(host, resolver, declaration) {
16379         var file = resolver.getExternalModuleFileFromDeclaration(declaration);
16380         if (!file || file.isDeclarationFile) {
16381             return undefined;
16382         }
16383         return getResolvedExternalModuleName(host, file);
16384     }
16385     ts.getExternalModuleNameFromDeclaration = getExternalModuleNameFromDeclaration;
16386     /**
16387      * Resolves a local path to a path which is absolute to the base of the emit
16388      */
16389     function getExternalModuleNameFromPath(host, fileName, referencePath) {
16390         var getCanonicalFileName = function (f) { return host.getCanonicalFileName(f); };
16391         var dir = ts.toPath(referencePath ? ts.getDirectoryPath(referencePath) : host.getCommonSourceDirectory(), host.getCurrentDirectory(), getCanonicalFileName);
16392         var filePath = ts.getNormalizedAbsolutePath(fileName, host.getCurrentDirectory());
16393         var relativePath = ts.getRelativePathToDirectoryOrUrl(dir, filePath, dir, getCanonicalFileName, /*isAbsolutePathAnUrl*/ false);
16394         var extensionless = removeFileExtension(relativePath);
16395         return referencePath ? ts.ensurePathIsNonModuleName(extensionless) : extensionless;
16396     }
16397     ts.getExternalModuleNameFromPath = getExternalModuleNameFromPath;
16398     function getOwnEmitOutputFilePath(fileName, host, extension) {
16399         var compilerOptions = host.getCompilerOptions();
16400         var emitOutputFilePathWithoutExtension;
16401         if (compilerOptions.outDir) {
16402             emitOutputFilePathWithoutExtension = removeFileExtension(getSourceFilePathInNewDir(fileName, host, compilerOptions.outDir));
16403         }
16404         else {
16405             emitOutputFilePathWithoutExtension = removeFileExtension(fileName);
16406         }
16407         return emitOutputFilePathWithoutExtension + extension;
16408     }
16409     ts.getOwnEmitOutputFilePath = getOwnEmitOutputFilePath;
16410     function getDeclarationEmitOutputFilePath(fileName, host) {
16411         return getDeclarationEmitOutputFilePathWorker(fileName, host.getCompilerOptions(), host.getCurrentDirectory(), host.getCommonSourceDirectory(), function (f) { return host.getCanonicalFileName(f); });
16412     }
16413     ts.getDeclarationEmitOutputFilePath = getDeclarationEmitOutputFilePath;
16414     function getDeclarationEmitOutputFilePathWorker(fileName, options, currentDirectory, commonSourceDirectory, getCanonicalFileName) {
16415         var outputDir = options.declarationDir || options.outDir; // Prefer declaration folder if specified
16416         var path = outputDir
16417             ? getSourceFilePathInNewDirWorker(fileName, outputDir, currentDirectory, commonSourceDirectory, getCanonicalFileName)
16418             : fileName;
16419         return removeFileExtension(path) + ".d.ts" /* Dts */;
16420     }
16421     ts.getDeclarationEmitOutputFilePathWorker = getDeclarationEmitOutputFilePathWorker;
16422     /**
16423      * Gets the source files that are expected to have an emit output.
16424      *
16425      * Originally part of `forEachExpectedEmitFile`, this functionality was extracted to support
16426      * transformations.
16427      *
16428      * @param host An EmitHost.
16429      * @param targetSourceFile An optional target source file to emit.
16430      */
16431     function getSourceFilesToEmit(host, targetSourceFile, forceDtsEmit) {
16432         var options = host.getCompilerOptions();
16433         if (options.outFile || options.out) {
16434             var moduleKind = getEmitModuleKind(options);
16435             var moduleEmitEnabled_1 = options.emitDeclarationOnly || moduleKind === ts.ModuleKind.AMD || moduleKind === ts.ModuleKind.System;
16436             // Can emit only sources that are not declaration file and are either non module code or module with --module or --target es6 specified
16437             return ts.filter(host.getSourceFiles(), function (sourceFile) {
16438                 return (moduleEmitEnabled_1 || !ts.isExternalModule(sourceFile)) &&
16439                     sourceFileMayBeEmitted(sourceFile, host, forceDtsEmit);
16440             });
16441         }
16442         else {
16443             var sourceFiles = targetSourceFile === undefined ? host.getSourceFiles() : [targetSourceFile];
16444             return ts.filter(sourceFiles, function (sourceFile) { return sourceFileMayBeEmitted(sourceFile, host, forceDtsEmit); });
16445         }
16446     }
16447     ts.getSourceFilesToEmit = getSourceFilesToEmit;
16448     /** Don't call this for `--outFile`, just for `--outDir` or plain emit. `--outFile` needs additional checks. */
16449     function sourceFileMayBeEmitted(sourceFile, host, forceDtsEmit) {
16450         var options = host.getCompilerOptions();
16451         return !(options.noEmitForJsFiles && isSourceFileJS(sourceFile)) &&
16452             !sourceFile.isDeclarationFile &&
16453             !host.isSourceFileFromExternalLibrary(sourceFile) &&
16454             !(isJsonSourceFile(sourceFile) && host.getResolvedProjectReferenceToRedirect(sourceFile.fileName)) &&
16455             (forceDtsEmit || !host.isSourceOfProjectReferenceRedirect(sourceFile.fileName));
16456     }
16457     ts.sourceFileMayBeEmitted = sourceFileMayBeEmitted;
16458     function getSourceFilePathInNewDir(fileName, host, newDirPath) {
16459         return getSourceFilePathInNewDirWorker(fileName, newDirPath, host.getCurrentDirectory(), host.getCommonSourceDirectory(), function (f) { return host.getCanonicalFileName(f); });
16460     }
16461     ts.getSourceFilePathInNewDir = getSourceFilePathInNewDir;
16462     function getSourceFilePathInNewDirWorker(fileName, newDirPath, currentDirectory, commonSourceDirectory, getCanonicalFileName) {
16463         var sourceFilePath = ts.getNormalizedAbsolutePath(fileName, currentDirectory);
16464         var isSourceFileInCommonSourceDirectory = getCanonicalFileName(sourceFilePath).indexOf(getCanonicalFileName(commonSourceDirectory)) === 0;
16465         sourceFilePath = isSourceFileInCommonSourceDirectory ? sourceFilePath.substring(commonSourceDirectory.length) : sourceFilePath;
16466         return ts.combinePaths(newDirPath, sourceFilePath);
16467     }
16468     ts.getSourceFilePathInNewDirWorker = getSourceFilePathInNewDirWorker;
16469     function writeFile(host, diagnostics, fileName, data, writeByteOrderMark, sourceFiles) {
16470         host.writeFile(fileName, data, writeByteOrderMark, function (hostErrorMessage) {
16471             diagnostics.add(createCompilerDiagnostic(ts.Diagnostics.Could_not_write_file_0_Colon_1, fileName, hostErrorMessage));
16472         }, sourceFiles);
16473     }
16474     ts.writeFile = writeFile;
16475     function ensureDirectoriesExist(directoryPath, createDirectory, directoryExists) {
16476         if (directoryPath.length > ts.getRootLength(directoryPath) && !directoryExists(directoryPath)) {
16477             var parentDirectory = ts.getDirectoryPath(directoryPath);
16478             ensureDirectoriesExist(parentDirectory, createDirectory, directoryExists);
16479             createDirectory(directoryPath);
16480         }
16481     }
16482     function writeFileEnsuringDirectories(path, data, writeByteOrderMark, writeFile, createDirectory, directoryExists) {
16483         // PERF: Checking for directory existence is expensive.  Instead, assume the directory exists
16484         // and fall back to creating it if the file write fails.
16485         try {
16486             writeFile(path, data, writeByteOrderMark);
16487         }
16488         catch (_a) {
16489             ensureDirectoriesExist(ts.getDirectoryPath(ts.normalizePath(path)), createDirectory, directoryExists);
16490             writeFile(path, data, writeByteOrderMark);
16491         }
16492     }
16493     ts.writeFileEnsuringDirectories = writeFileEnsuringDirectories;
16494     function getLineOfLocalPosition(sourceFile, pos) {
16495         var lineStarts = ts.getLineStarts(sourceFile);
16496         return ts.computeLineOfPosition(lineStarts, pos);
16497     }
16498     ts.getLineOfLocalPosition = getLineOfLocalPosition;
16499     function getLineOfLocalPositionFromLineMap(lineMap, pos) {
16500         return ts.computeLineOfPosition(lineMap, pos);
16501     }
16502     ts.getLineOfLocalPositionFromLineMap = getLineOfLocalPositionFromLineMap;
16503     function getFirstConstructorWithBody(node) {
16504         return ts.find(node.members, function (member) { return ts.isConstructorDeclaration(member) && nodeIsPresent(member.body); });
16505     }
16506     ts.getFirstConstructorWithBody = getFirstConstructorWithBody;
16507     function getSetAccessorValueParameter(accessor) {
16508         if (accessor && accessor.parameters.length > 0) {
16509             var hasThis = accessor.parameters.length === 2 && parameterIsThisKeyword(accessor.parameters[0]);
16510             return accessor.parameters[hasThis ? 1 : 0];
16511         }
16512     }
16513     ts.getSetAccessorValueParameter = getSetAccessorValueParameter;
16514     /** Get the type annotation for the value parameter. */
16515     function getSetAccessorTypeAnnotationNode(accessor) {
16516         var parameter = getSetAccessorValueParameter(accessor);
16517         return parameter && parameter.type;
16518     }
16519     ts.getSetAccessorTypeAnnotationNode = getSetAccessorTypeAnnotationNode;
16520     function getThisParameter(signature) {
16521         // callback tags do not currently support this parameters
16522         if (signature.parameters.length && !ts.isJSDocSignature(signature)) {
16523             var thisParameter = signature.parameters[0];
16524             if (parameterIsThisKeyword(thisParameter)) {
16525                 return thisParameter;
16526             }
16527         }
16528     }
16529     ts.getThisParameter = getThisParameter;
16530     function parameterIsThisKeyword(parameter) {
16531         return isThisIdentifier(parameter.name);
16532     }
16533     ts.parameterIsThisKeyword = parameterIsThisKeyword;
16534     function isThisIdentifier(node) {
16535         return !!node && node.kind === 75 /* Identifier */ && identifierIsThisKeyword(node);
16536     }
16537     ts.isThisIdentifier = isThisIdentifier;
16538     function identifierIsThisKeyword(id) {
16539         return id.originalKeywordKind === 104 /* ThisKeyword */;
16540     }
16541     ts.identifierIsThisKeyword = identifierIsThisKeyword;
16542     function getAllAccessorDeclarations(declarations, accessor) {
16543         // TODO: GH#18217
16544         var firstAccessor;
16545         var secondAccessor;
16546         var getAccessor;
16547         var setAccessor;
16548         if (hasDynamicName(accessor)) {
16549             firstAccessor = accessor;
16550             if (accessor.kind === 163 /* GetAccessor */) {
16551                 getAccessor = accessor;
16552             }
16553             else if (accessor.kind === 164 /* SetAccessor */) {
16554                 setAccessor = accessor;
16555             }
16556             else {
16557                 ts.Debug.fail("Accessor has wrong kind");
16558             }
16559         }
16560         else {
16561             ts.forEach(declarations, function (member) {
16562                 if (ts.isAccessor(member)
16563                     && hasModifier(member, 32 /* Static */) === hasModifier(accessor, 32 /* Static */)) {
16564                     var memberName = getPropertyNameForPropertyNameNode(member.name);
16565                     var accessorName = getPropertyNameForPropertyNameNode(accessor.name);
16566                     if (memberName === accessorName) {
16567                         if (!firstAccessor) {
16568                             firstAccessor = member;
16569                         }
16570                         else if (!secondAccessor) {
16571                             secondAccessor = member;
16572                         }
16573                         if (member.kind === 163 /* GetAccessor */ && !getAccessor) {
16574                             // eslint-disable-next-line
16575                             getAccessor = member;
16576                         }
16577                         if (member.kind === 164 /* SetAccessor */ && !setAccessor) {
16578                             // eslint-disable-next-line
16579                             setAccessor = member;
16580                         }
16581                     }
16582                 }
16583             });
16584         }
16585         return {
16586             firstAccessor: firstAccessor,
16587             secondAccessor: secondAccessor,
16588             getAccessor: getAccessor,
16589             setAccessor: setAccessor
16590         };
16591     }
16592     ts.getAllAccessorDeclarations = getAllAccessorDeclarations;
16593     /**
16594      * Gets the effective type annotation of a variable, parameter, or property. If the node was
16595      * parsed in a JavaScript file, gets the type annotation from JSDoc.  Also gets the type of
16596      * functions only the JSDoc case.
16597      */
16598     function getEffectiveTypeAnnotationNode(node) {
16599         if (!isInJSFile(node) && ts.isFunctionDeclaration(node))
16600             return undefined;
16601         var type = node.type;
16602         if (type || !isInJSFile(node))
16603             return type;
16604         return ts.isJSDocPropertyLikeTag(node) ? node.typeExpression && node.typeExpression.type : ts.getJSDocType(node);
16605     }
16606     ts.getEffectiveTypeAnnotationNode = getEffectiveTypeAnnotationNode;
16607     function getTypeAnnotationNode(node) {
16608         return node.type;
16609     }
16610     ts.getTypeAnnotationNode = getTypeAnnotationNode;
16611     /**
16612      * Gets the effective return type annotation of a signature. If the node was parsed in a
16613      * JavaScript file, gets the return type annotation from JSDoc.
16614      */
16615     function getEffectiveReturnTypeNode(node) {
16616         return ts.isJSDocSignature(node) ?
16617             node.type && node.type.typeExpression && node.type.typeExpression.type :
16618             node.type || (isInJSFile(node) ? ts.getJSDocReturnType(node) : undefined);
16619     }
16620     ts.getEffectiveReturnTypeNode = getEffectiveReturnTypeNode;
16621     function getJSDocTypeParameterDeclarations(node) {
16622         return ts.flatMap(ts.getJSDocTags(node), function (tag) { return isNonTypeAliasTemplate(tag) ? tag.typeParameters : undefined; });
16623     }
16624     ts.getJSDocTypeParameterDeclarations = getJSDocTypeParameterDeclarations;
16625     /** template tags are only available when a typedef isn't already using them */
16626     function isNonTypeAliasTemplate(tag) {
16627         return ts.isJSDocTemplateTag(tag) && !(tag.parent.kind === 303 /* JSDocComment */ && tag.parent.tags.some(isJSDocTypeAlias));
16628     }
16629     /**
16630      * Gets the effective type annotation of the value parameter of a set accessor. If the node
16631      * was parsed in a JavaScript file, gets the type annotation from JSDoc.
16632      */
16633     function getEffectiveSetAccessorTypeAnnotationNode(node) {
16634         var parameter = getSetAccessorValueParameter(node);
16635         return parameter && getEffectiveTypeAnnotationNode(parameter);
16636     }
16637     ts.getEffectiveSetAccessorTypeAnnotationNode = getEffectiveSetAccessorTypeAnnotationNode;
16638     function emitNewLineBeforeLeadingComments(lineMap, writer, node, leadingComments) {
16639         emitNewLineBeforeLeadingCommentsOfPosition(lineMap, writer, node.pos, leadingComments);
16640     }
16641     ts.emitNewLineBeforeLeadingComments = emitNewLineBeforeLeadingComments;
16642     function emitNewLineBeforeLeadingCommentsOfPosition(lineMap, writer, pos, leadingComments) {
16643         // If the leading comments start on different line than the start of node, write new line
16644         if (leadingComments && leadingComments.length && pos !== leadingComments[0].pos &&
16645             getLineOfLocalPositionFromLineMap(lineMap, pos) !== getLineOfLocalPositionFromLineMap(lineMap, leadingComments[0].pos)) {
16646             writer.writeLine();
16647         }
16648     }
16649     ts.emitNewLineBeforeLeadingCommentsOfPosition = emitNewLineBeforeLeadingCommentsOfPosition;
16650     function emitNewLineBeforeLeadingCommentOfPosition(lineMap, writer, pos, commentPos) {
16651         // If the leading comments start on different line than the start of node, write new line
16652         if (pos !== commentPos &&
16653             getLineOfLocalPositionFromLineMap(lineMap, pos) !== getLineOfLocalPositionFromLineMap(lineMap, commentPos)) {
16654             writer.writeLine();
16655         }
16656     }
16657     ts.emitNewLineBeforeLeadingCommentOfPosition = emitNewLineBeforeLeadingCommentOfPosition;
16658     function emitComments(text, lineMap, writer, comments, leadingSeparator, trailingSeparator, newLine, writeComment) {
16659         if (comments && comments.length > 0) {
16660             if (leadingSeparator) {
16661                 writer.writeSpace(" ");
16662             }
16663             var emitInterveningSeparator = false;
16664             for (var _i = 0, comments_1 = comments; _i < comments_1.length; _i++) {
16665                 var comment = comments_1[_i];
16666                 if (emitInterveningSeparator) {
16667                     writer.writeSpace(" ");
16668                     emitInterveningSeparator = false;
16669                 }
16670                 writeComment(text, lineMap, writer, comment.pos, comment.end, newLine);
16671                 if (comment.hasTrailingNewLine) {
16672                     writer.writeLine();
16673                 }
16674                 else {
16675                     emitInterveningSeparator = true;
16676                 }
16677             }
16678             if (emitInterveningSeparator && trailingSeparator) {
16679                 writer.writeSpace(" ");
16680             }
16681         }
16682     }
16683     ts.emitComments = emitComments;
16684     /**
16685      * Detached comment is a comment at the top of file or function body that is separated from
16686      * the next statement by space.
16687      */
16688     function emitDetachedComments(text, lineMap, writer, writeComment, node, newLine, removeComments) {
16689         var leadingComments;
16690         var currentDetachedCommentInfo;
16691         if (removeComments) {
16692             // removeComments is true, only reserve pinned comment at the top of file
16693             // For example:
16694             //      /*! Pinned Comment */
16695             //
16696             //      var x = 10;
16697             if (node.pos === 0) {
16698                 leadingComments = ts.filter(ts.getLeadingCommentRanges(text, node.pos), isPinnedCommentLocal);
16699             }
16700         }
16701         else {
16702             // removeComments is false, just get detached as normal and bypass the process to filter comment
16703             leadingComments = ts.getLeadingCommentRanges(text, node.pos);
16704         }
16705         if (leadingComments) {
16706             var detachedComments = [];
16707             var lastComment = void 0;
16708             for (var _i = 0, leadingComments_1 = leadingComments; _i < leadingComments_1.length; _i++) {
16709                 var comment = leadingComments_1[_i];
16710                 if (lastComment) {
16711                     var lastCommentLine = getLineOfLocalPositionFromLineMap(lineMap, lastComment.end);
16712                     var commentLine = getLineOfLocalPositionFromLineMap(lineMap, comment.pos);
16713                     if (commentLine >= lastCommentLine + 2) {
16714                         // There was a blank line between the last comment and this comment.  This
16715                         // comment is not part of the copyright comments.  Return what we have so
16716                         // far.
16717                         break;
16718                     }
16719                 }
16720                 detachedComments.push(comment);
16721                 lastComment = comment;
16722             }
16723             if (detachedComments.length) {
16724                 // All comments look like they could have been part of the copyright header.  Make
16725                 // sure there is at least one blank line between it and the node.  If not, it's not
16726                 // a copyright header.
16727                 var lastCommentLine = getLineOfLocalPositionFromLineMap(lineMap, ts.last(detachedComments).end);
16728                 var nodeLine = getLineOfLocalPositionFromLineMap(lineMap, ts.skipTrivia(text, node.pos));
16729                 if (nodeLine >= lastCommentLine + 2) {
16730                     // Valid detachedComments
16731                     emitNewLineBeforeLeadingComments(lineMap, writer, node, leadingComments);
16732                     emitComments(text, lineMap, writer, detachedComments, /*leadingSeparator*/ false, /*trailingSeparator*/ true, newLine, writeComment);
16733                     currentDetachedCommentInfo = { nodePos: node.pos, detachedCommentEndPos: ts.last(detachedComments).end };
16734                 }
16735             }
16736         }
16737         return currentDetachedCommentInfo;
16738         function isPinnedCommentLocal(comment) {
16739             return isPinnedComment(text, comment.pos);
16740         }
16741     }
16742     ts.emitDetachedComments = emitDetachedComments;
16743     function writeCommentRange(text, lineMap, writer, commentPos, commentEnd, newLine) {
16744         if (text.charCodeAt(commentPos + 1) === 42 /* asterisk */) {
16745             var firstCommentLineAndCharacter = ts.computeLineAndCharacterOfPosition(lineMap, commentPos);
16746             var lineCount = lineMap.length;
16747             var firstCommentLineIndent = void 0;
16748             for (var pos = commentPos, currentLine = firstCommentLineAndCharacter.line; pos < commentEnd; currentLine++) {
16749                 var nextLineStart = (currentLine + 1) === lineCount
16750                     ? text.length + 1
16751                     : lineMap[currentLine + 1];
16752                 if (pos !== commentPos) {
16753                     // If we are not emitting first line, we need to write the spaces to adjust the alignment
16754                     if (firstCommentLineIndent === undefined) {
16755                         firstCommentLineIndent = calculateIndent(text, lineMap[firstCommentLineAndCharacter.line], commentPos);
16756                     }
16757                     // These are number of spaces writer is going to write at current indent
16758                     var currentWriterIndentSpacing = writer.getIndent() * getIndentSize();
16759                     // Number of spaces we want to be writing
16760                     // eg: Assume writer indent
16761                     // module m {
16762                     //         /* starts at character 9 this is line 1
16763                     //    * starts at character pos 4 line                        --1  = 8 - 8 + 3
16764                     //   More left indented comment */                            --2  = 8 - 8 + 2
16765                     //     class c { }
16766                     // }
16767                     // module m {
16768                     //     /* this is line 1 -- Assume current writer indent 8
16769                     //      * line                                                --3 = 8 - 4 + 5
16770                     //            More right indented comment */                  --4 = 8 - 4 + 11
16771                     //     class c { }
16772                     // }
16773                     var spacesToEmit = currentWriterIndentSpacing - firstCommentLineIndent + calculateIndent(text, pos, nextLineStart);
16774                     if (spacesToEmit > 0) {
16775                         var numberOfSingleSpacesToEmit = spacesToEmit % getIndentSize();
16776                         var indentSizeSpaceString = getIndentString((spacesToEmit - numberOfSingleSpacesToEmit) / getIndentSize());
16777                         // Write indent size string ( in eg 1: = "", 2: "" , 3: string with 8 spaces 4: string with 12 spaces
16778                         writer.rawWrite(indentSizeSpaceString);
16779                         // Emit the single spaces (in eg: 1: 3 spaces, 2: 2 spaces, 3: 1 space, 4: 3 spaces)
16780                         while (numberOfSingleSpacesToEmit) {
16781                             writer.rawWrite(" ");
16782                             numberOfSingleSpacesToEmit--;
16783                         }
16784                     }
16785                     else {
16786                         // No spaces to emit write empty string
16787                         writer.rawWrite("");
16788                     }
16789                 }
16790                 // Write the comment line text
16791                 writeTrimmedCurrentLine(text, commentEnd, writer, newLine, pos, nextLineStart);
16792                 pos = nextLineStart;
16793             }
16794         }
16795         else {
16796             // Single line comment of style //....
16797             writer.writeComment(text.substring(commentPos, commentEnd));
16798         }
16799     }
16800     ts.writeCommentRange = writeCommentRange;
16801     function writeTrimmedCurrentLine(text, commentEnd, writer, newLine, pos, nextLineStart) {
16802         var end = Math.min(commentEnd, nextLineStart - 1);
16803         var currentLineText = text.substring(pos, end).replace(/^\s+|\s+$/g, "");
16804         if (currentLineText) {
16805             // trimmed forward and ending spaces text
16806             writer.writeComment(currentLineText);
16807             if (end !== commentEnd) {
16808                 writer.writeLine();
16809             }
16810         }
16811         else {
16812             // Empty string - make sure we write empty line
16813             writer.rawWrite(newLine);
16814         }
16815     }
16816     function calculateIndent(text, pos, end) {
16817         var currentLineIndent = 0;
16818         for (; pos < end && ts.isWhiteSpaceSingleLine(text.charCodeAt(pos)); pos++) {
16819             if (text.charCodeAt(pos) === 9 /* tab */) {
16820                 // Tabs = TabSize = indent size and go to next tabStop
16821                 currentLineIndent += getIndentSize() - (currentLineIndent % getIndentSize());
16822             }
16823             else {
16824                 // Single space
16825                 currentLineIndent++;
16826             }
16827         }
16828         return currentLineIndent;
16829     }
16830     function hasModifiers(node) {
16831         return getModifierFlags(node) !== 0 /* None */;
16832     }
16833     ts.hasModifiers = hasModifiers;
16834     function hasModifier(node, flags) {
16835         return !!getSelectedModifierFlags(node, flags);
16836     }
16837     ts.hasModifier = hasModifier;
16838     function hasStaticModifier(node) {
16839         return hasModifier(node, 32 /* Static */);
16840     }
16841     ts.hasStaticModifier = hasStaticModifier;
16842     function hasReadonlyModifier(node) {
16843         return hasModifier(node, 64 /* Readonly */);
16844     }
16845     ts.hasReadonlyModifier = hasReadonlyModifier;
16846     function getSelectedModifierFlags(node, flags) {
16847         return getModifierFlags(node) & flags;
16848     }
16849     ts.getSelectedModifierFlags = getSelectedModifierFlags;
16850     function getModifierFlags(node) {
16851         if (node.kind >= 0 /* FirstToken */ && node.kind <= 152 /* LastToken */) {
16852             return 0 /* None */;
16853         }
16854         if (node.modifierFlagsCache & 536870912 /* HasComputedFlags */) {
16855             return node.modifierFlagsCache & ~536870912 /* HasComputedFlags */;
16856         }
16857         var flags = getModifierFlagsNoCache(node);
16858         node.modifierFlagsCache = flags | 536870912 /* HasComputedFlags */;
16859         return flags;
16860     }
16861     ts.getModifierFlags = getModifierFlags;
16862     function getModifierFlagsNoCache(node) {
16863         var flags = 0 /* None */;
16864         if (node.modifiers) {
16865             for (var _i = 0, _a = node.modifiers; _i < _a.length; _i++) {
16866                 var modifier = _a[_i];
16867                 flags |= modifierToFlag(modifier.kind);
16868             }
16869         }
16870         if (isInJSFile(node) && !!node.parent) {
16871             // getModifierFlagsNoCache should only be called when parent pointers are set,
16872             // or when !(node.flags & NodeFlags.Synthesized) && node.kind !== SyntaxKind.SourceFile)
16873             var tags = (ts.getJSDocPublicTag(node) ? 4 /* Public */ : 0 /* None */)
16874                 | (ts.getJSDocPrivateTag(node) ? 8 /* Private */ : 0 /* None */)
16875                 | (ts.getJSDocProtectedTag(node) ? 16 /* Protected */ : 0 /* None */)
16876                 | (ts.getJSDocReadonlyTag(node) ? 64 /* Readonly */ : 0 /* None */);
16877             flags |= tags;
16878         }
16879         if (node.flags & 4 /* NestedNamespace */ || (node.kind === 75 /* Identifier */ && node.isInJSDocNamespace)) {
16880             flags |= 1 /* Export */;
16881         }
16882         return flags;
16883     }
16884     ts.getModifierFlagsNoCache = getModifierFlagsNoCache;
16885     function modifierToFlag(token) {
16886         switch (token) {
16887             case 120 /* StaticKeyword */: return 32 /* Static */;
16888             case 119 /* PublicKeyword */: return 4 /* Public */;
16889             case 118 /* ProtectedKeyword */: return 16 /* Protected */;
16890             case 117 /* PrivateKeyword */: return 8 /* Private */;
16891             case 122 /* AbstractKeyword */: return 128 /* Abstract */;
16892             case 89 /* ExportKeyword */: return 1 /* Export */;
16893             case 130 /* DeclareKeyword */: return 2 /* Ambient */;
16894             case 81 /* ConstKeyword */: return 2048 /* Const */;
16895             case 84 /* DefaultKeyword */: return 512 /* Default */;
16896             case 126 /* AsyncKeyword */: return 256 /* Async */;
16897             case 138 /* ReadonlyKeyword */: return 64 /* Readonly */;
16898         }
16899         return 0 /* None */;
16900     }
16901     ts.modifierToFlag = modifierToFlag;
16902     function isLogicalOperator(token) {
16903         return token === 56 /* BarBarToken */
16904             || token === 55 /* AmpersandAmpersandToken */
16905             || token === 53 /* ExclamationToken */;
16906     }
16907     ts.isLogicalOperator = isLogicalOperator;
16908     function isAssignmentOperator(token) {
16909         return token >= 62 /* FirstAssignment */ && token <= 74 /* LastAssignment */;
16910     }
16911     ts.isAssignmentOperator = isAssignmentOperator;
16912     /** Get `C` given `N` if `N` is in the position `class C extends N` where `N` is an ExpressionWithTypeArguments. */
16913     function tryGetClassExtendingExpressionWithTypeArguments(node) {
16914         var cls = tryGetClassImplementingOrExtendingExpressionWithTypeArguments(node);
16915         return cls && !cls.isImplements ? cls.class : undefined;
16916     }
16917     ts.tryGetClassExtendingExpressionWithTypeArguments = tryGetClassExtendingExpressionWithTypeArguments;
16918     function tryGetClassImplementingOrExtendingExpressionWithTypeArguments(node) {
16919         return ts.isExpressionWithTypeArguments(node)
16920             && ts.isHeritageClause(node.parent)
16921             && ts.isClassLike(node.parent.parent)
16922             ? { class: node.parent.parent, isImplements: node.parent.token === 113 /* ImplementsKeyword */ }
16923             : undefined;
16924     }
16925     ts.tryGetClassImplementingOrExtendingExpressionWithTypeArguments = tryGetClassImplementingOrExtendingExpressionWithTypeArguments;
16926     function isAssignmentExpression(node, excludeCompoundAssignment) {
16927         return ts.isBinaryExpression(node)
16928             && (excludeCompoundAssignment
16929                 ? node.operatorToken.kind === 62 /* EqualsToken */
16930                 : isAssignmentOperator(node.operatorToken.kind))
16931             && ts.isLeftHandSideExpression(node.left);
16932     }
16933     ts.isAssignmentExpression = isAssignmentExpression;
16934     function isDestructuringAssignment(node) {
16935         if (isAssignmentExpression(node, /*excludeCompoundAssignment*/ true)) {
16936             var kind = node.left.kind;
16937             return kind === 193 /* ObjectLiteralExpression */
16938                 || kind === 192 /* ArrayLiteralExpression */;
16939         }
16940         return false;
16941     }
16942     ts.isDestructuringAssignment = isDestructuringAssignment;
16943     function isExpressionWithTypeArgumentsInClassExtendsClause(node) {
16944         return tryGetClassExtendingExpressionWithTypeArguments(node) !== undefined;
16945     }
16946     ts.isExpressionWithTypeArgumentsInClassExtendsClause = isExpressionWithTypeArgumentsInClassExtendsClause;
16947     function isEntityNameExpression(node) {
16948         return node.kind === 75 /* Identifier */ || isPropertyAccessEntityNameExpression(node);
16949     }
16950     ts.isEntityNameExpression = isEntityNameExpression;
16951     function getFirstIdentifier(node) {
16952         switch (node.kind) {
16953             case 75 /* Identifier */:
16954                 return node;
16955             case 153 /* QualifiedName */:
16956                 do {
16957                     node = node.left;
16958                 } while (node.kind !== 75 /* Identifier */);
16959                 return node;
16960             case 194 /* PropertyAccessExpression */:
16961                 do {
16962                     node = node.expression;
16963                 } while (node.kind !== 75 /* Identifier */);
16964                 return node;
16965         }
16966     }
16967     ts.getFirstIdentifier = getFirstIdentifier;
16968     function isDottedName(node) {
16969         return node.kind === 75 /* Identifier */ || node.kind === 104 /* ThisKeyword */ || node.kind === 102 /* SuperKeyword */ ||
16970             node.kind === 194 /* PropertyAccessExpression */ && isDottedName(node.expression) ||
16971             node.kind === 200 /* ParenthesizedExpression */ && isDottedName(node.expression);
16972     }
16973     ts.isDottedName = isDottedName;
16974     function isPropertyAccessEntityNameExpression(node) {
16975         return ts.isPropertyAccessExpression(node) && ts.isIdentifier(node.name) && isEntityNameExpression(node.expression);
16976     }
16977     ts.isPropertyAccessEntityNameExpression = isPropertyAccessEntityNameExpression;
16978     function tryGetPropertyAccessOrIdentifierToString(expr) {
16979         if (ts.isPropertyAccessExpression(expr)) {
16980             var baseStr = tryGetPropertyAccessOrIdentifierToString(expr.expression);
16981             if (baseStr !== undefined) {
16982                 return baseStr + "." + expr.name;
16983             }
16984         }
16985         else if (ts.isIdentifier(expr)) {
16986             return ts.unescapeLeadingUnderscores(expr.escapedText);
16987         }
16988         return undefined;
16989     }
16990     ts.tryGetPropertyAccessOrIdentifierToString = tryGetPropertyAccessOrIdentifierToString;
16991     function isPrototypeAccess(node) {
16992         return isBindableStaticAccessExpression(node) && getElementOrPropertyAccessName(node) === "prototype";
16993     }
16994     ts.isPrototypeAccess = isPrototypeAccess;
16995     function isRightSideOfQualifiedNameOrPropertyAccess(node) {
16996         return (node.parent.kind === 153 /* QualifiedName */ && node.parent.right === node) ||
16997             (node.parent.kind === 194 /* PropertyAccessExpression */ && node.parent.name === node);
16998     }
16999     ts.isRightSideOfQualifiedNameOrPropertyAccess = isRightSideOfQualifiedNameOrPropertyAccess;
17000     function isEmptyObjectLiteral(expression) {
17001         return expression.kind === 193 /* ObjectLiteralExpression */ &&
17002             expression.properties.length === 0;
17003     }
17004     ts.isEmptyObjectLiteral = isEmptyObjectLiteral;
17005     function isEmptyArrayLiteral(expression) {
17006         return expression.kind === 192 /* ArrayLiteralExpression */ &&
17007             expression.elements.length === 0;
17008     }
17009     ts.isEmptyArrayLiteral = isEmptyArrayLiteral;
17010     function getLocalSymbolForExportDefault(symbol) {
17011         return isExportDefaultSymbol(symbol) ? symbol.declarations[0].localSymbol : undefined;
17012     }
17013     ts.getLocalSymbolForExportDefault = getLocalSymbolForExportDefault;
17014     function isExportDefaultSymbol(symbol) {
17015         return symbol && ts.length(symbol.declarations) > 0 && hasModifier(symbol.declarations[0], 512 /* Default */);
17016     }
17017     /** Return ".ts", ".d.ts", or ".tsx", if that is the extension. */
17018     function tryExtractTSExtension(fileName) {
17019         return ts.find(ts.supportedTSExtensionsForExtractExtension, function (extension) { return ts.fileExtensionIs(fileName, extension); });
17020     }
17021     ts.tryExtractTSExtension = tryExtractTSExtension;
17022     /**
17023      * Replace each instance of non-ascii characters by one, two, three, or four escape sequences
17024      * representing the UTF-8 encoding of the character, and return the expanded char code list.
17025      */
17026     function getExpandedCharCodes(input) {
17027         var output = [];
17028         var length = input.length;
17029         for (var i = 0; i < length; i++) {
17030             var charCode = input.charCodeAt(i);
17031             // handle utf8
17032             if (charCode < 0x80) {
17033                 output.push(charCode);
17034             }
17035             else if (charCode < 0x800) {
17036                 output.push((charCode >> 6) | 192);
17037                 output.push((charCode & 63) | 128);
17038             }
17039             else if (charCode < 0x10000) {
17040                 output.push((charCode >> 12) | 224);
17041                 output.push(((charCode >> 6) & 63) | 128);
17042                 output.push((charCode & 63) | 128);
17043             }
17044             else if (charCode < 0x20000) {
17045                 output.push((charCode >> 18) | 240);
17046                 output.push(((charCode >> 12) & 63) | 128);
17047                 output.push(((charCode >> 6) & 63) | 128);
17048                 output.push((charCode & 63) | 128);
17049             }
17050             else {
17051                 ts.Debug.assert(false, "Unexpected code point");
17052             }
17053         }
17054         return output;
17055     }
17056     var base64Digits = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
17057     /**
17058      * Converts a string to a base-64 encoded ASCII string.
17059      */
17060     function convertToBase64(input) {
17061         var result = "";
17062         var charCodes = getExpandedCharCodes(input);
17063         var i = 0;
17064         var length = charCodes.length;
17065         var byte1, byte2, byte3, byte4;
17066         while (i < length) {
17067             // Convert every 6-bits in the input 3 character points
17068             // into a base64 digit
17069             byte1 = charCodes[i] >> 2;
17070             byte2 = (charCodes[i] & 3) << 4 | charCodes[i + 1] >> 4;
17071             byte3 = (charCodes[i + 1] & 15) << 2 | charCodes[i + 2] >> 6;
17072             byte4 = charCodes[i + 2] & 63;
17073             // We are out of characters in the input, set the extra
17074             // digits to 64 (padding character).
17075             if (i + 1 >= length) {
17076                 byte3 = byte4 = 64;
17077             }
17078             else if (i + 2 >= length) {
17079                 byte4 = 64;
17080             }
17081             // Write to the output
17082             result += base64Digits.charAt(byte1) + base64Digits.charAt(byte2) + base64Digits.charAt(byte3) + base64Digits.charAt(byte4);
17083             i += 3;
17084         }
17085         return result;
17086     }
17087     ts.convertToBase64 = convertToBase64;
17088     function getStringFromExpandedCharCodes(codes) {
17089         var output = "";
17090         var i = 0;
17091         var length = codes.length;
17092         while (i < length) {
17093             var charCode = codes[i];
17094             if (charCode < 0x80) {
17095                 output += String.fromCharCode(charCode);
17096                 i++;
17097             }
17098             else if ((charCode & 192) === 192) {
17099                 var value = charCode & 63;
17100                 i++;
17101                 var nextCode = codes[i];
17102                 while ((nextCode & 192) === 128) {
17103                     value = (value << 6) | (nextCode & 63);
17104                     i++;
17105                     nextCode = codes[i];
17106                 }
17107                 // `value` may be greater than 10FFFF (the maximum unicode codepoint) - JS will just make this into an invalid character for us
17108                 output += String.fromCharCode(value);
17109             }
17110             else {
17111                 // We don't want to kill the process when decoding fails (due to a following char byte not
17112                 // following a leading char), so we just print the (bad) value
17113                 output += String.fromCharCode(charCode);
17114                 i++;
17115             }
17116         }
17117         return output;
17118     }
17119     function base64encode(host, input) {
17120         if (host && host.base64encode) {
17121             return host.base64encode(input);
17122         }
17123         return convertToBase64(input);
17124     }
17125     ts.base64encode = base64encode;
17126     function base64decode(host, input) {
17127         if (host && host.base64decode) {
17128             return host.base64decode(input);
17129         }
17130         var length = input.length;
17131         var expandedCharCodes = [];
17132         var i = 0;
17133         while (i < length) {
17134             // Stop decoding once padding characters are present
17135             if (input.charCodeAt(i) === base64Digits.charCodeAt(64)) {
17136                 break;
17137             }
17138             // convert 4 input digits into three characters, ignoring padding characters at the end
17139             var ch1 = base64Digits.indexOf(input[i]);
17140             var ch2 = base64Digits.indexOf(input[i + 1]);
17141             var ch3 = base64Digits.indexOf(input[i + 2]);
17142             var ch4 = base64Digits.indexOf(input[i + 3]);
17143             var code1 = ((ch1 & 63) << 2) | ((ch2 >> 4) & 3);
17144             var code2 = ((ch2 & 15) << 4) | ((ch3 >> 2) & 15);
17145             var code3 = ((ch3 & 3) << 6) | (ch4 & 63);
17146             if (code2 === 0 && ch3 !== 0) { // code2 decoded to zero, but ch3 was padding - elide code2 and code3
17147                 expandedCharCodes.push(code1);
17148             }
17149             else if (code3 === 0 && ch4 !== 0) { // code3 decoded to zero, but ch4 was padding, elide code3
17150                 expandedCharCodes.push(code1, code2);
17151             }
17152             else {
17153                 expandedCharCodes.push(code1, code2, code3);
17154             }
17155             i += 4;
17156         }
17157         return getStringFromExpandedCharCodes(expandedCharCodes);
17158     }
17159     ts.base64decode = base64decode;
17160     function readJson(path, host) {
17161         try {
17162             var jsonText = host.readFile(path);
17163             if (!jsonText)
17164                 return {};
17165             var result = ts.parseConfigFileTextToJson(path, jsonText);
17166             if (result.error) {
17167                 return {};
17168             }
17169             return result.config;
17170         }
17171         catch (e) {
17172             // gracefully handle if readFile fails or returns not JSON
17173             return {};
17174         }
17175     }
17176     ts.readJson = readJson;
17177     function directoryProbablyExists(directoryName, host) {
17178         // if host does not support 'directoryExists' assume that directory will exist
17179         return !host.directoryExists || host.directoryExists(directoryName);
17180     }
17181     ts.directoryProbablyExists = directoryProbablyExists;
17182     var carriageReturnLineFeed = "\r\n";
17183     var lineFeed = "\n";
17184     function getNewLineCharacter(options, getNewLine) {
17185         switch (options.newLine) {
17186             case 0 /* CarriageReturnLineFeed */:
17187                 return carriageReturnLineFeed;
17188             case 1 /* LineFeed */:
17189                 return lineFeed;
17190         }
17191         return getNewLine ? getNewLine() : ts.sys ? ts.sys.newLine : carriageReturnLineFeed;
17192     }
17193     ts.getNewLineCharacter = getNewLineCharacter;
17194     /**
17195      * Creates a new TextRange from the provided pos and end.
17196      *
17197      * @param pos The start position.
17198      * @param end The end position.
17199      */
17200     function createRange(pos, end) {
17201         if (end === void 0) { end = pos; }
17202         ts.Debug.assert(end >= pos || end === -1);
17203         return { pos: pos, end: end };
17204     }
17205     ts.createRange = createRange;
17206     /**
17207      * Creates a new TextRange from a provided range with a new end position.
17208      *
17209      * @param range A TextRange.
17210      * @param end The new end position.
17211      */
17212     function moveRangeEnd(range, end) {
17213         return createRange(range.pos, end);
17214     }
17215     ts.moveRangeEnd = moveRangeEnd;
17216     /**
17217      * Creates a new TextRange from a provided range with a new start position.
17218      *
17219      * @param range A TextRange.
17220      * @param pos The new Start position.
17221      */
17222     function moveRangePos(range, pos) {
17223         return createRange(pos, range.end);
17224     }
17225     ts.moveRangePos = moveRangePos;
17226     /**
17227      * Moves the start position of a range past any decorators.
17228      */
17229     function moveRangePastDecorators(node) {
17230         return node.decorators && node.decorators.length > 0
17231             ? moveRangePos(node, node.decorators.end)
17232             : node;
17233     }
17234     ts.moveRangePastDecorators = moveRangePastDecorators;
17235     /**
17236      * Moves the start position of a range past any decorators or modifiers.
17237      */
17238     function moveRangePastModifiers(node) {
17239         return node.modifiers && node.modifiers.length > 0
17240             ? moveRangePos(node, node.modifiers.end)
17241             : moveRangePastDecorators(node);
17242     }
17243     ts.moveRangePastModifiers = moveRangePastModifiers;
17244     /**
17245      * Determines whether a TextRange has the same start and end positions.
17246      *
17247      * @param range A TextRange.
17248      */
17249     function isCollapsedRange(range) {
17250         return range.pos === range.end;
17251     }
17252     ts.isCollapsedRange = isCollapsedRange;
17253     /**
17254      * Creates a new TextRange for a token at the provides start position.
17255      *
17256      * @param pos The start position.
17257      * @param token The token.
17258      */
17259     function createTokenRange(pos, token) {
17260         return createRange(pos, pos + ts.tokenToString(token).length);
17261     }
17262     ts.createTokenRange = createTokenRange;
17263     function rangeIsOnSingleLine(range, sourceFile) {
17264         return rangeStartIsOnSameLineAsRangeEnd(range, range, sourceFile);
17265     }
17266     ts.rangeIsOnSingleLine = rangeIsOnSingleLine;
17267     function rangeStartPositionsAreOnSameLine(range1, range2, sourceFile) {
17268         return positionsAreOnSameLine(getStartPositionOfRange(range1, sourceFile, /*includeComments*/ false), getStartPositionOfRange(range2, sourceFile, /*includeComments*/ false), sourceFile);
17269     }
17270     ts.rangeStartPositionsAreOnSameLine = rangeStartPositionsAreOnSameLine;
17271     function rangeEndPositionsAreOnSameLine(range1, range2, sourceFile) {
17272         return positionsAreOnSameLine(range1.end, range2.end, sourceFile);
17273     }
17274     ts.rangeEndPositionsAreOnSameLine = rangeEndPositionsAreOnSameLine;
17275     function rangeStartIsOnSameLineAsRangeEnd(range1, range2, sourceFile) {
17276         return positionsAreOnSameLine(getStartPositionOfRange(range1, sourceFile, /*includeComments*/ false), range2.end, sourceFile);
17277     }
17278     ts.rangeStartIsOnSameLineAsRangeEnd = rangeStartIsOnSameLineAsRangeEnd;
17279     function rangeEndIsOnSameLineAsRangeStart(range1, range2, sourceFile) {
17280         return positionsAreOnSameLine(range1.end, getStartPositionOfRange(range2, sourceFile, /*includeComments*/ false), sourceFile);
17281     }
17282     ts.rangeEndIsOnSameLineAsRangeStart = rangeEndIsOnSameLineAsRangeStart;
17283     function getLinesBetweenRangeEndAndRangeStart(range1, range2, sourceFile, includeSecondRangeComments) {
17284         var range2Start = getStartPositionOfRange(range2, sourceFile, includeSecondRangeComments);
17285         return ts.getLinesBetweenPositions(sourceFile, range1.end, range2Start);
17286     }
17287     ts.getLinesBetweenRangeEndAndRangeStart = getLinesBetweenRangeEndAndRangeStart;
17288     function getLinesBetweenRangeEndPositions(range1, range2, sourceFile) {
17289         return ts.getLinesBetweenPositions(sourceFile, range1.end, range2.end);
17290     }
17291     ts.getLinesBetweenRangeEndPositions = getLinesBetweenRangeEndPositions;
17292     function isNodeArrayMultiLine(list, sourceFile) {
17293         return !positionsAreOnSameLine(list.pos, list.end, sourceFile);
17294     }
17295     ts.isNodeArrayMultiLine = isNodeArrayMultiLine;
17296     function positionsAreOnSameLine(pos1, pos2, sourceFile) {
17297         return ts.getLinesBetweenPositions(sourceFile, pos1, pos2) === 0;
17298     }
17299     ts.positionsAreOnSameLine = positionsAreOnSameLine;
17300     function getStartPositionOfRange(range, sourceFile, includeComments) {
17301         return positionIsSynthesized(range.pos) ? -1 : ts.skipTrivia(sourceFile.text, range.pos, /*stopAfterLineBreak*/ false, includeComments);
17302     }
17303     ts.getStartPositionOfRange = getStartPositionOfRange;
17304     function getLinesBetweenPositionAndPrecedingNonWhitespaceCharacter(pos, stopPos, sourceFile, includeComments) {
17305         var startPos = ts.skipTrivia(sourceFile.text, pos, /*stopAfterLineBreak*/ false, includeComments);
17306         var prevPos = getPreviousNonWhitespacePosition(startPos, stopPos, sourceFile);
17307         return ts.getLinesBetweenPositions(sourceFile, prevPos !== null && prevPos !== void 0 ? prevPos : stopPos, startPos);
17308     }
17309     ts.getLinesBetweenPositionAndPrecedingNonWhitespaceCharacter = getLinesBetweenPositionAndPrecedingNonWhitespaceCharacter;
17310     function getLinesBetweenPositionAndNextNonWhitespaceCharacter(pos, stopPos, sourceFile, includeComments) {
17311         var nextPos = ts.skipTrivia(sourceFile.text, pos, /*stopAfterLineBreak*/ false, includeComments);
17312         return ts.getLinesBetweenPositions(sourceFile, pos, Math.min(stopPos, nextPos));
17313     }
17314     ts.getLinesBetweenPositionAndNextNonWhitespaceCharacter = getLinesBetweenPositionAndNextNonWhitespaceCharacter;
17315     function getPreviousNonWhitespacePosition(pos, stopPos, sourceFile) {
17316         if (stopPos === void 0) { stopPos = 0; }
17317         while (pos-- > stopPos) {
17318             if (!ts.isWhiteSpaceLike(sourceFile.text.charCodeAt(pos))) {
17319                 return pos;
17320             }
17321         }
17322     }
17323     /**
17324      * Determines whether a name was originally the declaration name of an enum or namespace
17325      * declaration.
17326      */
17327     function isDeclarationNameOfEnumOrNamespace(node) {
17328         var parseNode = ts.getParseTreeNode(node);
17329         if (parseNode) {
17330             switch (parseNode.parent.kind) {
17331                 case 248 /* EnumDeclaration */:
17332                 case 249 /* ModuleDeclaration */:
17333                     return parseNode === parseNode.parent.name;
17334             }
17335         }
17336         return false;
17337     }
17338     ts.isDeclarationNameOfEnumOrNamespace = isDeclarationNameOfEnumOrNamespace;
17339     function getInitializedVariables(node) {
17340         return ts.filter(node.declarations, isInitializedVariable);
17341     }
17342     ts.getInitializedVariables = getInitializedVariables;
17343     function isInitializedVariable(node) {
17344         return node.initializer !== undefined;
17345     }
17346     function isWatchSet(options) {
17347         // Firefox has Object.prototype.watch
17348         return options.watch && options.hasOwnProperty("watch");
17349     }
17350     ts.isWatchSet = isWatchSet;
17351     function closeFileWatcher(watcher) {
17352         watcher.close();
17353     }
17354     ts.closeFileWatcher = closeFileWatcher;
17355     function getCheckFlags(symbol) {
17356         return symbol.flags & 33554432 /* Transient */ ? symbol.checkFlags : 0;
17357     }
17358     ts.getCheckFlags = getCheckFlags;
17359     function getDeclarationModifierFlagsFromSymbol(s) {
17360         if (s.valueDeclaration) {
17361             var flags = ts.getCombinedModifierFlags(s.valueDeclaration);
17362             return s.parent && s.parent.flags & 32 /* Class */ ? flags : flags & ~28 /* AccessibilityModifier */;
17363         }
17364         if (getCheckFlags(s) & 6 /* Synthetic */) {
17365             var checkFlags = s.checkFlags;
17366             var accessModifier = checkFlags & 1024 /* ContainsPrivate */ ? 8 /* Private */ :
17367                 checkFlags & 256 /* ContainsPublic */ ? 4 /* Public */ :
17368                     16 /* Protected */;
17369             var staticModifier = checkFlags & 2048 /* ContainsStatic */ ? 32 /* Static */ : 0;
17370             return accessModifier | staticModifier;
17371         }
17372         if (s.flags & 4194304 /* Prototype */) {
17373             return 4 /* Public */ | 32 /* Static */;
17374         }
17375         return 0;
17376     }
17377     ts.getDeclarationModifierFlagsFromSymbol = getDeclarationModifierFlagsFromSymbol;
17378     function skipAlias(symbol, checker) {
17379         return symbol.flags & 2097152 /* Alias */ ? checker.getAliasedSymbol(symbol) : symbol;
17380     }
17381     ts.skipAlias = skipAlias;
17382     /** See comment on `declareModuleMember` in `binder.ts`. */
17383     function getCombinedLocalAndExportSymbolFlags(symbol) {
17384         return symbol.exportSymbol ? symbol.exportSymbol.flags | symbol.flags : symbol.flags;
17385     }
17386     ts.getCombinedLocalAndExportSymbolFlags = getCombinedLocalAndExportSymbolFlags;
17387     function isWriteOnlyAccess(node) {
17388         return accessKind(node) === 1 /* Write */;
17389     }
17390     ts.isWriteOnlyAccess = isWriteOnlyAccess;
17391     function isWriteAccess(node) {
17392         return accessKind(node) !== 0 /* Read */;
17393     }
17394     ts.isWriteAccess = isWriteAccess;
17395     var AccessKind;
17396     (function (AccessKind) {
17397         /** Only reads from a variable. */
17398         AccessKind[AccessKind["Read"] = 0] = "Read";
17399         /** Only writes to a variable without using the result. E.g.: `x++;`. */
17400         AccessKind[AccessKind["Write"] = 1] = "Write";
17401         /** Writes to a variable and uses the result as an expression. E.g.: `f(x++);`. */
17402         AccessKind[AccessKind["ReadWrite"] = 2] = "ReadWrite";
17403     })(AccessKind || (AccessKind = {}));
17404     function accessKind(node) {
17405         var parent = node.parent;
17406         if (!parent)
17407             return 0 /* Read */;
17408         switch (parent.kind) {
17409             case 200 /* ParenthesizedExpression */:
17410                 return accessKind(parent);
17411             case 208 /* PostfixUnaryExpression */:
17412             case 207 /* PrefixUnaryExpression */:
17413                 var operator = parent.operator;
17414                 return operator === 45 /* PlusPlusToken */ || operator === 46 /* MinusMinusToken */ ? writeOrReadWrite() : 0 /* Read */;
17415             case 209 /* BinaryExpression */:
17416                 var _a = parent, left = _a.left, operatorToken = _a.operatorToken;
17417                 return left === node && isAssignmentOperator(operatorToken.kind) ?
17418                     operatorToken.kind === 62 /* EqualsToken */ ? 1 /* Write */ : writeOrReadWrite()
17419                     : 0 /* Read */;
17420             case 194 /* PropertyAccessExpression */:
17421                 return parent.name !== node ? 0 /* Read */ : accessKind(parent);
17422             case 281 /* PropertyAssignment */: {
17423                 var parentAccess = accessKind(parent.parent);
17424                 // In `({ x: varname }) = { x: 1 }`, the left `x` is a read, the right `x` is a write.
17425                 return node === parent.name ? reverseAccessKind(parentAccess) : parentAccess;
17426             }
17427             case 282 /* ShorthandPropertyAssignment */:
17428                 // Assume it's the local variable being accessed, since we don't check public properties for --noUnusedLocals.
17429                 return node === parent.objectAssignmentInitializer ? 0 /* Read */ : accessKind(parent.parent);
17430             case 192 /* ArrayLiteralExpression */:
17431                 return accessKind(parent);
17432             default:
17433                 return 0 /* Read */;
17434         }
17435         function writeOrReadWrite() {
17436             // If grandparent is not an ExpressionStatement, this is used as an expression in addition to having a side effect.
17437             return parent.parent && skipParenthesesUp(parent.parent).kind === 226 /* ExpressionStatement */ ? 1 /* Write */ : 2 /* ReadWrite */;
17438         }
17439     }
17440     function reverseAccessKind(a) {
17441         switch (a) {
17442             case 0 /* Read */:
17443                 return 1 /* Write */;
17444             case 1 /* Write */:
17445                 return 0 /* Read */;
17446             case 2 /* ReadWrite */:
17447                 return 2 /* ReadWrite */;
17448             default:
17449                 return ts.Debug.assertNever(a);
17450         }
17451     }
17452     function compareDataObjects(dst, src) {
17453         if (!dst || !src || Object.keys(dst).length !== Object.keys(src).length) {
17454             return false;
17455         }
17456         for (var e in dst) {
17457             if (typeof dst[e] === "object") {
17458                 if (!compareDataObjects(dst[e], src[e])) {
17459                     return false;
17460                 }
17461             }
17462             else if (typeof dst[e] !== "function") {
17463                 if (dst[e] !== src[e]) {
17464                     return false;
17465                 }
17466             }
17467         }
17468         return true;
17469     }
17470     ts.compareDataObjects = compareDataObjects;
17471     /**
17472      * clears already present map by calling onDeleteExistingValue callback before deleting that key/value
17473      */
17474     function clearMap(map, onDeleteValue) {
17475         // Remove all
17476         map.forEach(onDeleteValue);
17477         map.clear();
17478     }
17479     ts.clearMap = clearMap;
17480     /**
17481      * Mutates the map with newMap such that keys in map will be same as newMap.
17482      */
17483     function mutateMapSkippingNewValues(map, newMap, options) {
17484         var onDeleteValue = options.onDeleteValue, onExistingValue = options.onExistingValue;
17485         // Needs update
17486         map.forEach(function (existingValue, key) {
17487             var valueInNewMap = newMap.get(key);
17488             // Not present any more in new map, remove it
17489             if (valueInNewMap === undefined) {
17490                 map.delete(key);
17491                 onDeleteValue(existingValue, key);
17492             }
17493             // If present notify about existing values
17494             else if (onExistingValue) {
17495                 onExistingValue(existingValue, valueInNewMap, key);
17496             }
17497         });
17498     }
17499     ts.mutateMapSkippingNewValues = mutateMapSkippingNewValues;
17500     /**
17501      * Mutates the map with newMap such that keys in map will be same as newMap.
17502      */
17503     function mutateMap(map, newMap, options) {
17504         // Needs update
17505         mutateMapSkippingNewValues(map, newMap, options);
17506         var createNewValue = options.createNewValue;
17507         // Add new values that are not already present
17508         newMap.forEach(function (valueInNewMap, key) {
17509             if (!map.has(key)) {
17510                 // New values
17511                 map.set(key, createNewValue(key, valueInNewMap));
17512             }
17513         });
17514     }
17515     ts.mutateMap = mutateMap;
17516     // Return true if the given type is the constructor type for an abstract class
17517     function isAbstractConstructorType(type) {
17518         return !!(getObjectFlags(type) & 16 /* Anonymous */) && !!type.symbol && isAbstractConstructorSymbol(type.symbol);
17519     }
17520     ts.isAbstractConstructorType = isAbstractConstructorType;
17521     function isAbstractConstructorSymbol(symbol) {
17522         if (symbol.flags & 32 /* Class */) {
17523             var declaration = getClassLikeDeclarationOfSymbol(symbol);
17524             return !!declaration && hasModifier(declaration, 128 /* Abstract */);
17525         }
17526         return false;
17527     }
17528     ts.isAbstractConstructorSymbol = isAbstractConstructorSymbol;
17529     function getClassLikeDeclarationOfSymbol(symbol) {
17530         return ts.find(symbol.declarations, ts.isClassLike);
17531     }
17532     ts.getClassLikeDeclarationOfSymbol = getClassLikeDeclarationOfSymbol;
17533     function getObjectFlags(type) {
17534         return type.flags & 3899393 /* ObjectFlagsType */ ? type.objectFlags : 0;
17535     }
17536     ts.getObjectFlags = getObjectFlags;
17537     function typeHasCallOrConstructSignatures(type, checker) {
17538         return checker.getSignaturesOfType(type, 0 /* Call */).length !== 0 || checker.getSignaturesOfType(type, 1 /* Construct */).length !== 0;
17539     }
17540     ts.typeHasCallOrConstructSignatures = typeHasCallOrConstructSignatures;
17541     function forSomeAncestorDirectory(directory, callback) {
17542         return !!ts.forEachAncestorDirectory(directory, function (d) { return callback(d) ? true : undefined; });
17543     }
17544     ts.forSomeAncestorDirectory = forSomeAncestorDirectory;
17545     function isUMDExportSymbol(symbol) {
17546         return !!symbol && !!symbol.declarations && !!symbol.declarations[0] && ts.isNamespaceExportDeclaration(symbol.declarations[0]);
17547     }
17548     ts.isUMDExportSymbol = isUMDExportSymbol;
17549     function showModuleSpecifier(_a) {
17550         var moduleSpecifier = _a.moduleSpecifier;
17551         return ts.isStringLiteral(moduleSpecifier) ? moduleSpecifier.text : getTextOfNode(moduleSpecifier);
17552     }
17553     ts.showModuleSpecifier = showModuleSpecifier;
17554     function getLastChild(node) {
17555         var lastChild;
17556         ts.forEachChild(node, function (child) {
17557             if (nodeIsPresent(child))
17558                 lastChild = child;
17559         }, function (children) {
17560             // As an optimization, jump straight to the end of the list.
17561             for (var i = children.length - 1; i >= 0; i--) {
17562                 if (nodeIsPresent(children[i])) {
17563                     lastChild = children[i];
17564                     break;
17565                 }
17566             }
17567         });
17568         return lastChild;
17569     }
17570     ts.getLastChild = getLastChild;
17571     function addToSeen(seen, key, value) {
17572         if (value === void 0) { value = true; }
17573         key = String(key);
17574         if (seen.has(key)) {
17575             return false;
17576         }
17577         seen.set(key, value);
17578         return true;
17579     }
17580     ts.addToSeen = addToSeen;
17581     function isObjectTypeDeclaration(node) {
17582         return ts.isClassLike(node) || ts.isInterfaceDeclaration(node) || ts.isTypeLiteralNode(node);
17583     }
17584     ts.isObjectTypeDeclaration = isObjectTypeDeclaration;
17585     function isTypeNodeKind(kind) {
17586         return (kind >= 168 /* FirstTypeNode */ && kind <= 188 /* LastTypeNode */)
17587             || kind === 125 /* AnyKeyword */
17588             || kind === 148 /* UnknownKeyword */
17589             || kind === 140 /* NumberKeyword */
17590             || kind === 151 /* BigIntKeyword */
17591             || kind === 141 /* ObjectKeyword */
17592             || kind === 128 /* BooleanKeyword */
17593             || kind === 143 /* StringKeyword */
17594             || kind === 144 /* SymbolKeyword */
17595             || kind === 104 /* ThisKeyword */
17596             || kind === 110 /* VoidKeyword */
17597             || kind === 146 /* UndefinedKeyword */
17598             || kind === 100 /* NullKeyword */
17599             || kind === 137 /* NeverKeyword */
17600             || kind === 216 /* ExpressionWithTypeArguments */
17601             || kind === 295 /* JSDocAllType */
17602             || kind === 296 /* JSDocUnknownType */
17603             || kind === 297 /* JSDocNullableType */
17604             || kind === 298 /* JSDocNonNullableType */
17605             || kind === 299 /* JSDocOptionalType */
17606             || kind === 300 /* JSDocFunctionType */
17607             || kind === 301 /* JSDocVariadicType */;
17608     }
17609     ts.isTypeNodeKind = isTypeNodeKind;
17610     function isAccessExpression(node) {
17611         return node.kind === 194 /* PropertyAccessExpression */ || node.kind === 195 /* ElementAccessExpression */;
17612     }
17613     ts.isAccessExpression = isAccessExpression;
17614     function getNameOfAccessExpression(node) {
17615         if (node.kind === 194 /* PropertyAccessExpression */) {
17616             return node.name;
17617         }
17618         ts.Debug.assert(node.kind === 195 /* ElementAccessExpression */);
17619         return node.argumentExpression;
17620     }
17621     ts.getNameOfAccessExpression = getNameOfAccessExpression;
17622     function isBundleFileTextLike(section) {
17623         switch (section.kind) {
17624             case "text" /* Text */:
17625             case "internal" /* Internal */:
17626                 return true;
17627             default:
17628                 return false;
17629         }
17630     }
17631     ts.isBundleFileTextLike = isBundleFileTextLike;
17632     function isNamedImportsOrExports(node) {
17633         return node.kind === 257 /* NamedImports */ || node.kind === 261 /* NamedExports */;
17634     }
17635     ts.isNamedImportsOrExports = isNamedImportsOrExports;
17636     function Symbol(flags, name) {
17637         this.flags = flags;
17638         this.escapedName = name;
17639         this.declarations = undefined;
17640         this.valueDeclaration = undefined;
17641         this.id = undefined;
17642         this.mergeId = undefined;
17643         this.parent = undefined;
17644     }
17645     function Type(checker, flags) {
17646         this.flags = flags;
17647         if (ts.Debug.isDebugging) {
17648             this.checker = checker;
17649         }
17650     }
17651     function Signature(checker, flags) {
17652         this.flags = flags;
17653         if (ts.Debug.isDebugging) {
17654             this.checker = checker;
17655         }
17656     }
17657     function Node(kind, pos, end) {
17658         this.pos = pos;
17659         this.end = end;
17660         this.kind = kind;
17661         this.id = 0;
17662         this.flags = 0 /* None */;
17663         this.modifierFlagsCache = 0 /* None */;
17664         this.transformFlags = 0 /* None */;
17665         this.parent = undefined;
17666         this.original = undefined;
17667     }
17668     function Token(kind, pos, end) {
17669         this.pos = pos;
17670         this.end = end;
17671         this.kind = kind;
17672         this.id = 0;
17673         this.flags = 0 /* None */;
17674         this.transformFlags = 0 /* None */;
17675         this.parent = undefined;
17676     }
17677     function Identifier(kind, pos, end) {
17678         this.pos = pos;
17679         this.end = end;
17680         this.kind = kind;
17681         this.id = 0;
17682         this.flags = 0 /* None */;
17683         this.transformFlags = 0 /* None */;
17684         this.parent = undefined;
17685         this.original = undefined;
17686         this.flowNode = undefined;
17687     }
17688     function SourceMapSource(fileName, text, skipTrivia) {
17689         this.fileName = fileName;
17690         this.text = text;
17691         this.skipTrivia = skipTrivia || (function (pos) { return pos; });
17692     }
17693     // eslint-disable-next-line prefer-const
17694     ts.objectAllocator = {
17695         getNodeConstructor: function () { return Node; },
17696         getTokenConstructor: function () { return Token; },
17697         getIdentifierConstructor: function () { return Identifier; },
17698         getPrivateIdentifierConstructor: function () { return Node; },
17699         getSourceFileConstructor: function () { return Node; },
17700         getSymbolConstructor: function () { return Symbol; },
17701         getTypeConstructor: function () { return Type; },
17702         getSignatureConstructor: function () { return Signature; },
17703         getSourceMapSourceConstructor: function () { return SourceMapSource; },
17704     };
17705     function setObjectAllocator(alloc) {
17706         ts.objectAllocator = alloc;
17707     }
17708     ts.setObjectAllocator = setObjectAllocator;
17709     function formatStringFromArgs(text, args, baseIndex) {
17710         if (baseIndex === void 0) { baseIndex = 0; }
17711         return text.replace(/{(\d+)}/g, function (_match, index) { return "" + ts.Debug.checkDefined(args[+index + baseIndex]); });
17712     }
17713     ts.formatStringFromArgs = formatStringFromArgs;
17714     /* @internal */
17715     function setLocalizedDiagnosticMessages(messages) {
17716         ts.localizedDiagnosticMessages = messages;
17717     }
17718     ts.setLocalizedDiagnosticMessages = setLocalizedDiagnosticMessages;
17719     function getLocaleSpecificMessage(message) {
17720         return ts.localizedDiagnosticMessages && ts.localizedDiagnosticMessages[message.key] || message.message;
17721     }
17722     ts.getLocaleSpecificMessage = getLocaleSpecificMessage;
17723     function createFileDiagnostic(file, start, length, message) {
17724         ts.Debug.assertGreaterThanOrEqual(start, 0);
17725         ts.Debug.assertGreaterThanOrEqual(length, 0);
17726         if (file) {
17727             ts.Debug.assertLessThanOrEqual(start, file.text.length);
17728             ts.Debug.assertLessThanOrEqual(start + length, file.text.length);
17729         }
17730         var text = getLocaleSpecificMessage(message);
17731         if (arguments.length > 4) {
17732             text = formatStringFromArgs(text, arguments, 4);
17733         }
17734         return {
17735             file: file,
17736             start: start,
17737             length: length,
17738             messageText: text,
17739             category: message.category,
17740             code: message.code,
17741             reportsUnnecessary: message.reportsUnnecessary,
17742         };
17743     }
17744     ts.createFileDiagnostic = createFileDiagnostic;
17745     function formatMessage(_dummy, message) {
17746         var text = getLocaleSpecificMessage(message);
17747         if (arguments.length > 2) {
17748             text = formatStringFromArgs(text, arguments, 2);
17749         }
17750         return text;
17751     }
17752     ts.formatMessage = formatMessage;
17753     function createCompilerDiagnostic(message) {
17754         var text = getLocaleSpecificMessage(message);
17755         if (arguments.length > 1) {
17756             text = formatStringFromArgs(text, arguments, 1);
17757         }
17758         return {
17759             file: undefined,
17760             start: undefined,
17761             length: undefined,
17762             messageText: text,
17763             category: message.category,
17764             code: message.code,
17765             reportsUnnecessary: message.reportsUnnecessary,
17766         };
17767     }
17768     ts.createCompilerDiagnostic = createCompilerDiagnostic;
17769     function createCompilerDiagnosticFromMessageChain(chain) {
17770         return {
17771             file: undefined,
17772             start: undefined,
17773             length: undefined,
17774             code: chain.code,
17775             category: chain.category,
17776             messageText: chain.next ? chain : chain.messageText,
17777         };
17778     }
17779     ts.createCompilerDiagnosticFromMessageChain = createCompilerDiagnosticFromMessageChain;
17780     function chainDiagnosticMessages(details, message) {
17781         var text = getLocaleSpecificMessage(message);
17782         if (arguments.length > 2) {
17783             text = formatStringFromArgs(text, arguments, 2);
17784         }
17785         return {
17786             messageText: text,
17787             category: message.category,
17788             code: message.code,
17789             next: details === undefined || Array.isArray(details) ? details : [details]
17790         };
17791     }
17792     ts.chainDiagnosticMessages = chainDiagnosticMessages;
17793     function concatenateDiagnosticMessageChains(headChain, tailChain) {
17794         var lastChain = headChain;
17795         while (lastChain.next) {
17796             lastChain = lastChain.next[0];
17797         }
17798         lastChain.next = [tailChain];
17799     }
17800     ts.concatenateDiagnosticMessageChains = concatenateDiagnosticMessageChains;
17801     function getDiagnosticFilePath(diagnostic) {
17802         return diagnostic.file ? diagnostic.file.path : undefined;
17803     }
17804     function compareDiagnostics(d1, d2) {
17805         return compareDiagnosticsSkipRelatedInformation(d1, d2) ||
17806             compareRelatedInformation(d1, d2) ||
17807             0 /* EqualTo */;
17808     }
17809     ts.compareDiagnostics = compareDiagnostics;
17810     function compareDiagnosticsSkipRelatedInformation(d1, d2) {
17811         return ts.compareStringsCaseSensitive(getDiagnosticFilePath(d1), getDiagnosticFilePath(d2)) ||
17812             ts.compareValues(d1.start, d2.start) ||
17813             ts.compareValues(d1.length, d2.length) ||
17814             ts.compareValues(d1.code, d2.code) ||
17815             compareMessageText(d1.messageText, d2.messageText) ||
17816             0 /* EqualTo */;
17817     }
17818     ts.compareDiagnosticsSkipRelatedInformation = compareDiagnosticsSkipRelatedInformation;
17819     function compareRelatedInformation(d1, d2) {
17820         if (!d1.relatedInformation && !d2.relatedInformation) {
17821             return 0 /* EqualTo */;
17822         }
17823         if (d1.relatedInformation && d2.relatedInformation) {
17824             return ts.compareValues(d1.relatedInformation.length, d2.relatedInformation.length) || ts.forEach(d1.relatedInformation, function (d1i, index) {
17825                 var d2i = d2.relatedInformation[index];
17826                 return compareDiagnostics(d1i, d2i); // EqualTo is 0, so falsy, and will cause the next item to be compared
17827             }) || 0 /* EqualTo */;
17828         }
17829         return d1.relatedInformation ? -1 /* LessThan */ : 1 /* GreaterThan */;
17830     }
17831     function compareMessageText(t1, t2) {
17832         if (typeof t1 === "string" && typeof t2 === "string") {
17833             return ts.compareStringsCaseSensitive(t1, t2);
17834         }
17835         else if (typeof t1 === "string") {
17836             return -1 /* LessThan */;
17837         }
17838         else if (typeof t2 === "string") {
17839             return 1 /* GreaterThan */;
17840         }
17841         var res = ts.compareStringsCaseSensitive(t1.messageText, t2.messageText);
17842         if (res) {
17843             return res;
17844         }
17845         if (!t1.next && !t2.next) {
17846             return 0 /* EqualTo */;
17847         }
17848         if (!t1.next) {
17849             return -1 /* LessThan */;
17850         }
17851         if (!t2.next) {
17852             return 1 /* GreaterThan */;
17853         }
17854         var len = Math.min(t1.next.length, t2.next.length);
17855         for (var i = 0; i < len; i++) {
17856             res = compareMessageText(t1.next[i], t2.next[i]);
17857             if (res) {
17858                 return res;
17859             }
17860         }
17861         if (t1.next.length < t2.next.length) {
17862             return -1 /* LessThan */;
17863         }
17864         else if (t1.next.length > t2.next.length) {
17865             return 1 /* GreaterThan */;
17866         }
17867         return 0 /* EqualTo */;
17868     }
17869     function getEmitScriptTarget(compilerOptions) {
17870         return compilerOptions.target || 0 /* ES3 */;
17871     }
17872     ts.getEmitScriptTarget = getEmitScriptTarget;
17873     function getEmitModuleKind(compilerOptions) {
17874         return typeof compilerOptions.module === "number" ?
17875             compilerOptions.module :
17876             getEmitScriptTarget(compilerOptions) >= 2 /* ES2015 */ ? ts.ModuleKind.ES2015 : ts.ModuleKind.CommonJS;
17877     }
17878     ts.getEmitModuleKind = getEmitModuleKind;
17879     function getEmitModuleResolutionKind(compilerOptions) {
17880         var moduleResolution = compilerOptions.moduleResolution;
17881         if (moduleResolution === undefined) {
17882             moduleResolution = getEmitModuleKind(compilerOptions) === ts.ModuleKind.CommonJS ? ts.ModuleResolutionKind.NodeJs : ts.ModuleResolutionKind.Classic;
17883         }
17884         return moduleResolution;
17885     }
17886     ts.getEmitModuleResolutionKind = getEmitModuleResolutionKind;
17887     function hasJsonModuleEmitEnabled(options) {
17888         switch (getEmitModuleKind(options)) {
17889             case ts.ModuleKind.CommonJS:
17890             case ts.ModuleKind.AMD:
17891             case ts.ModuleKind.ES2015:
17892             case ts.ModuleKind.ES2020:
17893             case ts.ModuleKind.ESNext:
17894                 return true;
17895             default:
17896                 return false;
17897         }
17898     }
17899     ts.hasJsonModuleEmitEnabled = hasJsonModuleEmitEnabled;
17900     function unreachableCodeIsError(options) {
17901         return options.allowUnreachableCode === false;
17902     }
17903     ts.unreachableCodeIsError = unreachableCodeIsError;
17904     function unusedLabelIsError(options) {
17905         return options.allowUnusedLabels === false;
17906     }
17907     ts.unusedLabelIsError = unusedLabelIsError;
17908     function getAreDeclarationMapsEnabled(options) {
17909         return !!(getEmitDeclarations(options) && options.declarationMap);
17910     }
17911     ts.getAreDeclarationMapsEnabled = getAreDeclarationMapsEnabled;
17912     function getAllowSyntheticDefaultImports(compilerOptions) {
17913         var moduleKind = getEmitModuleKind(compilerOptions);
17914         return compilerOptions.allowSyntheticDefaultImports !== undefined
17915             ? compilerOptions.allowSyntheticDefaultImports
17916             : compilerOptions.esModuleInterop ||
17917                 moduleKind === ts.ModuleKind.System;
17918     }
17919     ts.getAllowSyntheticDefaultImports = getAllowSyntheticDefaultImports;
17920     function getEmitDeclarations(compilerOptions) {
17921         return !!(compilerOptions.declaration || compilerOptions.composite);
17922     }
17923     ts.getEmitDeclarations = getEmitDeclarations;
17924     function isIncrementalCompilation(options) {
17925         return !!(options.incremental || options.composite);
17926     }
17927     ts.isIncrementalCompilation = isIncrementalCompilation;
17928     function getStrictOptionValue(compilerOptions, flag) {
17929         return compilerOptions[flag] === undefined ? !!compilerOptions.strict : !!compilerOptions[flag];
17930     }
17931     ts.getStrictOptionValue = getStrictOptionValue;
17932     function compilerOptionsAffectSemanticDiagnostics(newOptions, oldOptions) {
17933         return oldOptions !== newOptions &&
17934             ts.semanticDiagnosticsOptionDeclarations.some(function (option) { return !isJsonEqual(getCompilerOptionValue(oldOptions, option), getCompilerOptionValue(newOptions, option)); });
17935     }
17936     ts.compilerOptionsAffectSemanticDiagnostics = compilerOptionsAffectSemanticDiagnostics;
17937     function compilerOptionsAffectEmit(newOptions, oldOptions) {
17938         return oldOptions !== newOptions &&
17939             ts.affectsEmitOptionDeclarations.some(function (option) { return !isJsonEqual(getCompilerOptionValue(oldOptions, option), getCompilerOptionValue(newOptions, option)); });
17940     }
17941     ts.compilerOptionsAffectEmit = compilerOptionsAffectEmit;
17942     function getCompilerOptionValue(options, option) {
17943         return option.strictFlag ? getStrictOptionValue(options, option.name) : options[option.name];
17944     }
17945     ts.getCompilerOptionValue = getCompilerOptionValue;
17946     function hasZeroOrOneAsteriskCharacter(str) {
17947         var seenAsterisk = false;
17948         for (var i = 0; i < str.length; i++) {
17949             if (str.charCodeAt(i) === 42 /* asterisk */) {
17950                 if (!seenAsterisk) {
17951                     seenAsterisk = true;
17952                 }
17953                 else {
17954                     // have already seen asterisk
17955                     return false;
17956                 }
17957             }
17958         }
17959         return true;
17960     }
17961     ts.hasZeroOrOneAsteriskCharacter = hasZeroOrOneAsteriskCharacter;
17962     function discoverProbableSymlinks(files, getCanonicalFileName, cwd) {
17963         var result = ts.createMap();
17964         var symlinks = ts.flatten(ts.mapDefined(files, function (sf) {
17965             return sf.resolvedModules && ts.compact(ts.arrayFrom(ts.mapIterator(sf.resolvedModules.values(), function (res) {
17966                 return res && res.originalPath && res.resolvedFileName !== res.originalPath ? [res.resolvedFileName, res.originalPath] : undefined;
17967             })));
17968         }));
17969         for (var _i = 0, symlinks_1 = symlinks; _i < symlinks_1.length; _i++) {
17970             var _a = symlinks_1[_i], resolvedPath = _a[0], originalPath = _a[1];
17971             var _b = guessDirectorySymlink(resolvedPath, originalPath, cwd, getCanonicalFileName), commonResolved = _b[0], commonOriginal = _b[1];
17972             result.set(commonOriginal, commonResolved);
17973         }
17974         return result;
17975     }
17976     ts.discoverProbableSymlinks = discoverProbableSymlinks;
17977     function guessDirectorySymlink(a, b, cwd, getCanonicalFileName) {
17978         var aParts = ts.getPathComponents(ts.toPath(a, cwd, getCanonicalFileName));
17979         var bParts = ts.getPathComponents(ts.toPath(b, cwd, getCanonicalFileName));
17980         while (!isNodeModulesOrScopedPackageDirectory(aParts[aParts.length - 2], getCanonicalFileName) &&
17981             !isNodeModulesOrScopedPackageDirectory(bParts[bParts.length - 2], getCanonicalFileName) &&
17982             getCanonicalFileName(aParts[aParts.length - 1]) === getCanonicalFileName(bParts[bParts.length - 1])) {
17983             aParts.pop();
17984             bParts.pop();
17985         }
17986         return [ts.getPathFromPathComponents(aParts), ts.getPathFromPathComponents(bParts)];
17987     }
17988     // KLUDGE: Don't assume one 'node_modules' links to another. More likely a single directory inside the node_modules is the symlink.
17989     // ALso, don't assume that an `@foo` directory is linked. More likely the contents of that are linked.
17990     function isNodeModulesOrScopedPackageDirectory(s, getCanonicalFileName) {
17991         return getCanonicalFileName(s) === "node_modules" || ts.startsWith(s, "@");
17992     }
17993     function stripLeadingDirectorySeparator(s) {
17994         return ts.isAnyDirectorySeparator(s.charCodeAt(0)) ? s.slice(1) : undefined;
17995     }
17996     function tryRemoveDirectoryPrefix(path, dirPath, getCanonicalFileName) {
17997         var withoutPrefix = ts.tryRemovePrefix(path, dirPath, getCanonicalFileName);
17998         return withoutPrefix === undefined ? undefined : stripLeadingDirectorySeparator(withoutPrefix);
17999     }
18000     ts.tryRemoveDirectoryPrefix = tryRemoveDirectoryPrefix;
18001     // Reserved characters, forces escaping of any non-word (or digit), non-whitespace character.
18002     // It may be inefficient (we could just match (/[-[\]{}()*+?.,\\^$|#\s]/g), but this is future
18003     // proof.
18004     var reservedCharacterPattern = /[^\w\s\/]/g;
18005     function regExpEscape(text) {
18006         return text.replace(reservedCharacterPattern, escapeRegExpCharacter);
18007     }
18008     ts.regExpEscape = regExpEscape;
18009     function escapeRegExpCharacter(match) {
18010         return "\\" + match;
18011     }
18012     var wildcardCharCodes = [42 /* asterisk */, 63 /* question */];
18013     ts.commonPackageFolders = ["node_modules", "bower_components", "jspm_packages"];
18014     var implicitExcludePathRegexPattern = "(?!(" + ts.commonPackageFolders.join("|") + ")(/|$))";
18015     var filesMatcher = {
18016         /**
18017          * Matches any single directory segment unless it is the last segment and a .min.js file
18018          * Breakdown:
18019          *  [^./]                   # matches everything up to the first . character (excluding directory separators)
18020          *  (\\.(?!min\\.js$))?     # matches . characters but not if they are part of the .min.js file extension
18021          */
18022         singleAsteriskRegexFragment: "([^./]|(\\.(?!min\\.js$))?)*",
18023         /**
18024          * Regex for the ** wildcard. Matches any number of subdirectories. When used for including
18025          * files or directories, does not match subdirectories that start with a . character
18026          */
18027         doubleAsteriskRegexFragment: "(/" + implicitExcludePathRegexPattern + "[^/.][^/]*)*?",
18028         replaceWildcardCharacter: function (match) { return replaceWildcardCharacter(match, filesMatcher.singleAsteriskRegexFragment); }
18029     };
18030     var directoriesMatcher = {
18031         singleAsteriskRegexFragment: "[^/]*",
18032         /**
18033          * Regex for the ** wildcard. Matches any number of subdirectories. When used for including
18034          * files or directories, does not match subdirectories that start with a . character
18035          */
18036         doubleAsteriskRegexFragment: "(/" + implicitExcludePathRegexPattern + "[^/.][^/]*)*?",
18037         replaceWildcardCharacter: function (match) { return replaceWildcardCharacter(match, directoriesMatcher.singleAsteriskRegexFragment); }
18038     };
18039     var excludeMatcher = {
18040         singleAsteriskRegexFragment: "[^/]*",
18041         doubleAsteriskRegexFragment: "(/.+?)?",
18042         replaceWildcardCharacter: function (match) { return replaceWildcardCharacter(match, excludeMatcher.singleAsteriskRegexFragment); }
18043     };
18044     var wildcardMatchers = {
18045         files: filesMatcher,
18046         directories: directoriesMatcher,
18047         exclude: excludeMatcher
18048     };
18049     function getRegularExpressionForWildcard(specs, basePath, usage) {
18050         var patterns = getRegularExpressionsForWildcards(specs, basePath, usage);
18051         if (!patterns || !patterns.length) {
18052             return undefined;
18053         }
18054         var pattern = patterns.map(function (pattern) { return "(" + pattern + ")"; }).join("|");
18055         // If excluding, match "foo/bar/baz...", but if including, only allow "foo".
18056         var terminator = usage === "exclude" ? "($|/)" : "$";
18057         return "^(" + pattern + ")" + terminator;
18058     }
18059     ts.getRegularExpressionForWildcard = getRegularExpressionForWildcard;
18060     function getRegularExpressionsForWildcards(specs, basePath, usage) {
18061         if (specs === undefined || specs.length === 0) {
18062             return undefined;
18063         }
18064         return ts.flatMap(specs, function (spec) {
18065             return spec && getSubPatternFromSpec(spec, basePath, usage, wildcardMatchers[usage]);
18066         });
18067     }
18068     ts.getRegularExpressionsForWildcards = getRegularExpressionsForWildcards;
18069     /**
18070      * An "includes" path "foo" is implicitly a glob "foo/** /*" (without the space) if its last component has no extension,
18071      * and does not contain any glob characters itself.
18072      */
18073     function isImplicitGlob(lastPathComponent) {
18074         return !/[.*?]/.test(lastPathComponent);
18075     }
18076     ts.isImplicitGlob = isImplicitGlob;
18077     function getSubPatternFromSpec(spec, basePath, usage, _a) {
18078         var singleAsteriskRegexFragment = _a.singleAsteriskRegexFragment, doubleAsteriskRegexFragment = _a.doubleAsteriskRegexFragment, replaceWildcardCharacter = _a.replaceWildcardCharacter;
18079         var subpattern = "";
18080         var hasWrittenComponent = false;
18081         var components = ts.getNormalizedPathComponents(spec, basePath);
18082         var lastComponent = ts.last(components);
18083         if (usage !== "exclude" && lastComponent === "**") {
18084             return undefined;
18085         }
18086         // getNormalizedPathComponents includes the separator for the root component.
18087         // We need to remove to create our regex correctly.
18088         components[0] = ts.removeTrailingDirectorySeparator(components[0]);
18089         if (isImplicitGlob(lastComponent)) {
18090             components.push("**", "*");
18091         }
18092         var optionalCount = 0;
18093         for (var _i = 0, components_1 = components; _i < components_1.length; _i++) {
18094             var component = components_1[_i];
18095             if (component === "**") {
18096                 subpattern += doubleAsteriskRegexFragment;
18097             }
18098             else {
18099                 if (usage === "directories") {
18100                     subpattern += "(";
18101                     optionalCount++;
18102                 }
18103                 if (hasWrittenComponent) {
18104                     subpattern += ts.directorySeparator;
18105                 }
18106                 if (usage !== "exclude") {
18107                     var componentPattern = "";
18108                     // The * and ? wildcards should not match directories or files that start with . if they
18109                     // appear first in a component. Dotted directories and files can be included explicitly
18110                     // like so: **/.*/.*
18111                     if (component.charCodeAt(0) === 42 /* asterisk */) {
18112                         componentPattern += "([^./]" + singleAsteriskRegexFragment + ")?";
18113                         component = component.substr(1);
18114                     }
18115                     else if (component.charCodeAt(0) === 63 /* question */) {
18116                         componentPattern += "[^./]";
18117                         component = component.substr(1);
18118                     }
18119                     componentPattern += component.replace(reservedCharacterPattern, replaceWildcardCharacter);
18120                     // Patterns should not include subfolders like node_modules unless they are
18121                     // explicitly included as part of the path.
18122                     //
18123                     // As an optimization, if the component pattern is the same as the component,
18124                     // then there definitely were no wildcard characters and we do not need to
18125                     // add the exclusion pattern.
18126                     if (componentPattern !== component) {
18127                         subpattern += implicitExcludePathRegexPattern;
18128                     }
18129                     subpattern += componentPattern;
18130                 }
18131                 else {
18132                     subpattern += component.replace(reservedCharacterPattern, replaceWildcardCharacter);
18133                 }
18134             }
18135             hasWrittenComponent = true;
18136         }
18137         while (optionalCount > 0) {
18138             subpattern += ")?";
18139             optionalCount--;
18140         }
18141         return subpattern;
18142     }
18143     function replaceWildcardCharacter(match, singleAsteriskRegexFragment) {
18144         return match === "*" ? singleAsteriskRegexFragment : match === "?" ? "[^/]" : "\\" + match;
18145     }
18146     /** @param path directory of the tsconfig.json */
18147     function getFileMatcherPatterns(path, excludes, includes, useCaseSensitiveFileNames, currentDirectory) {
18148         path = ts.normalizePath(path);
18149         currentDirectory = ts.normalizePath(currentDirectory);
18150         var absolutePath = ts.combinePaths(currentDirectory, path);
18151         return {
18152             includeFilePatterns: ts.map(getRegularExpressionsForWildcards(includes, absolutePath, "files"), function (pattern) { return "^" + pattern + "$"; }),
18153             includeFilePattern: getRegularExpressionForWildcard(includes, absolutePath, "files"),
18154             includeDirectoryPattern: getRegularExpressionForWildcard(includes, absolutePath, "directories"),
18155             excludePattern: getRegularExpressionForWildcard(excludes, absolutePath, "exclude"),
18156             basePaths: getBasePaths(path, includes, useCaseSensitiveFileNames)
18157         };
18158     }
18159     ts.getFileMatcherPatterns = getFileMatcherPatterns;
18160     function getRegexFromPattern(pattern, useCaseSensitiveFileNames) {
18161         return new RegExp(pattern, useCaseSensitiveFileNames ? "" : "i");
18162     }
18163     ts.getRegexFromPattern = getRegexFromPattern;
18164     /** @param path directory of the tsconfig.json */
18165     function matchFiles(path, extensions, excludes, includes, useCaseSensitiveFileNames, currentDirectory, depth, getFileSystemEntries, realpath) {
18166         path = ts.normalizePath(path);
18167         currentDirectory = ts.normalizePath(currentDirectory);
18168         var patterns = getFileMatcherPatterns(path, excludes, includes, useCaseSensitiveFileNames, currentDirectory);
18169         var includeFileRegexes = patterns.includeFilePatterns && patterns.includeFilePatterns.map(function (pattern) { return getRegexFromPattern(pattern, useCaseSensitiveFileNames); });
18170         var includeDirectoryRegex = patterns.includeDirectoryPattern && getRegexFromPattern(patterns.includeDirectoryPattern, useCaseSensitiveFileNames);
18171         var excludeRegex = patterns.excludePattern && getRegexFromPattern(patterns.excludePattern, useCaseSensitiveFileNames);
18172         // Associate an array of results with each include regex. This keeps results in order of the "include" order.
18173         // If there are no "includes", then just put everything in results[0].
18174         var results = includeFileRegexes ? includeFileRegexes.map(function () { return []; }) : [[]];
18175         var visited = ts.createMap();
18176         var toCanonical = ts.createGetCanonicalFileName(useCaseSensitiveFileNames);
18177         for (var _i = 0, _a = patterns.basePaths; _i < _a.length; _i++) {
18178             var basePath = _a[_i];
18179             visitDirectory(basePath, ts.combinePaths(currentDirectory, basePath), depth);
18180         }
18181         return ts.flatten(results);
18182         function visitDirectory(path, absolutePath, depth) {
18183             var canonicalPath = toCanonical(realpath(absolutePath));
18184             if (visited.has(canonicalPath))
18185                 return;
18186             visited.set(canonicalPath, true);
18187             var _a = getFileSystemEntries(path), files = _a.files, directories = _a.directories;
18188             var _loop_1 = function (current) {
18189                 var name = ts.combinePaths(path, current);
18190                 var absoluteName = ts.combinePaths(absolutePath, current);
18191                 if (extensions && !ts.fileExtensionIsOneOf(name, extensions))
18192                     return "continue";
18193                 if (excludeRegex && excludeRegex.test(absoluteName))
18194                     return "continue";
18195                 if (!includeFileRegexes) {
18196                     results[0].push(name);
18197                 }
18198                 else {
18199                     var includeIndex = ts.findIndex(includeFileRegexes, function (re) { return re.test(absoluteName); });
18200                     if (includeIndex !== -1) {
18201                         results[includeIndex].push(name);
18202                     }
18203                 }
18204             };
18205             for (var _i = 0, _b = ts.sort(files, ts.compareStringsCaseSensitive); _i < _b.length; _i++) {
18206                 var current = _b[_i];
18207                 _loop_1(current);
18208             }
18209             if (depth !== undefined) {
18210                 depth--;
18211                 if (depth === 0) {
18212                     return;
18213                 }
18214             }
18215             for (var _c = 0, _d = ts.sort(directories, ts.compareStringsCaseSensitive); _c < _d.length; _c++) {
18216                 var current = _d[_c];
18217                 var name = ts.combinePaths(path, current);
18218                 var absoluteName = ts.combinePaths(absolutePath, current);
18219                 if ((!includeDirectoryRegex || includeDirectoryRegex.test(absoluteName)) &&
18220                     (!excludeRegex || !excludeRegex.test(absoluteName))) {
18221                     visitDirectory(name, absoluteName, depth);
18222                 }
18223             }
18224         }
18225     }
18226     ts.matchFiles = matchFiles;
18227     /**
18228      * Computes the unique non-wildcard base paths amongst the provided include patterns.
18229      */
18230     function getBasePaths(path, includes, useCaseSensitiveFileNames) {
18231         // Storage for our results in the form of literal paths (e.g. the paths as written by the user).
18232         var basePaths = [path];
18233         if (includes) {
18234             // Storage for literal base paths amongst the include patterns.
18235             var includeBasePaths = [];
18236             for (var _i = 0, includes_1 = includes; _i < includes_1.length; _i++) {
18237                 var include = includes_1[_i];
18238                 // We also need to check the relative paths by converting them to absolute and normalizing
18239                 // in case they escape the base path (e.g "..\somedirectory")
18240                 var absolute = ts.isRootedDiskPath(include) ? include : ts.normalizePath(ts.combinePaths(path, include));
18241                 // Append the literal and canonical candidate base paths.
18242                 includeBasePaths.push(getIncludeBasePath(absolute));
18243             }
18244             // Sort the offsets array using either the literal or canonical path representations.
18245             includeBasePaths.sort(ts.getStringComparer(!useCaseSensitiveFileNames));
18246             var _loop_2 = function (includeBasePath) {
18247                 if (ts.every(basePaths, function (basePath) { return !ts.containsPath(basePath, includeBasePath, path, !useCaseSensitiveFileNames); })) {
18248                     basePaths.push(includeBasePath);
18249                 }
18250             };
18251             // Iterate over each include base path and include unique base paths that are not a
18252             // subpath of an existing base path
18253             for (var _a = 0, includeBasePaths_1 = includeBasePaths; _a < includeBasePaths_1.length; _a++) {
18254                 var includeBasePath = includeBasePaths_1[_a];
18255                 _loop_2(includeBasePath);
18256             }
18257         }
18258         return basePaths;
18259     }
18260     function getIncludeBasePath(absolute) {
18261         var wildcardOffset = ts.indexOfAnyCharCode(absolute, wildcardCharCodes);
18262         if (wildcardOffset < 0) {
18263             // No "*" or "?" in the path
18264             return !ts.hasExtension(absolute)
18265                 ? absolute
18266                 : ts.removeTrailingDirectorySeparator(ts.getDirectoryPath(absolute));
18267         }
18268         return absolute.substring(0, absolute.lastIndexOf(ts.directorySeparator, wildcardOffset));
18269     }
18270     function ensureScriptKind(fileName, scriptKind) {
18271         // Using scriptKind as a condition handles both:
18272         // - 'scriptKind' is unspecified and thus it is `undefined`
18273         // - 'scriptKind' is set and it is `Unknown` (0)
18274         // If the 'scriptKind' is 'undefined' or 'Unknown' then we attempt
18275         // to get the ScriptKind from the file name. If it cannot be resolved
18276         // from the file name then the default 'TS' script kind is returned.
18277         return scriptKind || getScriptKindFromFileName(fileName) || 3 /* TS */;
18278     }
18279     ts.ensureScriptKind = ensureScriptKind;
18280     function getScriptKindFromFileName(fileName) {
18281         var ext = fileName.substr(fileName.lastIndexOf("."));
18282         switch (ext.toLowerCase()) {
18283             case ".js" /* Js */:
18284                 return 1 /* JS */;
18285             case ".jsx" /* Jsx */:
18286                 return 2 /* JSX */;
18287             case ".ts" /* Ts */:
18288                 return 3 /* TS */;
18289             case ".tsx" /* Tsx */:
18290                 return 4 /* TSX */;
18291             case ".json" /* Json */:
18292                 return 6 /* JSON */;
18293             default:
18294                 return 0 /* Unknown */;
18295         }
18296     }
18297     ts.getScriptKindFromFileName = getScriptKindFromFileName;
18298     /**
18299      *  List of supported extensions in order of file resolution precedence.
18300      */
18301     ts.supportedTSExtensions = [".ts" /* Ts */, ".tsx" /* Tsx */, ".d.ts" /* Dts */];
18302     ts.supportedTSExtensionsWithJson = [".ts" /* Ts */, ".tsx" /* Tsx */, ".d.ts" /* Dts */, ".json" /* Json */];
18303     /** Must have ".d.ts" first because if ".ts" goes first, that will be detected as the extension instead of ".d.ts". */
18304     ts.supportedTSExtensionsForExtractExtension = [".d.ts" /* Dts */, ".ts" /* Ts */, ".tsx" /* Tsx */];
18305     ts.supportedJSExtensions = [".js" /* Js */, ".jsx" /* Jsx */];
18306     ts.supportedJSAndJsonExtensions = [".js" /* Js */, ".jsx" /* Jsx */, ".json" /* Json */];
18307     var allSupportedExtensions = __spreadArrays(ts.supportedTSExtensions, ts.supportedJSExtensions);
18308     var allSupportedExtensionsWithJson = __spreadArrays(ts.supportedTSExtensions, ts.supportedJSExtensions, [".json" /* Json */]);
18309     function getSupportedExtensions(options, extraFileExtensions) {
18310         var needJsExtensions = options && options.allowJs;
18311         if (!extraFileExtensions || extraFileExtensions.length === 0) {
18312             return needJsExtensions ? allSupportedExtensions : ts.supportedTSExtensions;
18313         }
18314         var extensions = __spreadArrays(needJsExtensions ? allSupportedExtensions : ts.supportedTSExtensions, ts.mapDefined(extraFileExtensions, function (x) { return x.scriptKind === 7 /* Deferred */ || needJsExtensions && isJSLike(x.scriptKind) ? x.extension : undefined; }));
18315         return ts.deduplicate(extensions, ts.equateStringsCaseSensitive, ts.compareStringsCaseSensitive);
18316     }
18317     ts.getSupportedExtensions = getSupportedExtensions;
18318     function getSuppoertedExtensionsWithJsonIfResolveJsonModule(options, supportedExtensions) {
18319         if (!options || !options.resolveJsonModule) {
18320             return supportedExtensions;
18321         }
18322         if (supportedExtensions === allSupportedExtensions) {
18323             return allSupportedExtensionsWithJson;
18324         }
18325         if (supportedExtensions === ts.supportedTSExtensions) {
18326             return ts.supportedTSExtensionsWithJson;
18327         }
18328         return __spreadArrays(supportedExtensions, [".json" /* Json */]);
18329     }
18330     ts.getSuppoertedExtensionsWithJsonIfResolveJsonModule = getSuppoertedExtensionsWithJsonIfResolveJsonModule;
18331     function isJSLike(scriptKind) {
18332         return scriptKind === 1 /* JS */ || scriptKind === 2 /* JSX */;
18333     }
18334     function hasJSFileExtension(fileName) {
18335         return ts.some(ts.supportedJSExtensions, function (extension) { return ts.fileExtensionIs(fileName, extension); });
18336     }
18337     ts.hasJSFileExtension = hasJSFileExtension;
18338     function hasTSFileExtension(fileName) {
18339         return ts.some(ts.supportedTSExtensions, function (extension) { return ts.fileExtensionIs(fileName, extension); });
18340     }
18341     ts.hasTSFileExtension = hasTSFileExtension;
18342     function isSupportedSourceFileName(fileName, compilerOptions, extraFileExtensions) {
18343         if (!fileName) {
18344             return false;
18345         }
18346         var supportedExtensions = getSupportedExtensions(compilerOptions, extraFileExtensions);
18347         for (var _i = 0, _a = getSuppoertedExtensionsWithJsonIfResolveJsonModule(compilerOptions, supportedExtensions); _i < _a.length; _i++) {
18348             var extension = _a[_i];
18349             if (ts.fileExtensionIs(fileName, extension)) {
18350                 return true;
18351             }
18352         }
18353         return false;
18354     }
18355     ts.isSupportedSourceFileName = isSupportedSourceFileName;
18356     /**
18357      * Extension boundaries by priority. Lower numbers indicate higher priorities, and are
18358      * aligned to the offset of the highest priority extension in the
18359      * allSupportedExtensions array.
18360      */
18361     var ExtensionPriority;
18362     (function (ExtensionPriority) {
18363         ExtensionPriority[ExtensionPriority["TypeScriptFiles"] = 0] = "TypeScriptFiles";
18364         ExtensionPriority[ExtensionPriority["DeclarationAndJavaScriptFiles"] = 2] = "DeclarationAndJavaScriptFiles";
18365         ExtensionPriority[ExtensionPriority["Highest"] = 0] = "Highest";
18366         ExtensionPriority[ExtensionPriority["Lowest"] = 2] = "Lowest";
18367     })(ExtensionPriority = ts.ExtensionPriority || (ts.ExtensionPriority = {}));
18368     function getExtensionPriority(path, supportedExtensions) {
18369         for (var i = supportedExtensions.length - 1; i >= 0; i--) {
18370             if (ts.fileExtensionIs(path, supportedExtensions[i])) {
18371                 return adjustExtensionPriority(i, supportedExtensions);
18372             }
18373         }
18374         // If its not in the list of supported extensions, this is likely a
18375         // TypeScript file with a non-ts extension
18376         return 0 /* Highest */;
18377     }
18378     ts.getExtensionPriority = getExtensionPriority;
18379     /**
18380      * Adjusts an extension priority to be the highest priority within the same range.
18381      */
18382     function adjustExtensionPriority(extensionPriority, supportedExtensions) {
18383         if (extensionPriority < 2 /* DeclarationAndJavaScriptFiles */) {
18384             return 0 /* TypeScriptFiles */;
18385         }
18386         else if (extensionPriority < supportedExtensions.length) {
18387             return 2 /* DeclarationAndJavaScriptFiles */;
18388         }
18389         else {
18390             return supportedExtensions.length;
18391         }
18392     }
18393     ts.adjustExtensionPriority = adjustExtensionPriority;
18394     /**
18395      * Gets the next lowest extension priority for a given priority.
18396      */
18397     function getNextLowestExtensionPriority(extensionPriority, supportedExtensions) {
18398         if (extensionPriority < 2 /* DeclarationAndJavaScriptFiles */) {
18399             return 2 /* DeclarationAndJavaScriptFiles */;
18400         }
18401         else {
18402             return supportedExtensions.length;
18403         }
18404     }
18405     ts.getNextLowestExtensionPriority = getNextLowestExtensionPriority;
18406     var extensionsToRemove = [".d.ts" /* Dts */, ".ts" /* Ts */, ".js" /* Js */, ".tsx" /* Tsx */, ".jsx" /* Jsx */, ".json" /* Json */];
18407     function removeFileExtension(path) {
18408         for (var _i = 0, extensionsToRemove_1 = extensionsToRemove; _i < extensionsToRemove_1.length; _i++) {
18409             var ext = extensionsToRemove_1[_i];
18410             var extensionless = tryRemoveExtension(path, ext);
18411             if (extensionless !== undefined) {
18412                 return extensionless;
18413             }
18414         }
18415         return path;
18416     }
18417     ts.removeFileExtension = removeFileExtension;
18418     function tryRemoveExtension(path, extension) {
18419         return ts.fileExtensionIs(path, extension) ? removeExtension(path, extension) : undefined;
18420     }
18421     ts.tryRemoveExtension = tryRemoveExtension;
18422     function removeExtension(path, extension) {
18423         return path.substring(0, path.length - extension.length);
18424     }
18425     ts.removeExtension = removeExtension;
18426     function changeExtension(path, newExtension) {
18427         return ts.changeAnyExtension(path, newExtension, extensionsToRemove, /*ignoreCase*/ false);
18428     }
18429     ts.changeExtension = changeExtension;
18430     function tryParsePattern(pattern) {
18431         // This should be verified outside of here and a proper error thrown.
18432         ts.Debug.assert(hasZeroOrOneAsteriskCharacter(pattern));
18433         var indexOfStar = pattern.indexOf("*");
18434         return indexOfStar === -1 ? undefined : {
18435             prefix: pattern.substr(0, indexOfStar),
18436             suffix: pattern.substr(indexOfStar + 1)
18437         };
18438     }
18439     ts.tryParsePattern = tryParsePattern;
18440     function positionIsSynthesized(pos) {
18441         // This is a fast way of testing the following conditions:
18442         //  pos === undefined || pos === null || isNaN(pos) || pos < 0;
18443         return !(pos >= 0);
18444     }
18445     ts.positionIsSynthesized = positionIsSynthesized;
18446     /** True if an extension is one of the supported TypeScript extensions. */
18447     function extensionIsTS(ext) {
18448         return ext === ".ts" /* Ts */ || ext === ".tsx" /* Tsx */ || ext === ".d.ts" /* Dts */;
18449     }
18450     ts.extensionIsTS = extensionIsTS;
18451     function resolutionExtensionIsTSOrJson(ext) {
18452         return extensionIsTS(ext) || ext === ".json" /* Json */;
18453     }
18454     ts.resolutionExtensionIsTSOrJson = resolutionExtensionIsTSOrJson;
18455     /**
18456      * Gets the extension from a path.
18457      * Path must have a valid extension.
18458      */
18459     function extensionFromPath(path) {
18460         var ext = tryGetExtensionFromPath(path);
18461         return ext !== undefined ? ext : ts.Debug.fail("File " + path + " has unknown extension.");
18462     }
18463     ts.extensionFromPath = extensionFromPath;
18464     function isAnySupportedFileExtension(path) {
18465         return tryGetExtensionFromPath(path) !== undefined;
18466     }
18467     ts.isAnySupportedFileExtension = isAnySupportedFileExtension;
18468     function tryGetExtensionFromPath(path) {
18469         return ts.find(extensionsToRemove, function (e) { return ts.fileExtensionIs(path, e); });
18470     }
18471     ts.tryGetExtensionFromPath = tryGetExtensionFromPath;
18472     function isCheckJsEnabledForFile(sourceFile, compilerOptions) {
18473         return sourceFile.checkJsDirective ? sourceFile.checkJsDirective.enabled : compilerOptions.checkJs;
18474     }
18475     ts.isCheckJsEnabledForFile = isCheckJsEnabledForFile;
18476     ts.emptyFileSystemEntries = {
18477         files: ts.emptyArray,
18478         directories: ts.emptyArray
18479     };
18480     /**
18481      * patternStrings contains both pattern strings (containing "*") and regular strings.
18482      * Return an exact match if possible, or a pattern match, or undefined.
18483      * (These are verified by verifyCompilerOptions to have 0 or 1 "*" characters.)
18484      */
18485     function matchPatternOrExact(patternStrings, candidate) {
18486         var patterns = [];
18487         for (var _i = 0, patternStrings_1 = patternStrings; _i < patternStrings_1.length; _i++) {
18488             var patternString = patternStrings_1[_i];
18489             if (!hasZeroOrOneAsteriskCharacter(patternString))
18490                 continue;
18491             var pattern = tryParsePattern(patternString);
18492             if (pattern) {
18493                 patterns.push(pattern);
18494             }
18495             else if (patternString === candidate) {
18496                 // pattern was matched as is - no need to search further
18497                 return patternString;
18498             }
18499         }
18500         return ts.findBestPatternMatch(patterns, function (_) { return _; }, candidate);
18501     }
18502     ts.matchPatternOrExact = matchPatternOrExact;
18503     function sliceAfter(arr, value) {
18504         var index = arr.indexOf(value);
18505         ts.Debug.assert(index !== -1);
18506         return arr.slice(index);
18507     }
18508     ts.sliceAfter = sliceAfter;
18509     function addRelatedInfo(diagnostic) {
18510         var _a;
18511         var relatedInformation = [];
18512         for (var _i = 1; _i < arguments.length; _i++) {
18513             relatedInformation[_i - 1] = arguments[_i];
18514         }
18515         if (!relatedInformation.length) {
18516             return diagnostic;
18517         }
18518         if (!diagnostic.relatedInformation) {
18519             diagnostic.relatedInformation = [];
18520         }
18521         (_a = diagnostic.relatedInformation).push.apply(_a, relatedInformation);
18522         return diagnostic;
18523     }
18524     ts.addRelatedInfo = addRelatedInfo;
18525     function minAndMax(arr, getValue) {
18526         ts.Debug.assert(arr.length !== 0);
18527         var min = getValue(arr[0]);
18528         var max = min;
18529         for (var i = 1; i < arr.length; i++) {
18530             var value = getValue(arr[i]);
18531             if (value < min) {
18532                 min = value;
18533             }
18534             else if (value > max) {
18535                 max = value;
18536             }
18537         }
18538         return { min: min, max: max };
18539     }
18540     ts.minAndMax = minAndMax;
18541     var NodeSet = /** @class */ (function () {
18542         function NodeSet() {
18543             this.map = ts.createMap();
18544         }
18545         NodeSet.prototype.add = function (node) {
18546             this.map.set(String(ts.getNodeId(node)), node);
18547         };
18548         NodeSet.prototype.tryAdd = function (node) {
18549             if (this.has(node))
18550                 return false;
18551             this.add(node);
18552             return true;
18553         };
18554         NodeSet.prototype.has = function (node) {
18555             return this.map.has(String(ts.getNodeId(node)));
18556         };
18557         NodeSet.prototype.forEach = function (cb) {
18558             this.map.forEach(cb);
18559         };
18560         NodeSet.prototype.some = function (pred) {
18561             return forEachEntry(this.map, pred) || false;
18562         };
18563         return NodeSet;
18564     }());
18565     ts.NodeSet = NodeSet;
18566     var NodeMap = /** @class */ (function () {
18567         function NodeMap() {
18568             this.map = ts.createMap();
18569         }
18570         NodeMap.prototype.get = function (node) {
18571             var res = this.map.get(String(ts.getNodeId(node)));
18572             return res && res.value;
18573         };
18574         NodeMap.prototype.getOrUpdate = function (node, setValue) {
18575             var res = this.get(node);
18576             if (res)
18577                 return res;
18578             var value = setValue();
18579             this.set(node, value);
18580             return value;
18581         };
18582         NodeMap.prototype.set = function (node, value) {
18583             this.map.set(String(ts.getNodeId(node)), { node: node, value: value });
18584         };
18585         NodeMap.prototype.has = function (node) {
18586             return this.map.has(String(ts.getNodeId(node)));
18587         };
18588         NodeMap.prototype.forEach = function (cb) {
18589             this.map.forEach(function (_a) {
18590                 var node = _a.node, value = _a.value;
18591                 return cb(value, node);
18592             });
18593         };
18594         return NodeMap;
18595     }());
18596     ts.NodeMap = NodeMap;
18597     function rangeOfNode(node) {
18598         return { pos: getTokenPosOfNode(node), end: node.end };
18599     }
18600     ts.rangeOfNode = rangeOfNode;
18601     function rangeOfTypeParameters(typeParameters) {
18602         // Include the `<>`
18603         return { pos: typeParameters.pos - 1, end: typeParameters.end + 1 };
18604     }
18605     ts.rangeOfTypeParameters = rangeOfTypeParameters;
18606     function skipTypeChecking(sourceFile, options, host) {
18607         // If skipLibCheck is enabled, skip reporting errors if file is a declaration file.
18608         // If skipDefaultLibCheck is enabled, skip reporting errors if file contains a
18609         // '/// <reference no-default-lib="true"/>' directive.
18610         return (options.skipLibCheck && sourceFile.isDeclarationFile ||
18611             options.skipDefaultLibCheck && sourceFile.hasNoDefaultLib) ||
18612             host.isSourceOfProjectReferenceRedirect(sourceFile.fileName);
18613     }
18614     ts.skipTypeChecking = skipTypeChecking;
18615     function isJsonEqual(a, b) {
18616         // eslint-disable-next-line no-null/no-null
18617         return a === b || typeof a === "object" && a !== null && typeof b === "object" && b !== null && ts.equalOwnProperties(a, b, isJsonEqual);
18618     }
18619     ts.isJsonEqual = isJsonEqual;
18620     function getOrUpdate(map, key, getDefault) {
18621         var got = map.get(key);
18622         if (got === undefined) {
18623             var value = getDefault();
18624             map.set(key, value);
18625             return value;
18626         }
18627         else {
18628             return got;
18629         }
18630     }
18631     ts.getOrUpdate = getOrUpdate;
18632     /**
18633      * Converts a bigint literal string, e.g. `0x1234n`,
18634      * to its decimal string representation, e.g. `4660`.
18635      */
18636     function parsePseudoBigInt(stringValue) {
18637         var log2Base;
18638         switch (stringValue.charCodeAt(1)) { // "x" in "0x123"
18639             case 98 /* b */:
18640             case 66 /* B */: // 0b or 0B
18641                 log2Base = 1;
18642                 break;
18643             case 111 /* o */:
18644             case 79 /* O */: // 0o or 0O
18645                 log2Base = 3;
18646                 break;
18647             case 120 /* x */:
18648             case 88 /* X */: // 0x or 0X
18649                 log2Base = 4;
18650                 break;
18651             default: // already in decimal; omit trailing "n"
18652                 var nIndex = stringValue.length - 1;
18653                 // Skip leading 0s
18654                 var nonZeroStart = 0;
18655                 while (stringValue.charCodeAt(nonZeroStart) === 48 /* _0 */) {
18656                     nonZeroStart++;
18657                 }
18658                 return stringValue.slice(nonZeroStart, nIndex) || "0";
18659         }
18660         // Omit leading "0b", "0o", or "0x", and trailing "n"
18661         var startIndex = 2, endIndex = stringValue.length - 1;
18662         var bitsNeeded = (endIndex - startIndex) * log2Base;
18663         // Stores the value specified by the string as a LE array of 16-bit integers
18664         // using Uint16 instead of Uint32 so combining steps can use bitwise operators
18665         var segments = new Uint16Array((bitsNeeded >>> 4) + (bitsNeeded & 15 ? 1 : 0));
18666         // Add the digits, one at a time
18667         for (var i = endIndex - 1, bitOffset = 0; i >= startIndex; i--, bitOffset += log2Base) {
18668             var segment = bitOffset >>> 4;
18669             var digitChar = stringValue.charCodeAt(i);
18670             // Find character range: 0-9 < A-F < a-f
18671             var digit = digitChar <= 57 /* _9 */
18672                 ? digitChar - 48 /* _0 */
18673                 : 10 + digitChar -
18674                     (digitChar <= 70 /* F */ ? 65 /* A */ : 97 /* a */);
18675             var shiftedDigit = digit << (bitOffset & 15);
18676             segments[segment] |= shiftedDigit;
18677             var residual = shiftedDigit >>> 16;
18678             if (residual)
18679                 segments[segment + 1] |= residual; // overflows segment
18680         }
18681         // Repeatedly divide segments by 10 and add remainder to base10Value
18682         var base10Value = "";
18683         var firstNonzeroSegment = segments.length - 1;
18684         var segmentsRemaining = true;
18685         while (segmentsRemaining) {
18686             var mod10 = 0;
18687             segmentsRemaining = false;
18688             for (var segment = firstNonzeroSegment; segment >= 0; segment--) {
18689                 var newSegment = mod10 << 16 | segments[segment];
18690                 var segmentValue = (newSegment / 10) | 0;
18691                 segments[segment] = segmentValue;
18692                 mod10 = newSegment - segmentValue * 10;
18693                 if (segmentValue && !segmentsRemaining) {
18694                     firstNonzeroSegment = segment;
18695                     segmentsRemaining = true;
18696                 }
18697             }
18698             base10Value = mod10 + base10Value;
18699         }
18700         return base10Value;
18701     }
18702     ts.parsePseudoBigInt = parsePseudoBigInt;
18703     function pseudoBigIntToString(_a) {
18704         var negative = _a.negative, base10Value = _a.base10Value;
18705         return (negative && base10Value !== "0" ? "-" : "") + base10Value;
18706     }
18707     ts.pseudoBigIntToString = pseudoBigIntToString;
18708     function isValidTypeOnlyAliasUseSite(useSite) {
18709         return !!(useSite.flags & 8388608 /* Ambient */)
18710             || isPartOfTypeQuery(useSite)
18711             || isIdentifierInNonEmittingHeritageClause(useSite)
18712             || isPartOfPossiblyValidTypeOrAbstractComputedPropertyName(useSite)
18713             || !isExpressionNode(useSite);
18714     }
18715     ts.isValidTypeOnlyAliasUseSite = isValidTypeOnlyAliasUseSite;
18716     function typeOnlyDeclarationIsExport(typeOnlyDeclaration) {
18717         return typeOnlyDeclaration.kind === 263 /* ExportSpecifier */;
18718     }
18719     ts.typeOnlyDeclarationIsExport = typeOnlyDeclarationIsExport;
18720     function isPartOfPossiblyValidTypeOrAbstractComputedPropertyName(node) {
18721         while (node.kind === 75 /* Identifier */ || node.kind === 194 /* PropertyAccessExpression */) {
18722             node = node.parent;
18723         }
18724         if (node.kind !== 154 /* ComputedPropertyName */) {
18725             return false;
18726         }
18727         if (hasModifier(node.parent, 128 /* Abstract */)) {
18728             return true;
18729         }
18730         var containerKind = node.parent.parent.kind;
18731         return containerKind === 246 /* InterfaceDeclaration */ || containerKind === 173 /* TypeLiteral */;
18732     }
18733     /** Returns true for an identifier in 1) an `implements` clause, and 2) an `extends` clause of an interface. */
18734     function isIdentifierInNonEmittingHeritageClause(node) {
18735         if (node.kind !== 75 /* Identifier */)
18736             return false;
18737         var heritageClause = findAncestor(node.parent, function (parent) {
18738             switch (parent.kind) {
18739                 case 279 /* HeritageClause */:
18740                     return true;
18741                 case 194 /* PropertyAccessExpression */:
18742                 case 216 /* ExpressionWithTypeArguments */:
18743                     return false;
18744                 default:
18745                     return "quit";
18746             }
18747         });
18748         return (heritageClause === null || heritageClause === void 0 ? void 0 : heritageClause.token) === 113 /* ImplementsKeyword */ || (heritageClause === null || heritageClause === void 0 ? void 0 : heritageClause.parent.kind) === 246 /* InterfaceDeclaration */;
18749     }
18750     function isIdentifierTypeReference(node) {
18751         return ts.isTypeReferenceNode(node) && ts.isIdentifier(node.typeName);
18752     }
18753     ts.isIdentifierTypeReference = isIdentifierTypeReference;
18754     function arrayIsHomogeneous(array, comparer) {
18755         if (comparer === void 0) { comparer = ts.equateValues; }
18756         if (array.length < 2)
18757             return true;
18758         var first = array[0];
18759         for (var i = 1, length_1 = array.length; i < length_1; i++) {
18760             var target = array[i];
18761             if (!comparer(first, target))
18762                 return false;
18763         }
18764         return true;
18765     }
18766     ts.arrayIsHomogeneous = arrayIsHomogeneous;
18767 })(ts || (ts = {}));
18768 var ts;
18769 (function (ts) {
18770     var SignatureFlags;
18771     (function (SignatureFlags) {
18772         SignatureFlags[SignatureFlags["None"] = 0] = "None";
18773         SignatureFlags[SignatureFlags["Yield"] = 1] = "Yield";
18774         SignatureFlags[SignatureFlags["Await"] = 2] = "Await";
18775         SignatureFlags[SignatureFlags["Type"] = 4] = "Type";
18776         SignatureFlags[SignatureFlags["IgnoreMissingOpenBrace"] = 16] = "IgnoreMissingOpenBrace";
18777         SignatureFlags[SignatureFlags["JSDoc"] = 32] = "JSDoc";
18778     })(SignatureFlags || (SignatureFlags = {}));
18779     var NodeConstructor;
18780     var TokenConstructor;
18781     var IdentifierConstructor;
18782     var PrivateIdentifierConstructor;
18783     var SourceFileConstructor;
18784     function createNode(kind, pos, end) {
18785         if (kind === 290 /* SourceFile */) {
18786             return new (SourceFileConstructor || (SourceFileConstructor = ts.objectAllocator.getSourceFileConstructor()))(kind, pos, end);
18787         }
18788         else if (kind === 75 /* Identifier */) {
18789             return new (IdentifierConstructor || (IdentifierConstructor = ts.objectAllocator.getIdentifierConstructor()))(kind, pos, end);
18790         }
18791         else if (kind === 76 /* PrivateIdentifier */) {
18792             return new (PrivateIdentifierConstructor || (PrivateIdentifierConstructor = ts.objectAllocator.getPrivateIdentifierConstructor()))(kind, pos, end);
18793         }
18794         else if (!ts.isNodeKind(kind)) {
18795             return new (TokenConstructor || (TokenConstructor = ts.objectAllocator.getTokenConstructor()))(kind, pos, end);
18796         }
18797         else {
18798             return new (NodeConstructor || (NodeConstructor = ts.objectAllocator.getNodeConstructor()))(kind, pos, end);
18799         }
18800     }
18801     ts.createNode = createNode;
18802     function visitNode(cbNode, node) {
18803         return node && cbNode(node);
18804     }
18805     function visitNodes(cbNode, cbNodes, nodes) {
18806         if (nodes) {
18807             if (cbNodes) {
18808                 return cbNodes(nodes);
18809             }
18810             for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
18811                 var node = nodes_1[_i];
18812                 var result = cbNode(node);
18813                 if (result) {
18814                     return result;
18815                 }
18816             }
18817         }
18818     }
18819     /*@internal*/
18820     function isJSDocLikeText(text, start) {
18821         return text.charCodeAt(start + 1) === 42 /* asterisk */ &&
18822             text.charCodeAt(start + 2) === 42 /* asterisk */ &&
18823             text.charCodeAt(start + 3) !== 47 /* slash */;
18824     }
18825     ts.isJSDocLikeText = isJSDocLikeText;
18826     /**
18827      * Invokes a callback for each child of the given node. The 'cbNode' callback is invoked for all child nodes
18828      * stored in properties. If a 'cbNodes' callback is specified, it is invoked for embedded arrays; otherwise,
18829      * embedded arrays are flattened and the 'cbNode' callback is invoked for each element. If a callback returns
18830      * a truthy value, iteration stops and that value is returned. Otherwise, undefined is returned.
18831      *
18832      * @param node a given node to visit its children
18833      * @param cbNode a callback to be invoked for all child nodes
18834      * @param cbNodes a callback to be invoked for embedded array
18835      *
18836      * @remarks `forEachChild` must visit the children of a node in the order
18837      * that they appear in the source code. The language service depends on this property to locate nodes by position.
18838      */
18839     function forEachChild(node, cbNode, cbNodes) {
18840         if (!node || node.kind <= 152 /* LastToken */) {
18841             return;
18842         }
18843         switch (node.kind) {
18844             case 153 /* QualifiedName */:
18845                 return visitNode(cbNode, node.left) ||
18846                     visitNode(cbNode, node.right);
18847             case 155 /* TypeParameter */:
18848                 return visitNode(cbNode, node.name) ||
18849                     visitNode(cbNode, node.constraint) ||
18850                     visitNode(cbNode, node.default) ||
18851                     visitNode(cbNode, node.expression);
18852             case 282 /* ShorthandPropertyAssignment */:
18853                 return visitNodes(cbNode, cbNodes, node.decorators) ||
18854                     visitNodes(cbNode, cbNodes, node.modifiers) ||
18855                     visitNode(cbNode, node.name) ||
18856                     visitNode(cbNode, node.questionToken) ||
18857                     visitNode(cbNode, node.exclamationToken) ||
18858                     visitNode(cbNode, node.equalsToken) ||
18859                     visitNode(cbNode, node.objectAssignmentInitializer);
18860             case 283 /* SpreadAssignment */:
18861                 return visitNode(cbNode, node.expression);
18862             case 156 /* Parameter */:
18863                 return visitNodes(cbNode, cbNodes, node.decorators) ||
18864                     visitNodes(cbNode, cbNodes, node.modifiers) ||
18865                     visitNode(cbNode, node.dotDotDotToken) ||
18866                     visitNode(cbNode, node.name) ||
18867                     visitNode(cbNode, node.questionToken) ||
18868                     visitNode(cbNode, node.type) ||
18869                     visitNode(cbNode, node.initializer);
18870             case 159 /* PropertyDeclaration */:
18871                 return visitNodes(cbNode, cbNodes, node.decorators) ||
18872                     visitNodes(cbNode, cbNodes, node.modifiers) ||
18873                     visitNode(cbNode, node.name) ||
18874                     visitNode(cbNode, node.questionToken) ||
18875                     visitNode(cbNode, node.exclamationToken) ||
18876                     visitNode(cbNode, node.type) ||
18877                     visitNode(cbNode, node.initializer);
18878             case 158 /* PropertySignature */:
18879                 return visitNodes(cbNode, cbNodes, node.decorators) ||
18880                     visitNodes(cbNode, cbNodes, node.modifiers) ||
18881                     visitNode(cbNode, node.name) ||
18882                     visitNode(cbNode, node.questionToken) ||
18883                     visitNode(cbNode, node.type) ||
18884                     visitNode(cbNode, node.initializer);
18885             case 281 /* PropertyAssignment */:
18886                 return visitNodes(cbNode, cbNodes, node.decorators) ||
18887                     visitNodes(cbNode, cbNodes, node.modifiers) ||
18888                     visitNode(cbNode, node.name) ||
18889                     visitNode(cbNode, node.questionToken) ||
18890                     visitNode(cbNode, node.initializer);
18891             case 242 /* VariableDeclaration */:
18892                 return visitNodes(cbNode, cbNodes, node.decorators) ||
18893                     visitNodes(cbNode, cbNodes, node.modifiers) ||
18894                     visitNode(cbNode, node.name) ||
18895                     visitNode(cbNode, node.exclamationToken) ||
18896                     visitNode(cbNode, node.type) ||
18897                     visitNode(cbNode, node.initializer);
18898             case 191 /* BindingElement */:
18899                 return visitNodes(cbNode, cbNodes, node.decorators) ||
18900                     visitNodes(cbNode, cbNodes, node.modifiers) ||
18901                     visitNode(cbNode, node.dotDotDotToken) ||
18902                     visitNode(cbNode, node.propertyName) ||
18903                     visitNode(cbNode, node.name) ||
18904                     visitNode(cbNode, node.initializer);
18905             case 170 /* FunctionType */:
18906             case 171 /* ConstructorType */:
18907             case 165 /* CallSignature */:
18908             case 166 /* ConstructSignature */:
18909             case 167 /* IndexSignature */:
18910                 return visitNodes(cbNode, cbNodes, node.decorators) ||
18911                     visitNodes(cbNode, cbNodes, node.modifiers) ||
18912                     visitNodes(cbNode, cbNodes, node.typeParameters) ||
18913                     visitNodes(cbNode, cbNodes, node.parameters) ||
18914                     visitNode(cbNode, node.type);
18915             case 161 /* MethodDeclaration */:
18916             case 160 /* MethodSignature */:
18917             case 162 /* Constructor */:
18918             case 163 /* GetAccessor */:
18919             case 164 /* SetAccessor */:
18920             case 201 /* FunctionExpression */:
18921             case 244 /* FunctionDeclaration */:
18922             case 202 /* ArrowFunction */:
18923                 return visitNodes(cbNode, cbNodes, node.decorators) ||
18924                     visitNodes(cbNode, cbNodes, node.modifiers) ||
18925                     visitNode(cbNode, node.asteriskToken) ||
18926                     visitNode(cbNode, node.name) ||
18927                     visitNode(cbNode, node.questionToken) ||
18928                     visitNode(cbNode, node.exclamationToken) ||
18929                     visitNodes(cbNode, cbNodes, node.typeParameters) ||
18930                     visitNodes(cbNode, cbNodes, node.parameters) ||
18931                     visitNode(cbNode, node.type) ||
18932                     visitNode(cbNode, node.equalsGreaterThanToken) ||
18933                     visitNode(cbNode, node.body);
18934             case 169 /* TypeReference */:
18935                 return visitNode(cbNode, node.typeName) ||
18936                     visitNodes(cbNode, cbNodes, node.typeArguments);
18937             case 168 /* TypePredicate */:
18938                 return visitNode(cbNode, node.assertsModifier) ||
18939                     visitNode(cbNode, node.parameterName) ||
18940                     visitNode(cbNode, node.type);
18941             case 172 /* TypeQuery */:
18942                 return visitNode(cbNode, node.exprName);
18943             case 173 /* TypeLiteral */:
18944                 return visitNodes(cbNode, cbNodes, node.members);
18945             case 174 /* ArrayType */:
18946                 return visitNode(cbNode, node.elementType);
18947             case 175 /* TupleType */:
18948                 return visitNodes(cbNode, cbNodes, node.elementTypes);
18949             case 178 /* UnionType */:
18950             case 179 /* IntersectionType */:
18951                 return visitNodes(cbNode, cbNodes, node.types);
18952             case 180 /* ConditionalType */:
18953                 return visitNode(cbNode, node.checkType) ||
18954                     visitNode(cbNode, node.extendsType) ||
18955                     visitNode(cbNode, node.trueType) ||
18956                     visitNode(cbNode, node.falseType);
18957             case 181 /* InferType */:
18958                 return visitNode(cbNode, node.typeParameter);
18959             case 188 /* ImportType */:
18960                 return visitNode(cbNode, node.argument) ||
18961                     visitNode(cbNode, node.qualifier) ||
18962                     visitNodes(cbNode, cbNodes, node.typeArguments);
18963             case 182 /* ParenthesizedType */:
18964             case 184 /* TypeOperator */:
18965                 return visitNode(cbNode, node.type);
18966             case 185 /* IndexedAccessType */:
18967                 return visitNode(cbNode, node.objectType) ||
18968                     visitNode(cbNode, node.indexType);
18969             case 186 /* MappedType */:
18970                 return visitNode(cbNode, node.readonlyToken) ||
18971                     visitNode(cbNode, node.typeParameter) ||
18972                     visitNode(cbNode, node.questionToken) ||
18973                     visitNode(cbNode, node.type);
18974             case 187 /* LiteralType */:
18975                 return visitNode(cbNode, node.literal);
18976             case 189 /* ObjectBindingPattern */:
18977             case 190 /* ArrayBindingPattern */:
18978                 return visitNodes(cbNode, cbNodes, node.elements);
18979             case 192 /* ArrayLiteralExpression */:
18980                 return visitNodes(cbNode, cbNodes, node.elements);
18981             case 193 /* ObjectLiteralExpression */:
18982                 return visitNodes(cbNode, cbNodes, node.properties);
18983             case 194 /* PropertyAccessExpression */:
18984                 return visitNode(cbNode, node.expression) ||
18985                     visitNode(cbNode, node.questionDotToken) ||
18986                     visitNode(cbNode, node.name);
18987             case 195 /* ElementAccessExpression */:
18988                 return visitNode(cbNode, node.expression) ||
18989                     visitNode(cbNode, node.questionDotToken) ||
18990                     visitNode(cbNode, node.argumentExpression);
18991             case 196 /* CallExpression */:
18992             case 197 /* NewExpression */:
18993                 return visitNode(cbNode, node.expression) ||
18994                     visitNode(cbNode, node.questionDotToken) ||
18995                     visitNodes(cbNode, cbNodes, node.typeArguments) ||
18996                     visitNodes(cbNode, cbNodes, node.arguments);
18997             case 198 /* TaggedTemplateExpression */:
18998                 return visitNode(cbNode, node.tag) ||
18999                     visitNode(cbNode, node.questionDotToken) ||
19000                     visitNodes(cbNode, cbNodes, node.typeArguments) ||
19001                     visitNode(cbNode, node.template);
19002             case 199 /* TypeAssertionExpression */:
19003                 return visitNode(cbNode, node.type) ||
19004                     visitNode(cbNode, node.expression);
19005             case 200 /* ParenthesizedExpression */:
19006                 return visitNode(cbNode, node.expression);
19007             case 203 /* DeleteExpression */:
19008                 return visitNode(cbNode, node.expression);
19009             case 204 /* TypeOfExpression */:
19010                 return visitNode(cbNode, node.expression);
19011             case 205 /* VoidExpression */:
19012                 return visitNode(cbNode, node.expression);
19013             case 207 /* PrefixUnaryExpression */:
19014                 return visitNode(cbNode, node.operand);
19015             case 212 /* YieldExpression */:
19016                 return visitNode(cbNode, node.asteriskToken) ||
19017                     visitNode(cbNode, node.expression);
19018             case 206 /* AwaitExpression */:
19019                 return visitNode(cbNode, node.expression);
19020             case 208 /* PostfixUnaryExpression */:
19021                 return visitNode(cbNode, node.operand);
19022             case 209 /* BinaryExpression */:
19023                 return visitNode(cbNode, node.left) ||
19024                     visitNode(cbNode, node.operatorToken) ||
19025                     visitNode(cbNode, node.right);
19026             case 217 /* AsExpression */:
19027                 return visitNode(cbNode, node.expression) ||
19028                     visitNode(cbNode, node.type);
19029             case 218 /* NonNullExpression */:
19030                 return visitNode(cbNode, node.expression);
19031             case 219 /* MetaProperty */:
19032                 return visitNode(cbNode, node.name);
19033             case 210 /* ConditionalExpression */:
19034                 return visitNode(cbNode, node.condition) ||
19035                     visitNode(cbNode, node.questionToken) ||
19036                     visitNode(cbNode, node.whenTrue) ||
19037                     visitNode(cbNode, node.colonToken) ||
19038                     visitNode(cbNode, node.whenFalse);
19039             case 213 /* SpreadElement */:
19040                 return visitNode(cbNode, node.expression);
19041             case 223 /* Block */:
19042             case 250 /* ModuleBlock */:
19043                 return visitNodes(cbNode, cbNodes, node.statements);
19044             case 290 /* SourceFile */:
19045                 return visitNodes(cbNode, cbNodes, node.statements) ||
19046                     visitNode(cbNode, node.endOfFileToken);
19047             case 225 /* VariableStatement */:
19048                 return visitNodes(cbNode, cbNodes, node.decorators) ||
19049                     visitNodes(cbNode, cbNodes, node.modifiers) ||
19050                     visitNode(cbNode, node.declarationList);
19051             case 243 /* VariableDeclarationList */:
19052                 return visitNodes(cbNode, cbNodes, node.declarations);
19053             case 226 /* ExpressionStatement */:
19054                 return visitNode(cbNode, node.expression);
19055             case 227 /* IfStatement */:
19056                 return visitNode(cbNode, node.expression) ||
19057                     visitNode(cbNode, node.thenStatement) ||
19058                     visitNode(cbNode, node.elseStatement);
19059             case 228 /* DoStatement */:
19060                 return visitNode(cbNode, node.statement) ||
19061                     visitNode(cbNode, node.expression);
19062             case 229 /* WhileStatement */:
19063                 return visitNode(cbNode, node.expression) ||
19064                     visitNode(cbNode, node.statement);
19065             case 230 /* ForStatement */:
19066                 return visitNode(cbNode, node.initializer) ||
19067                     visitNode(cbNode, node.condition) ||
19068                     visitNode(cbNode, node.incrementor) ||
19069                     visitNode(cbNode, node.statement);
19070             case 231 /* ForInStatement */:
19071                 return visitNode(cbNode, node.initializer) ||
19072                     visitNode(cbNode, node.expression) ||
19073                     visitNode(cbNode, node.statement);
19074             case 232 /* ForOfStatement */:
19075                 return visitNode(cbNode, node.awaitModifier) ||
19076                     visitNode(cbNode, node.initializer) ||
19077                     visitNode(cbNode, node.expression) ||
19078                     visitNode(cbNode, node.statement);
19079             case 233 /* ContinueStatement */:
19080             case 234 /* BreakStatement */:
19081                 return visitNode(cbNode, node.label);
19082             case 235 /* ReturnStatement */:
19083                 return visitNode(cbNode, node.expression);
19084             case 236 /* WithStatement */:
19085                 return visitNode(cbNode, node.expression) ||
19086                     visitNode(cbNode, node.statement);
19087             case 237 /* SwitchStatement */:
19088                 return visitNode(cbNode, node.expression) ||
19089                     visitNode(cbNode, node.caseBlock);
19090             case 251 /* CaseBlock */:
19091                 return visitNodes(cbNode, cbNodes, node.clauses);
19092             case 277 /* CaseClause */:
19093                 return visitNode(cbNode, node.expression) ||
19094                     visitNodes(cbNode, cbNodes, node.statements);
19095             case 278 /* DefaultClause */:
19096                 return visitNodes(cbNode, cbNodes, node.statements);
19097             case 238 /* LabeledStatement */:
19098                 return visitNode(cbNode, node.label) ||
19099                     visitNode(cbNode, node.statement);
19100             case 239 /* ThrowStatement */:
19101                 return visitNode(cbNode, node.expression);
19102             case 240 /* TryStatement */:
19103                 return visitNode(cbNode, node.tryBlock) ||
19104                     visitNode(cbNode, node.catchClause) ||
19105                     visitNode(cbNode, node.finallyBlock);
19106             case 280 /* CatchClause */:
19107                 return visitNode(cbNode, node.variableDeclaration) ||
19108                     visitNode(cbNode, node.block);
19109             case 157 /* Decorator */:
19110                 return visitNode(cbNode, node.expression);
19111             case 245 /* ClassDeclaration */:
19112             case 214 /* ClassExpression */:
19113                 return visitNodes(cbNode, cbNodes, node.decorators) ||
19114                     visitNodes(cbNode, cbNodes, node.modifiers) ||
19115                     visitNode(cbNode, node.name) ||
19116                     visitNodes(cbNode, cbNodes, node.typeParameters) ||
19117                     visitNodes(cbNode, cbNodes, node.heritageClauses) ||
19118                     visitNodes(cbNode, cbNodes, node.members);
19119             case 246 /* InterfaceDeclaration */:
19120                 return visitNodes(cbNode, cbNodes, node.decorators) ||
19121                     visitNodes(cbNode, cbNodes, node.modifiers) ||
19122                     visitNode(cbNode, node.name) ||
19123                     visitNodes(cbNode, cbNodes, node.typeParameters) ||
19124                     visitNodes(cbNode, cbNodes, node.heritageClauses) ||
19125                     visitNodes(cbNode, cbNodes, node.members);
19126             case 247 /* TypeAliasDeclaration */:
19127                 return visitNodes(cbNode, cbNodes, node.decorators) ||
19128                     visitNodes(cbNode, cbNodes, node.modifiers) ||
19129                     visitNode(cbNode, node.name) ||
19130                     visitNodes(cbNode, cbNodes, node.typeParameters) ||
19131                     visitNode(cbNode, node.type);
19132             case 248 /* EnumDeclaration */:
19133                 return visitNodes(cbNode, cbNodes, node.decorators) ||
19134                     visitNodes(cbNode, cbNodes, node.modifiers) ||
19135                     visitNode(cbNode, node.name) ||
19136                     visitNodes(cbNode, cbNodes, node.members);
19137             case 284 /* EnumMember */:
19138                 return visitNode(cbNode, node.name) ||
19139                     visitNode(cbNode, node.initializer);
19140             case 249 /* ModuleDeclaration */:
19141                 return visitNodes(cbNode, cbNodes, node.decorators) ||
19142                     visitNodes(cbNode, cbNodes, node.modifiers) ||
19143                     visitNode(cbNode, node.name) ||
19144                     visitNode(cbNode, node.body);
19145             case 253 /* ImportEqualsDeclaration */:
19146                 return visitNodes(cbNode, cbNodes, node.decorators) ||
19147                     visitNodes(cbNode, cbNodes, node.modifiers) ||
19148                     visitNode(cbNode, node.name) ||
19149                     visitNode(cbNode, node.moduleReference);
19150             case 254 /* ImportDeclaration */:
19151                 return visitNodes(cbNode, cbNodes, node.decorators) ||
19152                     visitNodes(cbNode, cbNodes, node.modifiers) ||
19153                     visitNode(cbNode, node.importClause) ||
19154                     visitNode(cbNode, node.moduleSpecifier);
19155             case 255 /* ImportClause */:
19156                 return visitNode(cbNode, node.name) ||
19157                     visitNode(cbNode, node.namedBindings);
19158             case 252 /* NamespaceExportDeclaration */:
19159                 return visitNode(cbNode, node.name);
19160             case 256 /* NamespaceImport */:
19161                 return visitNode(cbNode, node.name);
19162             case 262 /* NamespaceExport */:
19163                 return visitNode(cbNode, node.name);
19164             case 257 /* NamedImports */:
19165             case 261 /* NamedExports */:
19166                 return visitNodes(cbNode, cbNodes, node.elements);
19167             case 260 /* ExportDeclaration */:
19168                 return visitNodes(cbNode, cbNodes, node.decorators) ||
19169                     visitNodes(cbNode, cbNodes, node.modifiers) ||
19170                     visitNode(cbNode, node.exportClause) ||
19171                     visitNode(cbNode, node.moduleSpecifier);
19172             case 258 /* ImportSpecifier */:
19173             case 263 /* ExportSpecifier */:
19174                 return visitNode(cbNode, node.propertyName) ||
19175                     visitNode(cbNode, node.name);
19176             case 259 /* ExportAssignment */:
19177                 return visitNodes(cbNode, cbNodes, node.decorators) ||
19178                     visitNodes(cbNode, cbNodes, node.modifiers) ||
19179                     visitNode(cbNode, node.expression);
19180             case 211 /* TemplateExpression */:
19181                 return visitNode(cbNode, node.head) || visitNodes(cbNode, cbNodes, node.templateSpans);
19182             case 221 /* TemplateSpan */:
19183                 return visitNode(cbNode, node.expression) || visitNode(cbNode, node.literal);
19184             case 154 /* ComputedPropertyName */:
19185                 return visitNode(cbNode, node.expression);
19186             case 279 /* HeritageClause */:
19187                 return visitNodes(cbNode, cbNodes, node.types);
19188             case 216 /* ExpressionWithTypeArguments */:
19189                 return visitNode(cbNode, node.expression) ||
19190                     visitNodes(cbNode, cbNodes, node.typeArguments);
19191             case 265 /* ExternalModuleReference */:
19192                 return visitNode(cbNode, node.expression);
19193             case 264 /* MissingDeclaration */:
19194                 return visitNodes(cbNode, cbNodes, node.decorators);
19195             case 327 /* CommaListExpression */:
19196                 return visitNodes(cbNode, cbNodes, node.elements);
19197             case 266 /* JsxElement */:
19198                 return visitNode(cbNode, node.openingElement) ||
19199                     visitNodes(cbNode, cbNodes, node.children) ||
19200                     visitNode(cbNode, node.closingElement);
19201             case 270 /* JsxFragment */:
19202                 return visitNode(cbNode, node.openingFragment) ||
19203                     visitNodes(cbNode, cbNodes, node.children) ||
19204                     visitNode(cbNode, node.closingFragment);
19205             case 267 /* JsxSelfClosingElement */:
19206             case 268 /* JsxOpeningElement */:
19207                 return visitNode(cbNode, node.tagName) ||
19208                     visitNodes(cbNode, cbNodes, node.typeArguments) ||
19209                     visitNode(cbNode, node.attributes);
19210             case 274 /* JsxAttributes */:
19211                 return visitNodes(cbNode, cbNodes, node.properties);
19212             case 273 /* JsxAttribute */:
19213                 return visitNode(cbNode, node.name) ||
19214                     visitNode(cbNode, node.initializer);
19215             case 275 /* JsxSpreadAttribute */:
19216                 return visitNode(cbNode, node.expression);
19217             case 276 /* JsxExpression */:
19218                 return visitNode(cbNode, node.dotDotDotToken) ||
19219                     visitNode(cbNode, node.expression);
19220             case 269 /* JsxClosingElement */:
19221                 return visitNode(cbNode, node.tagName);
19222             case 176 /* OptionalType */:
19223             case 177 /* RestType */:
19224             case 294 /* JSDocTypeExpression */:
19225             case 298 /* JSDocNonNullableType */:
19226             case 297 /* JSDocNullableType */:
19227             case 299 /* JSDocOptionalType */:
19228             case 301 /* JSDocVariadicType */:
19229                 return visitNode(cbNode, node.type);
19230             case 300 /* JSDocFunctionType */:
19231                 return visitNodes(cbNode, cbNodes, node.parameters) ||
19232                     visitNode(cbNode, node.type);
19233             case 303 /* JSDocComment */:
19234                 return visitNodes(cbNode, cbNodes, node.tags);
19235             case 317 /* JSDocParameterTag */:
19236             case 323 /* JSDocPropertyTag */:
19237                 return visitNode(cbNode, node.tagName) ||
19238                     (node.isNameFirst
19239                         ? visitNode(cbNode, node.name) ||
19240                             visitNode(cbNode, node.typeExpression)
19241                         : visitNode(cbNode, node.typeExpression) ||
19242                             visitNode(cbNode, node.name));
19243             case 309 /* JSDocAuthorTag */:
19244                 return visitNode(cbNode, node.tagName);
19245             case 308 /* JSDocImplementsTag */:
19246                 return visitNode(cbNode, node.tagName) ||
19247                     visitNode(cbNode, node.class);
19248             case 307 /* JSDocAugmentsTag */:
19249                 return visitNode(cbNode, node.tagName) ||
19250                     visitNode(cbNode, node.class);
19251             case 321 /* JSDocTemplateTag */:
19252                 return visitNode(cbNode, node.tagName) ||
19253                     visitNode(cbNode, node.constraint) ||
19254                     visitNodes(cbNode, cbNodes, node.typeParameters);
19255             case 322 /* JSDocTypedefTag */:
19256                 return visitNode(cbNode, node.tagName) ||
19257                     (node.typeExpression &&
19258                         node.typeExpression.kind === 294 /* JSDocTypeExpression */
19259                         ? visitNode(cbNode, node.typeExpression) ||
19260                             visitNode(cbNode, node.fullName)
19261                         : visitNode(cbNode, node.fullName) ||
19262                             visitNode(cbNode, node.typeExpression));
19263             case 315 /* JSDocCallbackTag */:
19264                 return visitNode(cbNode, node.tagName) ||
19265                     visitNode(cbNode, node.fullName) ||
19266                     visitNode(cbNode, node.typeExpression);
19267             case 318 /* JSDocReturnTag */:
19268             case 320 /* JSDocTypeTag */:
19269             case 319 /* JSDocThisTag */:
19270             case 316 /* JSDocEnumTag */:
19271                 return visitNode(cbNode, node.tagName) ||
19272                     visitNode(cbNode, node.typeExpression);
19273             case 305 /* JSDocSignature */:
19274                 return ts.forEach(node.typeParameters, cbNode) ||
19275                     ts.forEach(node.parameters, cbNode) ||
19276                     visitNode(cbNode, node.type);
19277             case 304 /* JSDocTypeLiteral */:
19278                 return ts.forEach(node.jsDocPropertyTags, cbNode);
19279             case 306 /* JSDocTag */:
19280             case 310 /* JSDocClassTag */:
19281             case 311 /* JSDocPublicTag */:
19282             case 312 /* JSDocPrivateTag */:
19283             case 313 /* JSDocProtectedTag */:
19284             case 314 /* JSDocReadonlyTag */:
19285                 return visitNode(cbNode, node.tagName);
19286             case 326 /* PartiallyEmittedExpression */:
19287                 return visitNode(cbNode, node.expression);
19288         }
19289     }
19290     ts.forEachChild = forEachChild;
19291     /** @internal */
19292     /**
19293      * Invokes a callback for each child of the given node. The 'cbNode' callback is invoked for all child nodes
19294      * stored in properties. If a 'cbNodes' callback is specified, it is invoked for embedded arrays; additionally,
19295      * unlike `forEachChild`, embedded arrays are flattened and the 'cbNode' callback is invoked for each element.
19296      *  If a callback returns a truthy value, iteration stops and that value is returned. Otherwise, undefined is returned.
19297      *
19298      * @param node a given node to visit its children
19299      * @param cbNode a callback to be invoked for all child nodes
19300      * @param cbNodes a callback to be invoked for embedded array
19301      *
19302      * @remarks Unlike `forEachChild`, `forEachChildRecursively` handles recursively invoking the traversal on each child node found,
19303      * and while doing so, handles traversing the structure without relying on the callstack to encode the tree structure.
19304      */
19305     function forEachChildRecursively(rootNode, cbNode, cbNodes) {
19306         var stack = [rootNode];
19307         while (stack.length) {
19308             var parent = stack.pop();
19309             var res = visitAllPossibleChildren(parent, gatherPossibleChildren(parent));
19310             if (res) {
19311                 return res;
19312             }
19313         }
19314         return;
19315         function gatherPossibleChildren(node) {
19316             var children = [];
19317             forEachChild(node, addWorkItem, addWorkItem); // By using a stack above and `unshift` here, we emulate a depth-first preorder traversal
19318             return children;
19319             function addWorkItem(n) {
19320                 children.unshift(n);
19321             }
19322         }
19323         function visitAllPossibleChildren(parent, children) {
19324             for (var _i = 0, children_1 = children; _i < children_1.length; _i++) {
19325                 var child = children_1[_i];
19326                 if (ts.isArray(child)) {
19327                     if (cbNodes) {
19328                         var res = cbNodes(child, parent);
19329                         if (res) {
19330                             if (res === "skip")
19331                                 continue;
19332                             return res;
19333                         }
19334                     }
19335                     for (var i = child.length - 1; i >= 0; i--) {
19336                         var realChild = child[i];
19337                         var res = cbNode(realChild, parent);
19338                         if (res) {
19339                             if (res === "skip")
19340                                 continue;
19341                             return res;
19342                         }
19343                         stack.push(realChild);
19344                     }
19345                 }
19346                 else {
19347                     stack.push(child);
19348                     var res = cbNode(child, parent);
19349                     if (res) {
19350                         if (res === "skip")
19351                             continue;
19352                         return res;
19353                     }
19354                 }
19355             }
19356         }
19357     }
19358     ts.forEachChildRecursively = forEachChildRecursively;
19359     function createSourceFile(fileName, sourceText, languageVersion, setParentNodes, scriptKind) {
19360         if (setParentNodes === void 0) { setParentNodes = false; }
19361         ts.performance.mark("beforeParse");
19362         var result;
19363         ts.perfLogger.logStartParseSourceFile(fileName);
19364         if (languageVersion === 100 /* JSON */) {
19365             result = Parser.parseSourceFile(fileName, sourceText, languageVersion, /*syntaxCursor*/ undefined, setParentNodes, 6 /* JSON */);
19366         }
19367         else {
19368             result = Parser.parseSourceFile(fileName, sourceText, languageVersion, /*syntaxCursor*/ undefined, setParentNodes, scriptKind);
19369         }
19370         ts.perfLogger.logStopParseSourceFile();
19371         ts.performance.mark("afterParse");
19372         ts.performance.measure("Parse", "beforeParse", "afterParse");
19373         return result;
19374     }
19375     ts.createSourceFile = createSourceFile;
19376     function parseIsolatedEntityName(text, languageVersion) {
19377         return Parser.parseIsolatedEntityName(text, languageVersion);
19378     }
19379     ts.parseIsolatedEntityName = parseIsolatedEntityName;
19380     /**
19381      * Parse json text into SyntaxTree and return node and parse errors if any
19382      * @param fileName
19383      * @param sourceText
19384      */
19385     function parseJsonText(fileName, sourceText) {
19386         return Parser.parseJsonText(fileName, sourceText);
19387     }
19388     ts.parseJsonText = parseJsonText;
19389     // See also `isExternalOrCommonJsModule` in utilities.ts
19390     function isExternalModule(file) {
19391         return file.externalModuleIndicator !== undefined;
19392     }
19393     ts.isExternalModule = isExternalModule;
19394     // Produces a new SourceFile for the 'newText' provided. The 'textChangeRange' parameter
19395     // indicates what changed between the 'text' that this SourceFile has and the 'newText'.
19396     // The SourceFile will be created with the compiler attempting to reuse as many nodes from
19397     // this file as possible.
19398     //
19399     // Note: this function mutates nodes from this SourceFile. That means any existing nodes
19400     // from this SourceFile that are being held onto may change as a result (including
19401     // becoming detached from any SourceFile).  It is recommended that this SourceFile not
19402     // be used once 'update' is called on it.
19403     function updateSourceFile(sourceFile, newText, textChangeRange, aggressiveChecks) {
19404         if (aggressiveChecks === void 0) { aggressiveChecks = false; }
19405         var newSourceFile = IncrementalParser.updateSourceFile(sourceFile, newText, textChangeRange, aggressiveChecks);
19406         // 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.
19407         // We will manually port the flag to the new source file.
19408         newSourceFile.flags |= (sourceFile.flags & 3145728 /* PermanentlySetIncrementalFlags */);
19409         return newSourceFile;
19410     }
19411     ts.updateSourceFile = updateSourceFile;
19412     /* @internal */
19413     function parseIsolatedJSDocComment(content, start, length) {
19414         var result = Parser.JSDocParser.parseIsolatedJSDocComment(content, start, length);
19415         if (result && result.jsDoc) {
19416             // because the jsDocComment was parsed out of the source file, it might
19417             // not be covered by the fixupParentReferences.
19418             Parser.fixupParentReferences(result.jsDoc);
19419         }
19420         return result;
19421     }
19422     ts.parseIsolatedJSDocComment = parseIsolatedJSDocComment;
19423     /* @internal */
19424     // Exposed only for testing.
19425     function parseJSDocTypeExpressionForTests(content, start, length) {
19426         return Parser.JSDocParser.parseJSDocTypeExpressionForTests(content, start, length);
19427     }
19428     ts.parseJSDocTypeExpressionForTests = parseJSDocTypeExpressionForTests;
19429     // Implement the parser as a singleton module.  We do this for perf reasons because creating
19430     // parser instances can actually be expensive enough to impact us on projects with many source
19431     // files.
19432     var Parser;
19433     (function (Parser) {
19434         // Share a single scanner across all calls to parse a source file.  This helps speed things
19435         // up by avoiding the cost of creating/compiling scanners over and over again.
19436         var scanner = ts.createScanner(99 /* Latest */, /*skipTrivia*/ true);
19437         var disallowInAndDecoratorContext = 4096 /* DisallowInContext */ | 16384 /* DecoratorContext */;
19438         // capture constructors in 'initializeState' to avoid null checks
19439         var NodeConstructor;
19440         var TokenConstructor;
19441         var IdentifierConstructor;
19442         var PrivateIdentifierConstructor;
19443         var SourceFileConstructor;
19444         var sourceFile;
19445         var parseDiagnostics;
19446         var syntaxCursor;
19447         var currentToken;
19448         var sourceText;
19449         var nodeCount;
19450         var identifiers;
19451         var privateIdentifiers;
19452         var identifierCount;
19453         var parsingContext;
19454         var notParenthesizedArrow;
19455         // Flags that dictate what parsing context we're in.  For example:
19456         // Whether or not we are in strict parsing mode.  All that changes in strict parsing mode is
19457         // that some tokens that would be considered identifiers may be considered keywords.
19458         //
19459         // When adding more parser context flags, consider which is the more common case that the
19460         // flag will be in.  This should be the 'false' state for that flag.  The reason for this is
19461         // that we don't store data in our nodes unless the value is in the *non-default* state.  So,
19462         // for example, more often than code 'allows-in' (or doesn't 'disallow-in').  We opt for
19463         // 'disallow-in' set to 'false'.  Otherwise, if we had 'allowsIn' set to 'true', then almost
19464         // all nodes would need extra state on them to store this info.
19465         //
19466         // Note: 'allowIn' and 'allowYield' track 1:1 with the [in] and [yield] concepts in the ES6
19467         // grammar specification.
19468         //
19469         // An important thing about these context concepts.  By default they are effectively inherited
19470         // while parsing through every grammar production.  i.e. if you don't change them, then when
19471         // you parse a sub-production, it will have the same context values as the parent production.
19472         // This is great most of the time.  After all, consider all the 'expression' grammar productions
19473         // and how nearly all of them pass along the 'in' and 'yield' context values:
19474         //
19475         // EqualityExpression[In, Yield] :
19476         //      RelationalExpression[?In, ?Yield]
19477         //      EqualityExpression[?In, ?Yield] == RelationalExpression[?In, ?Yield]
19478         //      EqualityExpression[?In, ?Yield] != RelationalExpression[?In, ?Yield]
19479         //      EqualityExpression[?In, ?Yield] === RelationalExpression[?In, ?Yield]
19480         //      EqualityExpression[?In, ?Yield] !== RelationalExpression[?In, ?Yield]
19481         //
19482         // Where you have to be careful is then understanding what the points are in the grammar
19483         // where the values are *not* passed along.  For example:
19484         //
19485         // SingleNameBinding[Yield,GeneratorParameter]
19486         //      [+GeneratorParameter]BindingIdentifier[Yield] Initializer[In]opt
19487         //      [~GeneratorParameter]BindingIdentifier[?Yield]Initializer[In, ?Yield]opt
19488         //
19489         // Here this is saying that if the GeneratorParameter context flag is set, that we should
19490         // explicitly set the 'yield' context flag to false before calling into the BindingIdentifier
19491         // and we should explicitly unset the 'yield' context flag before calling into the Initializer.
19492         // production.  Conversely, if the GeneratorParameter context flag is not set, then we
19493         // should leave the 'yield' context flag alone.
19494         //
19495         // Getting this all correct is tricky and requires careful reading of the grammar to
19496         // understand when these values should be changed versus when they should be inherited.
19497         //
19498         // Note: it should not be necessary to save/restore these flags during speculative/lookahead
19499         // parsing.  These context flags are naturally stored and restored through normal recursive
19500         // descent parsing and unwinding.
19501         var contextFlags;
19502         // Whether or not we've had a parse error since creating the last AST node.  If we have
19503         // encountered an error, it will be stored on the next AST node we create.  Parse errors
19504         // can be broken down into three categories:
19505         //
19506         // 1) An error that occurred during scanning.  For example, an unterminated literal, or a
19507         //    character that was completely not understood.
19508         //
19509         // 2) A token was expected, but was not present.  This type of error is commonly produced
19510         //    by the 'parseExpected' function.
19511         //
19512         // 3) A token was present that no parsing function was able to consume.  This type of error
19513         //    only occurs in the 'abortParsingListOrMoveToNextToken' function when the parser
19514         //    decides to skip the token.
19515         //
19516         // In all of these cases, we want to mark the next node as having had an error before it.
19517         // With this mark, we can know in incremental settings if this node can be reused, or if
19518         // we have to reparse it.  If we don't keep this information around, we may just reuse the
19519         // node.  in that event we would then not produce the same errors as we did before, causing
19520         // significant confusion problems.
19521         //
19522         // Note: it is necessary that this value be saved/restored during speculative/lookahead
19523         // parsing.  During lookahead parsing, we will often create a node.  That node will have
19524         // this value attached, and then this value will be set back to 'false'.  If we decide to
19525         // rewind, we must get back to the same value we had prior to the lookahead.
19526         //
19527         // Note: any errors at the end of the file that do not precede a regular node, should get
19528         // attached to the EOF token.
19529         var parseErrorBeforeNextFinishedNode = false;
19530         function parseSourceFile(fileName, sourceText, languageVersion, syntaxCursor, setParentNodes, scriptKind) {
19531             if (setParentNodes === void 0) { setParentNodes = false; }
19532             scriptKind = ts.ensureScriptKind(fileName, scriptKind);
19533             if (scriptKind === 6 /* JSON */) {
19534                 var result_2 = parseJsonText(fileName, sourceText, languageVersion, syntaxCursor, setParentNodes);
19535                 ts.convertToObjectWorker(result_2, result_2.parseDiagnostics, /*returnValue*/ false, /*knownRootOptions*/ undefined, /*jsonConversionNotifier*/ undefined);
19536                 result_2.referencedFiles = ts.emptyArray;
19537                 result_2.typeReferenceDirectives = ts.emptyArray;
19538                 result_2.libReferenceDirectives = ts.emptyArray;
19539                 result_2.amdDependencies = ts.emptyArray;
19540                 result_2.hasNoDefaultLib = false;
19541                 result_2.pragmas = ts.emptyMap;
19542                 return result_2;
19543             }
19544             initializeState(sourceText, languageVersion, syntaxCursor, scriptKind);
19545             var result = parseSourceFileWorker(fileName, languageVersion, setParentNodes, scriptKind);
19546             clearState();
19547             return result;
19548         }
19549         Parser.parseSourceFile = parseSourceFile;
19550         function parseIsolatedEntityName(content, languageVersion) {
19551             // Choice of `isDeclarationFile` should be arbitrary
19552             initializeState(content, languageVersion, /*syntaxCursor*/ undefined, 1 /* JS */);
19553             // Prime the scanner.
19554             nextToken();
19555             var entityName = parseEntityName(/*allowReservedWords*/ true);
19556             var isInvalid = token() === 1 /* EndOfFileToken */ && !parseDiagnostics.length;
19557             clearState();
19558             return isInvalid ? entityName : undefined;
19559         }
19560         Parser.parseIsolatedEntityName = parseIsolatedEntityName;
19561         function parseJsonText(fileName, sourceText, languageVersion, syntaxCursor, setParentNodes) {
19562             if (languageVersion === void 0) { languageVersion = 2 /* ES2015 */; }
19563             initializeState(sourceText, languageVersion, syntaxCursor, 6 /* JSON */);
19564             // Set source file so that errors will be reported with this file name
19565             sourceFile = createSourceFile(fileName, 2 /* ES2015 */, 6 /* JSON */, /*isDeclaration*/ false);
19566             sourceFile.flags = contextFlags;
19567             // Prime the scanner.
19568             nextToken();
19569             var pos = getNodePos();
19570             if (token() === 1 /* EndOfFileToken */) {
19571                 sourceFile.statements = createNodeArray([], pos, pos);
19572                 sourceFile.endOfFileToken = parseTokenNode();
19573             }
19574             else {
19575                 var statement = createNode(226 /* ExpressionStatement */);
19576                 switch (token()) {
19577                     case 22 /* OpenBracketToken */:
19578                         statement.expression = parseArrayLiteralExpression();
19579                         break;
19580                     case 106 /* TrueKeyword */:
19581                     case 91 /* FalseKeyword */:
19582                     case 100 /* NullKeyword */:
19583                         statement.expression = parseTokenNode();
19584                         break;
19585                     case 40 /* MinusToken */:
19586                         if (lookAhead(function () { return nextToken() === 8 /* NumericLiteral */ && nextToken() !== 58 /* ColonToken */; })) {
19587                             statement.expression = parsePrefixUnaryExpression();
19588                         }
19589                         else {
19590                             statement.expression = parseObjectLiteralExpression();
19591                         }
19592                         break;
19593                     case 8 /* NumericLiteral */:
19594                     case 10 /* StringLiteral */:
19595                         if (lookAhead(function () { return nextToken() !== 58 /* ColonToken */; })) {
19596                             statement.expression = parseLiteralNode();
19597                             break;
19598                         }
19599                     // falls through
19600                     default:
19601                         statement.expression = parseObjectLiteralExpression();
19602                         break;
19603                 }
19604                 finishNode(statement);
19605                 sourceFile.statements = createNodeArray([statement], pos);
19606                 sourceFile.endOfFileToken = parseExpectedToken(1 /* EndOfFileToken */, ts.Diagnostics.Unexpected_token);
19607             }
19608             if (setParentNodes) {
19609                 fixupParentReferences(sourceFile);
19610             }
19611             sourceFile.nodeCount = nodeCount;
19612             sourceFile.identifierCount = identifierCount;
19613             sourceFile.identifiers = identifiers;
19614             sourceFile.parseDiagnostics = parseDiagnostics;
19615             var result = sourceFile;
19616             clearState();
19617             return result;
19618         }
19619         Parser.parseJsonText = parseJsonText;
19620         function getLanguageVariant(scriptKind) {
19621             // .tsx and .jsx files are treated as jsx language variant.
19622             return scriptKind === 4 /* TSX */ || scriptKind === 2 /* JSX */ || scriptKind === 1 /* JS */ || scriptKind === 6 /* JSON */ ? 1 /* JSX */ : 0 /* Standard */;
19623         }
19624         function initializeState(_sourceText, languageVersion, _syntaxCursor, scriptKind) {
19625             NodeConstructor = ts.objectAllocator.getNodeConstructor();
19626             TokenConstructor = ts.objectAllocator.getTokenConstructor();
19627             IdentifierConstructor = ts.objectAllocator.getIdentifierConstructor();
19628             PrivateIdentifierConstructor = ts.objectAllocator.getPrivateIdentifierConstructor();
19629             SourceFileConstructor = ts.objectAllocator.getSourceFileConstructor();
19630             sourceText = _sourceText;
19631             syntaxCursor = _syntaxCursor;
19632             parseDiagnostics = [];
19633             parsingContext = 0;
19634             identifiers = ts.createMap();
19635             privateIdentifiers = ts.createMap();
19636             identifierCount = 0;
19637             nodeCount = 0;
19638             switch (scriptKind) {
19639                 case 1 /* JS */:
19640                 case 2 /* JSX */:
19641                     contextFlags = 131072 /* JavaScriptFile */;
19642                     break;
19643                 case 6 /* JSON */:
19644                     contextFlags = 131072 /* JavaScriptFile */ | 33554432 /* JsonFile */;
19645                     break;
19646                 default:
19647                     contextFlags = 0 /* None */;
19648                     break;
19649             }
19650             parseErrorBeforeNextFinishedNode = false;
19651             // Initialize and prime the scanner before parsing the source elements.
19652             scanner.setText(sourceText);
19653             scanner.setOnError(scanError);
19654             scanner.setScriptTarget(languageVersion);
19655             scanner.setLanguageVariant(getLanguageVariant(scriptKind));
19656         }
19657         function clearState() {
19658             // Clear out the text the scanner is pointing at, so it doesn't keep anything alive unnecessarily.
19659             scanner.clearCommentDirectives();
19660             scanner.setText("");
19661             scanner.setOnError(undefined);
19662             // Clear any data.  We don't want to accidentally hold onto it for too long.
19663             parseDiagnostics = undefined;
19664             sourceFile = undefined;
19665             identifiers = undefined;
19666             syntaxCursor = undefined;
19667             sourceText = undefined;
19668             notParenthesizedArrow = undefined;
19669         }
19670         function parseSourceFileWorker(fileName, languageVersion, setParentNodes, scriptKind) {
19671             var isDeclarationFile = isDeclarationFileName(fileName);
19672             if (isDeclarationFile) {
19673                 contextFlags |= 8388608 /* Ambient */;
19674             }
19675             sourceFile = createSourceFile(fileName, languageVersion, scriptKind, isDeclarationFile);
19676             sourceFile.flags = contextFlags;
19677             // Prime the scanner.
19678             nextToken();
19679             // 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
19680             processCommentPragmas(sourceFile, sourceText);
19681             processPragmasIntoFields(sourceFile, reportPragmaDiagnostic);
19682             sourceFile.statements = parseList(0 /* SourceElements */, parseStatement);
19683             ts.Debug.assert(token() === 1 /* EndOfFileToken */);
19684             sourceFile.endOfFileToken = addJSDocComment(parseTokenNode());
19685             setExternalModuleIndicator(sourceFile);
19686             sourceFile.commentDirectives = scanner.getCommentDirectives();
19687             sourceFile.nodeCount = nodeCount;
19688             sourceFile.identifierCount = identifierCount;
19689             sourceFile.identifiers = identifiers;
19690             sourceFile.parseDiagnostics = parseDiagnostics;
19691             if (setParentNodes) {
19692                 fixupParentReferences(sourceFile);
19693             }
19694             return sourceFile;
19695             function reportPragmaDiagnostic(pos, end, diagnostic) {
19696                 parseDiagnostics.push(ts.createFileDiagnostic(sourceFile, pos, end, diagnostic));
19697             }
19698         }
19699         function addJSDocComment(node) {
19700             ts.Debug.assert(!node.jsDoc); // Should only be called once per node
19701             var jsDoc = ts.mapDefined(ts.getJSDocCommentRanges(node, sourceFile.text), function (comment) { return JSDocParser.parseJSDocComment(node, comment.pos, comment.end - comment.pos); });
19702             if (jsDoc.length)
19703                 node.jsDoc = jsDoc;
19704             return node;
19705         }
19706         function fixupParentReferences(rootNode) {
19707             // normally parent references are set during binding. However, for clients that only need
19708             // a syntax tree, and no semantic features, then the binding process is an unnecessary
19709             // overhead.  This functions allows us to set all the parents, without all the expense of
19710             // binding.
19711             forEachChildRecursively(rootNode, bindParentToChild);
19712             function bindParentToChild(child, parent) {
19713                 child.parent = parent;
19714                 if (ts.hasJSDocNodes(child)) {
19715                     for (var _i = 0, _a = child.jsDoc; _i < _a.length; _i++) {
19716                         var doc = _a[_i];
19717                         bindParentToChild(doc, child);
19718                         forEachChildRecursively(doc, bindParentToChild);
19719                     }
19720                 }
19721             }
19722         }
19723         Parser.fixupParentReferences = fixupParentReferences;
19724         function createSourceFile(fileName, languageVersion, scriptKind, isDeclarationFile) {
19725             // code from createNode is inlined here so createNode won't have to deal with special case of creating source files
19726             // this is quite rare comparing to other nodes and createNode should be as fast as possible
19727             var sourceFile = new SourceFileConstructor(290 /* SourceFile */, /*pos*/ 0, /* end */ sourceText.length);
19728             nodeCount++;
19729             sourceFile.text = sourceText;
19730             sourceFile.bindDiagnostics = [];
19731             sourceFile.bindSuggestionDiagnostics = undefined;
19732             sourceFile.languageVersion = languageVersion;
19733             sourceFile.fileName = ts.normalizePath(fileName);
19734             sourceFile.languageVariant = getLanguageVariant(scriptKind);
19735             sourceFile.isDeclarationFile = isDeclarationFile;
19736             sourceFile.scriptKind = scriptKind;
19737             return sourceFile;
19738         }
19739         function setContextFlag(val, flag) {
19740             if (val) {
19741                 contextFlags |= flag;
19742             }
19743             else {
19744                 contextFlags &= ~flag;
19745             }
19746         }
19747         function setDisallowInContext(val) {
19748             setContextFlag(val, 4096 /* DisallowInContext */);
19749         }
19750         function setYieldContext(val) {
19751             setContextFlag(val, 8192 /* YieldContext */);
19752         }
19753         function setDecoratorContext(val) {
19754             setContextFlag(val, 16384 /* DecoratorContext */);
19755         }
19756         function setAwaitContext(val) {
19757             setContextFlag(val, 32768 /* AwaitContext */);
19758         }
19759         function doOutsideOfContext(context, func) {
19760             // contextFlagsToClear will contain only the context flags that are
19761             // currently set that we need to temporarily clear
19762             // We don't just blindly reset to the previous flags to ensure
19763             // that we do not mutate cached flags for the incremental
19764             // parser (ThisNodeHasError, ThisNodeOrAnySubNodesHasError, and
19765             // HasAggregatedChildData).
19766             var contextFlagsToClear = context & contextFlags;
19767             if (contextFlagsToClear) {
19768                 // clear the requested context flags
19769                 setContextFlag(/*val*/ false, contextFlagsToClear);
19770                 var result = func();
19771                 // restore the context flags we just cleared
19772                 setContextFlag(/*val*/ true, contextFlagsToClear);
19773                 return result;
19774             }
19775             // no need to do anything special as we are not in any of the requested contexts
19776             return func();
19777         }
19778         function doInsideOfContext(context, func) {
19779             // contextFlagsToSet will contain only the context flags that
19780             // are not currently set that we need to temporarily enable.
19781             // We don't just blindly reset to the previous flags to ensure
19782             // that we do not mutate cached flags for the incremental
19783             // parser (ThisNodeHasError, ThisNodeOrAnySubNodesHasError, and
19784             // HasAggregatedChildData).
19785             var contextFlagsToSet = context & ~contextFlags;
19786             if (contextFlagsToSet) {
19787                 // set the requested context flags
19788                 setContextFlag(/*val*/ true, contextFlagsToSet);
19789                 var result = func();
19790                 // reset the context flags we just set
19791                 setContextFlag(/*val*/ false, contextFlagsToSet);
19792                 return result;
19793             }
19794             // no need to do anything special as we are already in all of the requested contexts
19795             return func();
19796         }
19797         function allowInAnd(func) {
19798             return doOutsideOfContext(4096 /* DisallowInContext */, func);
19799         }
19800         function disallowInAnd(func) {
19801             return doInsideOfContext(4096 /* DisallowInContext */, func);
19802         }
19803         function doInYieldContext(func) {
19804             return doInsideOfContext(8192 /* YieldContext */, func);
19805         }
19806         function doInDecoratorContext(func) {
19807             return doInsideOfContext(16384 /* DecoratorContext */, func);
19808         }
19809         function doInAwaitContext(func) {
19810             return doInsideOfContext(32768 /* AwaitContext */, func);
19811         }
19812         function doOutsideOfAwaitContext(func) {
19813             return doOutsideOfContext(32768 /* AwaitContext */, func);
19814         }
19815         function doInYieldAndAwaitContext(func) {
19816             return doInsideOfContext(8192 /* YieldContext */ | 32768 /* AwaitContext */, func);
19817         }
19818         function doOutsideOfYieldAndAwaitContext(func) {
19819             return doOutsideOfContext(8192 /* YieldContext */ | 32768 /* AwaitContext */, func);
19820         }
19821         function inContext(flags) {
19822             return (contextFlags & flags) !== 0;
19823         }
19824         function inYieldContext() {
19825             return inContext(8192 /* YieldContext */);
19826         }
19827         function inDisallowInContext() {
19828             return inContext(4096 /* DisallowInContext */);
19829         }
19830         function inDecoratorContext() {
19831             return inContext(16384 /* DecoratorContext */);
19832         }
19833         function inAwaitContext() {
19834             return inContext(32768 /* AwaitContext */);
19835         }
19836         function parseErrorAtCurrentToken(message, arg0) {
19837             parseErrorAt(scanner.getTokenPos(), scanner.getTextPos(), message, arg0);
19838         }
19839         function parseErrorAtPosition(start, length, message, arg0) {
19840             // Don't report another error if it would just be at the same position as the last error.
19841             var lastError = ts.lastOrUndefined(parseDiagnostics);
19842             if (!lastError || start !== lastError.start) {
19843                 parseDiagnostics.push(ts.createFileDiagnostic(sourceFile, start, length, message, arg0));
19844             }
19845             // Mark that we've encountered an error.  We'll set an appropriate bit on the next
19846             // node we finish so that it can't be reused incrementally.
19847             parseErrorBeforeNextFinishedNode = true;
19848         }
19849         function parseErrorAt(start, end, message, arg0) {
19850             parseErrorAtPosition(start, end - start, message, arg0);
19851         }
19852         function parseErrorAtRange(range, message, arg0) {
19853             parseErrorAt(range.pos, range.end, message, arg0);
19854         }
19855         function scanError(message, length) {
19856             parseErrorAtPosition(scanner.getTextPos(), length, message);
19857         }
19858         function getNodePos() {
19859             return scanner.getStartPos();
19860         }
19861         // Use this function to access the current token instead of reading the currentToken
19862         // variable. Since function results aren't narrowed in control flow analysis, this ensures
19863         // that the type checker doesn't make wrong assumptions about the type of the current
19864         // token (e.g. a call to nextToken() changes the current token but the checker doesn't
19865         // reason about this side effect).  Mainstream VMs inline simple functions like this, so
19866         // there is no performance penalty.
19867         function token() {
19868             return currentToken;
19869         }
19870         function nextTokenWithoutCheck() {
19871             return currentToken = scanner.scan();
19872         }
19873         function nextToken() {
19874             // if the keyword had an escape
19875             if (ts.isKeyword(currentToken) && (scanner.hasUnicodeEscape() || scanner.hasExtendedUnicodeEscape())) {
19876                 // issue a parse error for the escape
19877                 parseErrorAt(scanner.getTokenPos(), scanner.getTextPos(), ts.Diagnostics.Keywords_cannot_contain_escape_characters);
19878             }
19879             return nextTokenWithoutCheck();
19880         }
19881         function nextTokenJSDoc() {
19882             return currentToken = scanner.scanJsDocToken();
19883         }
19884         function reScanGreaterToken() {
19885             return currentToken = scanner.reScanGreaterToken();
19886         }
19887         function reScanSlashToken() {
19888             return currentToken = scanner.reScanSlashToken();
19889         }
19890         function reScanTemplateToken(isTaggedTemplate) {
19891             return currentToken = scanner.reScanTemplateToken(isTaggedTemplate);
19892         }
19893         function reScanTemplateHeadOrNoSubstitutionTemplate() {
19894             return currentToken = scanner.reScanTemplateHeadOrNoSubstitutionTemplate();
19895         }
19896         function reScanLessThanToken() {
19897             return currentToken = scanner.reScanLessThanToken();
19898         }
19899         function scanJsxIdentifier() {
19900             return currentToken = scanner.scanJsxIdentifier();
19901         }
19902         function scanJsxText() {
19903             return currentToken = scanner.scanJsxToken();
19904         }
19905         function scanJsxAttributeValue() {
19906             return currentToken = scanner.scanJsxAttributeValue();
19907         }
19908         function speculationHelper(callback, isLookAhead) {
19909             // Keep track of the state we'll need to rollback to if lookahead fails (or if the
19910             // caller asked us to always reset our state).
19911             var saveToken = currentToken;
19912             var saveParseDiagnosticsLength = parseDiagnostics.length;
19913             var saveParseErrorBeforeNextFinishedNode = parseErrorBeforeNextFinishedNode;
19914             // Note: it is not actually necessary to save/restore the context flags here.  That's
19915             // because the saving/restoring of these flags happens naturally through the recursive
19916             // descent nature of our parser.  However, we still store this here just so we can
19917             // assert that invariant holds.
19918             var saveContextFlags = contextFlags;
19919             // If we're only looking ahead, then tell the scanner to only lookahead as well.
19920             // Otherwise, if we're actually speculatively parsing, then tell the scanner to do the
19921             // same.
19922             var result = isLookAhead
19923                 ? scanner.lookAhead(callback)
19924                 : scanner.tryScan(callback);
19925             ts.Debug.assert(saveContextFlags === contextFlags);
19926             // If our callback returned something 'falsy' or we're just looking ahead,
19927             // then unconditionally restore us to where we were.
19928             if (!result || isLookAhead) {
19929                 currentToken = saveToken;
19930                 parseDiagnostics.length = saveParseDiagnosticsLength;
19931                 parseErrorBeforeNextFinishedNode = saveParseErrorBeforeNextFinishedNode;
19932             }
19933             return result;
19934         }
19935         /** Invokes the provided callback then unconditionally restores the parser to the state it
19936          * was in immediately prior to invoking the callback.  The result of invoking the callback
19937          * is returned from this function.
19938          */
19939         function lookAhead(callback) {
19940             return speculationHelper(callback, /*isLookAhead*/ true);
19941         }
19942         /** Invokes the provided callback.  If the callback returns something falsy, then it restores
19943          * the parser to the state it was in immediately prior to invoking the callback.  If the
19944          * callback returns something truthy, then the parser state is not rolled back.  The result
19945          * of invoking the callback is returned from this function.
19946          */
19947         function tryParse(callback) {
19948             return speculationHelper(callback, /*isLookAhead*/ false);
19949         }
19950         // Ignore strict mode flag because we will report an error in type checker instead.
19951         function isIdentifier() {
19952             if (token() === 75 /* Identifier */) {
19953                 return true;
19954             }
19955             // If we have a 'yield' keyword, and we're in the [yield] context, then 'yield' is
19956             // considered a keyword and is not an identifier.
19957             if (token() === 121 /* YieldKeyword */ && inYieldContext()) {
19958                 return false;
19959             }
19960             // If we have a 'await' keyword, and we're in the [Await] context, then 'await' is
19961             // considered a keyword and is not an identifier.
19962             if (token() === 127 /* AwaitKeyword */ && inAwaitContext()) {
19963                 return false;
19964             }
19965             return token() > 112 /* LastReservedWord */;
19966         }
19967         function parseExpected(kind, diagnosticMessage, shouldAdvance) {
19968             if (shouldAdvance === void 0) { shouldAdvance = true; }
19969             if (token() === kind) {
19970                 if (shouldAdvance) {
19971                     nextToken();
19972                 }
19973                 return true;
19974             }
19975             // Report specific message if provided with one.  Otherwise, report generic fallback message.
19976             if (diagnosticMessage) {
19977                 parseErrorAtCurrentToken(diagnosticMessage);
19978             }
19979             else {
19980                 parseErrorAtCurrentToken(ts.Diagnostics._0_expected, ts.tokenToString(kind));
19981             }
19982             return false;
19983         }
19984         function parseExpectedJSDoc(kind) {
19985             if (token() === kind) {
19986                 nextTokenJSDoc();
19987                 return true;
19988             }
19989             parseErrorAtCurrentToken(ts.Diagnostics._0_expected, ts.tokenToString(kind));
19990             return false;
19991         }
19992         function parseOptional(t) {
19993             if (token() === t) {
19994                 nextToken();
19995                 return true;
19996             }
19997             return false;
19998         }
19999         function parseOptionalToken(t) {
20000             if (token() === t) {
20001                 return parseTokenNode();
20002             }
20003             return undefined;
20004         }
20005         function parseOptionalTokenJSDoc(t) {
20006             if (token() === t) {
20007                 return parseTokenNodeJSDoc();
20008             }
20009             return undefined;
20010         }
20011         function parseExpectedToken(t, diagnosticMessage, arg0) {
20012             return parseOptionalToken(t) ||
20013                 createMissingNode(t, /*reportAtCurrentPosition*/ false, diagnosticMessage || ts.Diagnostics._0_expected, arg0 || ts.tokenToString(t));
20014         }
20015         function parseExpectedTokenJSDoc(t) {
20016             return parseOptionalTokenJSDoc(t) ||
20017                 createMissingNode(t, /*reportAtCurrentPosition*/ false, ts.Diagnostics._0_expected, ts.tokenToString(t));
20018         }
20019         function parseTokenNode() {
20020             var node = createNode(token());
20021             nextToken();
20022             return finishNode(node);
20023         }
20024         function parseTokenNodeJSDoc() {
20025             var node = createNode(token());
20026             nextTokenJSDoc();
20027             return finishNode(node);
20028         }
20029         function canParseSemicolon() {
20030             // If there's a real semicolon, then we can always parse it out.
20031             if (token() === 26 /* SemicolonToken */) {
20032                 return true;
20033             }
20034             // We can parse out an optional semicolon in ASI cases in the following cases.
20035             return token() === 19 /* CloseBraceToken */ || token() === 1 /* EndOfFileToken */ || scanner.hasPrecedingLineBreak();
20036         }
20037         function parseSemicolon() {
20038             if (canParseSemicolon()) {
20039                 if (token() === 26 /* SemicolonToken */) {
20040                     // consume the semicolon if it was explicitly provided.
20041                     nextToken();
20042                 }
20043                 return true;
20044             }
20045             else {
20046                 return parseExpected(26 /* SemicolonToken */);
20047             }
20048         }
20049         function createNode(kind, pos) {
20050             nodeCount++;
20051             var p = pos >= 0 ? pos : scanner.getStartPos();
20052             return ts.isNodeKind(kind) || kind === 0 /* Unknown */ ? new NodeConstructor(kind, p, p) :
20053                 kind === 75 /* Identifier */ ? new IdentifierConstructor(kind, p, p) :
20054                     kind === 76 /* PrivateIdentifier */ ? new PrivateIdentifierConstructor(kind, p, p) :
20055                         new TokenConstructor(kind, p, p);
20056         }
20057         function createNodeWithJSDoc(kind, pos) {
20058             var node = createNode(kind, pos);
20059             if (scanner.getTokenFlags() & 2 /* PrecedingJSDocComment */ && (kind !== 226 /* ExpressionStatement */ || token() !== 20 /* OpenParenToken */)) {
20060                 addJSDocComment(node);
20061             }
20062             return node;
20063         }
20064         function createNodeArray(elements, pos, end) {
20065             // Since the element list of a node array is typically created by starting with an empty array and
20066             // repeatedly calling push(), the list may not have the optimal memory layout. We invoke slice() for
20067             // small arrays (1 to 4 elements) to give the VM a chance to allocate an optimal representation.
20068             var length = elements.length;
20069             var array = (length >= 1 && length <= 4 ? elements.slice() : elements);
20070             array.pos = pos;
20071             array.end = end === undefined ? scanner.getStartPos() : end;
20072             return array;
20073         }
20074         function finishNode(node, end) {
20075             node.end = end === undefined ? scanner.getStartPos() : end;
20076             if (contextFlags) {
20077                 node.flags |= contextFlags;
20078             }
20079             // Keep track on the node if we encountered an error while parsing it.  If we did, then
20080             // we cannot reuse the node incrementally.  Once we've marked this node, clear out the
20081             // flag so that we don't mark any subsequent nodes.
20082             if (parseErrorBeforeNextFinishedNode) {
20083                 parseErrorBeforeNextFinishedNode = false;
20084                 node.flags |= 65536 /* ThisNodeHasError */;
20085             }
20086             return node;
20087         }
20088         function createMissingNode(kind, reportAtCurrentPosition, diagnosticMessage, arg0) {
20089             if (reportAtCurrentPosition) {
20090                 parseErrorAtPosition(scanner.getStartPos(), 0, diagnosticMessage, arg0);
20091             }
20092             else if (diagnosticMessage) {
20093                 parseErrorAtCurrentToken(diagnosticMessage, arg0);
20094             }
20095             var result = createNode(kind);
20096             if (kind === 75 /* Identifier */) {
20097                 result.escapedText = "";
20098             }
20099             else if (ts.isLiteralKind(kind) || ts.isTemplateLiteralKind(kind)) {
20100                 result.text = "";
20101             }
20102             return finishNode(result);
20103         }
20104         function internIdentifier(text) {
20105             var identifier = identifiers.get(text);
20106             if (identifier === undefined) {
20107                 identifiers.set(text, identifier = text);
20108             }
20109             return identifier;
20110         }
20111         // An identifier that starts with two underscores has an extra underscore character prepended to it to avoid issues
20112         // with magic property names like '__proto__'. The 'identifiers' object is used to share a single string instance for
20113         // each identifier in order to reduce memory consumption.
20114         function createIdentifier(isIdentifier, diagnosticMessage, privateIdentifierDiagnosticMessage) {
20115             identifierCount++;
20116             if (isIdentifier) {
20117                 var node = createNode(75 /* Identifier */);
20118                 // Store original token kind if it is not just an Identifier so we can report appropriate error later in type checker
20119                 if (token() !== 75 /* Identifier */) {
20120                     node.originalKeywordKind = token();
20121                 }
20122                 node.escapedText = ts.escapeLeadingUnderscores(internIdentifier(scanner.getTokenValue()));
20123                 nextTokenWithoutCheck();
20124                 return finishNode(node);
20125             }
20126             if (token() === 76 /* PrivateIdentifier */) {
20127                 parseErrorAtCurrentToken(privateIdentifierDiagnosticMessage || ts.Diagnostics.Private_identifiers_are_not_allowed_outside_class_bodies);
20128                 return createIdentifier(/*isIdentifier*/ true);
20129             }
20130             // Only for end of file because the error gets reported incorrectly on embedded script tags.
20131             var reportAtCurrentPosition = token() === 1 /* EndOfFileToken */;
20132             var isReservedWord = scanner.isReservedWord();
20133             var msgArg = scanner.getTokenText();
20134             var defaultMessage = isReservedWord ?
20135                 ts.Diagnostics.Identifier_expected_0_is_a_reserved_word_that_cannot_be_used_here :
20136                 ts.Diagnostics.Identifier_expected;
20137             return createMissingNode(75 /* Identifier */, reportAtCurrentPosition, diagnosticMessage || defaultMessage, msgArg);
20138         }
20139         function parseIdentifier(diagnosticMessage, privateIdentifierDiagnosticMessage) {
20140             return createIdentifier(isIdentifier(), diagnosticMessage, privateIdentifierDiagnosticMessage);
20141         }
20142         function parseIdentifierName(diagnosticMessage) {
20143             return createIdentifier(ts.tokenIsIdentifierOrKeyword(token()), diagnosticMessage);
20144         }
20145         function isLiteralPropertyName() {
20146             return ts.tokenIsIdentifierOrKeyword(token()) ||
20147                 token() === 10 /* StringLiteral */ ||
20148                 token() === 8 /* NumericLiteral */;
20149         }
20150         function parsePropertyNameWorker(allowComputedPropertyNames) {
20151             if (token() === 10 /* StringLiteral */ || token() === 8 /* NumericLiteral */) {
20152                 var node = parseLiteralNode();
20153                 node.text = internIdentifier(node.text);
20154                 return node;
20155             }
20156             if (allowComputedPropertyNames && token() === 22 /* OpenBracketToken */) {
20157                 return parseComputedPropertyName();
20158             }
20159             if (token() === 76 /* PrivateIdentifier */) {
20160                 return parsePrivateIdentifier();
20161             }
20162             return parseIdentifierName();
20163         }
20164         function parsePropertyName() {
20165             return parsePropertyNameWorker(/*allowComputedPropertyNames*/ true);
20166         }
20167         function parseComputedPropertyName() {
20168             // PropertyName [Yield]:
20169             //      LiteralPropertyName
20170             //      ComputedPropertyName[?Yield]
20171             var node = createNode(154 /* ComputedPropertyName */);
20172             parseExpected(22 /* OpenBracketToken */);
20173             // We parse any expression (including a comma expression). But the grammar
20174             // says that only an assignment expression is allowed, so the grammar checker
20175             // will error if it sees a comma expression.
20176             node.expression = allowInAnd(parseExpression);
20177             parseExpected(23 /* CloseBracketToken */);
20178             return finishNode(node);
20179         }
20180         function internPrivateIdentifier(text) {
20181             var privateIdentifier = privateIdentifiers.get(text);
20182             if (privateIdentifier === undefined) {
20183                 privateIdentifiers.set(text, privateIdentifier = text);
20184             }
20185             return privateIdentifier;
20186         }
20187         function parsePrivateIdentifier() {
20188             var node = createNode(76 /* PrivateIdentifier */);
20189             node.escapedText = ts.escapeLeadingUnderscores(internPrivateIdentifier(scanner.getTokenText()));
20190             nextToken();
20191             return finishNode(node);
20192         }
20193         function parseContextualModifier(t) {
20194             return token() === t && tryParse(nextTokenCanFollowModifier);
20195         }
20196         function nextTokenIsOnSameLineAndCanFollowModifier() {
20197             nextToken();
20198             if (scanner.hasPrecedingLineBreak()) {
20199                 return false;
20200             }
20201             return canFollowModifier();
20202         }
20203         function nextTokenCanFollowModifier() {
20204             switch (token()) {
20205                 case 81 /* ConstKeyword */:
20206                     // 'const' is only a modifier if followed by 'enum'.
20207                     return nextToken() === 88 /* EnumKeyword */;
20208                 case 89 /* ExportKeyword */:
20209                     nextToken();
20210                     if (token() === 84 /* DefaultKeyword */) {
20211                         return lookAhead(nextTokenCanFollowDefaultKeyword);
20212                     }
20213                     if (token() === 145 /* TypeKeyword */) {
20214                         return lookAhead(nextTokenCanFollowExportModifier);
20215                     }
20216                     return canFollowExportModifier();
20217                 case 84 /* DefaultKeyword */:
20218                     return nextTokenCanFollowDefaultKeyword();
20219                 case 120 /* StaticKeyword */:
20220                 case 131 /* GetKeyword */:
20221                 case 142 /* SetKeyword */:
20222                     nextToken();
20223                     return canFollowModifier();
20224                 default:
20225                     return nextTokenIsOnSameLineAndCanFollowModifier();
20226             }
20227         }
20228         function canFollowExportModifier() {
20229             return token() !== 41 /* AsteriskToken */
20230                 && token() !== 123 /* AsKeyword */
20231                 && token() !== 18 /* OpenBraceToken */
20232                 && canFollowModifier();
20233         }
20234         function nextTokenCanFollowExportModifier() {
20235             nextToken();
20236             return canFollowExportModifier();
20237         }
20238         function parseAnyContextualModifier() {
20239             return ts.isModifierKind(token()) && tryParse(nextTokenCanFollowModifier);
20240         }
20241         function canFollowModifier() {
20242             return token() === 22 /* OpenBracketToken */
20243                 || token() === 18 /* OpenBraceToken */
20244                 || token() === 41 /* AsteriskToken */
20245                 || token() === 25 /* DotDotDotToken */
20246                 || isLiteralPropertyName();
20247         }
20248         function nextTokenCanFollowDefaultKeyword() {
20249             nextToken();
20250             return token() === 80 /* ClassKeyword */ || token() === 94 /* FunctionKeyword */ ||
20251                 token() === 114 /* InterfaceKeyword */ ||
20252                 (token() === 122 /* AbstractKeyword */ && lookAhead(nextTokenIsClassKeywordOnSameLine)) ||
20253                 (token() === 126 /* AsyncKeyword */ && lookAhead(nextTokenIsFunctionKeywordOnSameLine));
20254         }
20255         // True if positioned at the start of a list element
20256         function isListElement(parsingContext, inErrorRecovery) {
20257             var node = currentNode(parsingContext);
20258             if (node) {
20259                 return true;
20260             }
20261             switch (parsingContext) {
20262                 case 0 /* SourceElements */:
20263                 case 1 /* BlockStatements */:
20264                 case 3 /* SwitchClauseStatements */:
20265                     // If we're in error recovery, then we don't want to treat ';' as an empty statement.
20266                     // The problem is that ';' can show up in far too many contexts, and if we see one
20267                     // and assume it's a statement, then we may bail out inappropriately from whatever
20268                     // we're parsing.  For example, if we have a semicolon in the middle of a class, then
20269                     // we really don't want to assume the class is over and we're on a statement in the
20270                     // outer module.  We just want to consume and move on.
20271                     return !(token() === 26 /* SemicolonToken */ && inErrorRecovery) && isStartOfStatement();
20272                 case 2 /* SwitchClauses */:
20273                     return token() === 78 /* CaseKeyword */ || token() === 84 /* DefaultKeyword */;
20274                 case 4 /* TypeMembers */:
20275                     return lookAhead(isTypeMemberStart);
20276                 case 5 /* ClassMembers */:
20277                     // We allow semicolons as class elements (as specified by ES6) as long as we're
20278                     // not in error recovery.  If we're in error recovery, we don't want an errant
20279                     // semicolon to be treated as a class member (since they're almost always used
20280                     // for statements.
20281                     return lookAhead(isClassMemberStart) || (token() === 26 /* SemicolonToken */ && !inErrorRecovery);
20282                 case 6 /* EnumMembers */:
20283                     // Include open bracket computed properties. This technically also lets in indexers,
20284                     // which would be a candidate for improved error reporting.
20285                     return token() === 22 /* OpenBracketToken */ || isLiteralPropertyName();
20286                 case 12 /* ObjectLiteralMembers */:
20287                     switch (token()) {
20288                         case 22 /* OpenBracketToken */:
20289                         case 41 /* AsteriskToken */:
20290                         case 25 /* DotDotDotToken */:
20291                         case 24 /* DotToken */: // Not an object literal member, but don't want to close the object (see `tests/cases/fourslash/completionsDotInObjectLiteral.ts`)
20292                             return true;
20293                         default:
20294                             return isLiteralPropertyName();
20295                     }
20296                 case 18 /* RestProperties */:
20297                     return isLiteralPropertyName();
20298                 case 9 /* ObjectBindingElements */:
20299                     return token() === 22 /* OpenBracketToken */ || token() === 25 /* DotDotDotToken */ || isLiteralPropertyName();
20300                 case 7 /* HeritageClauseElement */:
20301                     // If we see `{ ... }` then only consume it as an expression if it is followed by `,` or `{`
20302                     // That way we won't consume the body of a class in its heritage clause.
20303                     if (token() === 18 /* OpenBraceToken */) {
20304                         return lookAhead(isValidHeritageClauseObjectLiteral);
20305                     }
20306                     if (!inErrorRecovery) {
20307                         return isStartOfLeftHandSideExpression() && !isHeritageClauseExtendsOrImplementsKeyword();
20308                     }
20309                     else {
20310                         // If we're in error recovery we tighten up what we're willing to match.
20311                         // That way we don't treat something like "this" as a valid heritage clause
20312                         // element during recovery.
20313                         return isIdentifier() && !isHeritageClauseExtendsOrImplementsKeyword();
20314                     }
20315                 case 8 /* VariableDeclarations */:
20316                     return isIdentifierOrPrivateIdentifierOrPattern();
20317                 case 10 /* ArrayBindingElements */:
20318                     return token() === 27 /* CommaToken */ || token() === 25 /* DotDotDotToken */ || isIdentifierOrPrivateIdentifierOrPattern();
20319                 case 19 /* TypeParameters */:
20320                     return isIdentifier();
20321                 case 15 /* ArrayLiteralMembers */:
20322                     switch (token()) {
20323                         case 27 /* CommaToken */:
20324                         case 24 /* DotToken */: // Not an array literal member, but don't want to close the array (see `tests/cases/fourslash/completionsDotInArrayLiteralInObjectLiteral.ts`)
20325                             return true;
20326                     }
20327                 // falls through
20328                 case 11 /* ArgumentExpressions */:
20329                     return token() === 25 /* DotDotDotToken */ || isStartOfExpression();
20330                 case 16 /* Parameters */:
20331                     return isStartOfParameter(/*isJSDocParameter*/ false);
20332                 case 17 /* JSDocParameters */:
20333                     return isStartOfParameter(/*isJSDocParameter*/ true);
20334                 case 20 /* TypeArguments */:
20335                 case 21 /* TupleElementTypes */:
20336                     return token() === 27 /* CommaToken */ || isStartOfType();
20337                 case 22 /* HeritageClauses */:
20338                     return isHeritageClause();
20339                 case 23 /* ImportOrExportSpecifiers */:
20340                     return ts.tokenIsIdentifierOrKeyword(token());
20341                 case 13 /* JsxAttributes */:
20342                     return ts.tokenIsIdentifierOrKeyword(token()) || token() === 18 /* OpenBraceToken */;
20343                 case 14 /* JsxChildren */:
20344                     return true;
20345             }
20346             return ts.Debug.fail("Non-exhaustive case in 'isListElement'.");
20347         }
20348         function isValidHeritageClauseObjectLiteral() {
20349             ts.Debug.assert(token() === 18 /* OpenBraceToken */);
20350             if (nextToken() === 19 /* CloseBraceToken */) {
20351                 // if we see "extends {}" then only treat the {} as what we're extending (and not
20352                 // the class body) if we have:
20353                 //
20354                 //      extends {} {
20355                 //      extends {},
20356                 //      extends {} extends
20357                 //      extends {} implements
20358                 var next = nextToken();
20359                 return next === 27 /* CommaToken */ || next === 18 /* OpenBraceToken */ || next === 90 /* ExtendsKeyword */ || next === 113 /* ImplementsKeyword */;
20360             }
20361             return true;
20362         }
20363         function nextTokenIsIdentifier() {
20364             nextToken();
20365             return isIdentifier();
20366         }
20367         function nextTokenIsIdentifierOrKeyword() {
20368             nextToken();
20369             return ts.tokenIsIdentifierOrKeyword(token());
20370         }
20371         function nextTokenIsIdentifierOrKeywordOrGreaterThan() {
20372             nextToken();
20373             return ts.tokenIsIdentifierOrKeywordOrGreaterThan(token());
20374         }
20375         function isHeritageClauseExtendsOrImplementsKeyword() {
20376             if (token() === 113 /* ImplementsKeyword */ ||
20377                 token() === 90 /* ExtendsKeyword */) {
20378                 return lookAhead(nextTokenIsStartOfExpression);
20379             }
20380             return false;
20381         }
20382         function nextTokenIsStartOfExpression() {
20383             nextToken();
20384             return isStartOfExpression();
20385         }
20386         function nextTokenIsStartOfType() {
20387             nextToken();
20388             return isStartOfType();
20389         }
20390         // True if positioned at a list terminator
20391         function isListTerminator(kind) {
20392             if (token() === 1 /* EndOfFileToken */) {
20393                 // Being at the end of the file ends all lists.
20394                 return true;
20395             }
20396             switch (kind) {
20397                 case 1 /* BlockStatements */:
20398                 case 2 /* SwitchClauses */:
20399                 case 4 /* TypeMembers */:
20400                 case 5 /* ClassMembers */:
20401                 case 6 /* EnumMembers */:
20402                 case 12 /* ObjectLiteralMembers */:
20403                 case 9 /* ObjectBindingElements */:
20404                 case 23 /* ImportOrExportSpecifiers */:
20405                     return token() === 19 /* CloseBraceToken */;
20406                 case 3 /* SwitchClauseStatements */:
20407                     return token() === 19 /* CloseBraceToken */ || token() === 78 /* CaseKeyword */ || token() === 84 /* DefaultKeyword */;
20408                 case 7 /* HeritageClauseElement */:
20409                     return token() === 18 /* OpenBraceToken */ || token() === 90 /* ExtendsKeyword */ || token() === 113 /* ImplementsKeyword */;
20410                 case 8 /* VariableDeclarations */:
20411                     return isVariableDeclaratorListTerminator();
20412                 case 19 /* TypeParameters */:
20413                     // Tokens other than '>' are here for better error recovery
20414                     return token() === 31 /* GreaterThanToken */ || token() === 20 /* OpenParenToken */ || token() === 18 /* OpenBraceToken */ || token() === 90 /* ExtendsKeyword */ || token() === 113 /* ImplementsKeyword */;
20415                 case 11 /* ArgumentExpressions */:
20416                     // Tokens other than ')' are here for better error recovery
20417                     return token() === 21 /* CloseParenToken */ || token() === 26 /* SemicolonToken */;
20418                 case 15 /* ArrayLiteralMembers */:
20419                 case 21 /* TupleElementTypes */:
20420                 case 10 /* ArrayBindingElements */:
20421                     return token() === 23 /* CloseBracketToken */;
20422                 case 17 /* JSDocParameters */:
20423                 case 16 /* Parameters */:
20424                 case 18 /* RestProperties */:
20425                     // Tokens other than ')' and ']' (the latter for index signatures) are here for better error recovery
20426                     return token() === 21 /* CloseParenToken */ || token() === 23 /* CloseBracketToken */ /*|| token === SyntaxKind.OpenBraceToken*/;
20427                 case 20 /* TypeArguments */:
20428                     // All other tokens should cause the type-argument to terminate except comma token
20429                     return token() !== 27 /* CommaToken */;
20430                 case 22 /* HeritageClauses */:
20431                     return token() === 18 /* OpenBraceToken */ || token() === 19 /* CloseBraceToken */;
20432                 case 13 /* JsxAttributes */:
20433                     return token() === 31 /* GreaterThanToken */ || token() === 43 /* SlashToken */;
20434                 case 14 /* JsxChildren */:
20435                     return token() === 29 /* LessThanToken */ && lookAhead(nextTokenIsSlash);
20436                 default:
20437                     return false;
20438             }
20439         }
20440         function isVariableDeclaratorListTerminator() {
20441             // If we can consume a semicolon (either explicitly, or with ASI), then consider us done
20442             // with parsing the list of variable declarators.
20443             if (canParseSemicolon()) {
20444                 return true;
20445             }
20446             // in the case where we're parsing the variable declarator of a 'for-in' statement, we
20447             // are done if we see an 'in' keyword in front of us. Same with for-of
20448             if (isInOrOfKeyword(token())) {
20449                 return true;
20450             }
20451             // ERROR RECOVERY TWEAK:
20452             // For better error recovery, if we see an '=>' then we just stop immediately.  We've got an
20453             // arrow function here and it's going to be very unlikely that we'll resynchronize and get
20454             // another variable declaration.
20455             if (token() === 38 /* EqualsGreaterThanToken */) {
20456                 return true;
20457             }
20458             // Keep trying to parse out variable declarators.
20459             return false;
20460         }
20461         // True if positioned at element or terminator of the current list or any enclosing list
20462         function isInSomeParsingContext() {
20463             for (var kind = 0; kind < 24 /* Count */; kind++) {
20464                 if (parsingContext & (1 << kind)) {
20465                     if (isListElement(kind, /*inErrorRecovery*/ true) || isListTerminator(kind)) {
20466                         return true;
20467                     }
20468                 }
20469             }
20470             return false;
20471         }
20472         // Parses a list of elements
20473         function parseList(kind, parseElement) {
20474             var saveParsingContext = parsingContext;
20475             parsingContext |= 1 << kind;
20476             var list = [];
20477             var listPos = getNodePos();
20478             while (!isListTerminator(kind)) {
20479                 if (isListElement(kind, /*inErrorRecovery*/ false)) {
20480                     var element = parseListElement(kind, parseElement);
20481                     list.push(element);
20482                     continue;
20483                 }
20484                 if (abortParsingListOrMoveToNextToken(kind)) {
20485                     break;
20486                 }
20487             }
20488             parsingContext = saveParsingContext;
20489             return createNodeArray(list, listPos);
20490         }
20491         function parseListElement(parsingContext, parseElement) {
20492             var node = currentNode(parsingContext);
20493             if (node) {
20494                 return consumeNode(node);
20495             }
20496             return parseElement();
20497         }
20498         function currentNode(parsingContext) {
20499             // If we don't have a cursor or the parsing context isn't reusable, there's nothing to reuse.
20500             //
20501             // If there is an outstanding parse error that we've encountered, but not attached to
20502             // some node, then we cannot get a node from the old source tree.  This is because we
20503             // want to mark the next node we encounter as being unusable.
20504             //
20505             // Note: This may be too conservative.  Perhaps we could reuse the node and set the bit
20506             // on it (or its leftmost child) as having the error.  For now though, being conservative
20507             // is nice and likely won't ever affect perf.
20508             if (!syntaxCursor || !isReusableParsingContext(parsingContext) || parseErrorBeforeNextFinishedNode) {
20509                 return undefined;
20510             }
20511             var node = syntaxCursor.currentNode(scanner.getStartPos());
20512             // Can't reuse a missing node.
20513             // Can't reuse a node that intersected the change range.
20514             // Can't reuse a node that contains a parse error.  This is necessary so that we
20515             // produce the same set of errors again.
20516             if (ts.nodeIsMissing(node) || node.intersectsChange || ts.containsParseError(node)) {
20517                 return undefined;
20518             }
20519             // We can only reuse a node if it was parsed under the same strict mode that we're
20520             // currently in.  i.e. if we originally parsed a node in non-strict mode, but then
20521             // the user added 'using strict' at the top of the file, then we can't use that node
20522             // again as the presence of strict mode may cause us to parse the tokens in the file
20523             // differently.
20524             //
20525             // Note: we *can* reuse tokens when the strict mode changes.  That's because tokens
20526             // are unaffected by strict mode.  It's just the parser will decide what to do with it
20527             // differently depending on what mode it is in.
20528             //
20529             // This also applies to all our other context flags as well.
20530             var nodeContextFlags = node.flags & 25358336 /* ContextFlags */;
20531             if (nodeContextFlags !== contextFlags) {
20532                 return undefined;
20533             }
20534             // Ok, we have a node that looks like it could be reused.  Now verify that it is valid
20535             // in the current list parsing context that we're currently at.
20536             if (!canReuseNode(node, parsingContext)) {
20537                 return undefined;
20538             }
20539             if (node.jsDocCache) {
20540                 // jsDocCache may include tags from parent nodes, which might have been modified.
20541                 node.jsDocCache = undefined;
20542             }
20543             return node;
20544         }
20545         function consumeNode(node) {
20546             // Move the scanner so it is after the node we just consumed.
20547             scanner.setTextPos(node.end);
20548             nextToken();
20549             return node;
20550         }
20551         function isReusableParsingContext(parsingContext) {
20552             switch (parsingContext) {
20553                 case 5 /* ClassMembers */:
20554                 case 2 /* SwitchClauses */:
20555                 case 0 /* SourceElements */:
20556                 case 1 /* BlockStatements */:
20557                 case 3 /* SwitchClauseStatements */:
20558                 case 6 /* EnumMembers */:
20559                 case 4 /* TypeMembers */:
20560                 case 8 /* VariableDeclarations */:
20561                 case 17 /* JSDocParameters */:
20562                 case 16 /* Parameters */:
20563                     return true;
20564             }
20565             return false;
20566         }
20567         function canReuseNode(node, parsingContext) {
20568             switch (parsingContext) {
20569                 case 5 /* ClassMembers */:
20570                     return isReusableClassMember(node);
20571                 case 2 /* SwitchClauses */:
20572                     return isReusableSwitchClause(node);
20573                 case 0 /* SourceElements */:
20574                 case 1 /* BlockStatements */:
20575                 case 3 /* SwitchClauseStatements */:
20576                     return isReusableStatement(node);
20577                 case 6 /* EnumMembers */:
20578                     return isReusableEnumMember(node);
20579                 case 4 /* TypeMembers */:
20580                     return isReusableTypeMember(node);
20581                 case 8 /* VariableDeclarations */:
20582                     return isReusableVariableDeclaration(node);
20583                 case 17 /* JSDocParameters */:
20584                 case 16 /* Parameters */:
20585                     return isReusableParameter(node);
20586                 // Any other lists we do not care about reusing nodes in.  But feel free to add if
20587                 // you can do so safely.  Danger areas involve nodes that may involve speculative
20588                 // parsing.  If speculative parsing is involved with the node, then the range the
20589                 // parser reached while looking ahead might be in the edited range (see the example
20590                 // in canReuseVariableDeclaratorNode for a good case of this).
20591                 // case ParsingContext.HeritageClauses:
20592                 // This would probably be safe to reuse.  There is no speculative parsing with
20593                 // heritage clauses.
20594                 // case ParsingContext.TypeParameters:
20595                 // This would probably be safe to reuse.  There is no speculative parsing with
20596                 // type parameters.  Note that that's because type *parameters* only occur in
20597                 // unambiguous *type* contexts.  While type *arguments* occur in very ambiguous
20598                 // *expression* contexts.
20599                 // case ParsingContext.TupleElementTypes:
20600                 // This would probably be safe to reuse.  There is no speculative parsing with
20601                 // tuple types.
20602                 // Technically, type argument list types are probably safe to reuse.  While
20603                 // speculative parsing is involved with them (since type argument lists are only
20604                 // produced from speculative parsing a < as a type argument list), we only have
20605                 // the types because speculative parsing succeeded.  Thus, the lookahead never
20606                 // went past the end of the list and rewound.
20607                 // case ParsingContext.TypeArguments:
20608                 // Note: these are almost certainly not safe to ever reuse.  Expressions commonly
20609                 // need a large amount of lookahead, and we should not reuse them as they may
20610                 // have actually intersected the edit.
20611                 // case ParsingContext.ArgumentExpressions:
20612                 // This is not safe to reuse for the same reason as the 'AssignmentExpression'
20613                 // cases.  i.e. a property assignment may end with an expression, and thus might
20614                 // have lookahead far beyond it's old node.
20615                 // case ParsingContext.ObjectLiteralMembers:
20616                 // This is probably not safe to reuse.  There can be speculative parsing with
20617                 // type names in a heritage clause.  There can be generic names in the type
20618                 // name list, and there can be left hand side expressions (which can have type
20619                 // arguments.)
20620                 // case ParsingContext.HeritageClauseElement:
20621                 // Perhaps safe to reuse, but it's unlikely we'd see more than a dozen attributes
20622                 // on any given element. Same for children.
20623                 // case ParsingContext.JsxAttributes:
20624                 // case ParsingContext.JsxChildren:
20625             }
20626             return false;
20627         }
20628         function isReusableClassMember(node) {
20629             if (node) {
20630                 switch (node.kind) {
20631                     case 162 /* Constructor */:
20632                     case 167 /* IndexSignature */:
20633                     case 163 /* GetAccessor */:
20634                     case 164 /* SetAccessor */:
20635                     case 159 /* PropertyDeclaration */:
20636                     case 222 /* SemicolonClassElement */:
20637                         return true;
20638                     case 161 /* MethodDeclaration */:
20639                         // Method declarations are not necessarily reusable.  An object-literal
20640                         // may have a method calls "constructor(...)" and we must reparse that
20641                         // into an actual .ConstructorDeclaration.
20642                         var methodDeclaration = node;
20643                         var nameIsConstructor = methodDeclaration.name.kind === 75 /* Identifier */ &&
20644                             methodDeclaration.name.originalKeywordKind === 129 /* ConstructorKeyword */;
20645                         return !nameIsConstructor;
20646                 }
20647             }
20648             return false;
20649         }
20650         function isReusableSwitchClause(node) {
20651             if (node) {
20652                 switch (node.kind) {
20653                     case 277 /* CaseClause */:
20654                     case 278 /* DefaultClause */:
20655                         return true;
20656                 }
20657             }
20658             return false;
20659         }
20660         function isReusableStatement(node) {
20661             if (node) {
20662                 switch (node.kind) {
20663                     case 244 /* FunctionDeclaration */:
20664                     case 225 /* VariableStatement */:
20665                     case 223 /* Block */:
20666                     case 227 /* IfStatement */:
20667                     case 226 /* ExpressionStatement */:
20668                     case 239 /* ThrowStatement */:
20669                     case 235 /* ReturnStatement */:
20670                     case 237 /* SwitchStatement */:
20671                     case 234 /* BreakStatement */:
20672                     case 233 /* ContinueStatement */:
20673                     case 231 /* ForInStatement */:
20674                     case 232 /* ForOfStatement */:
20675                     case 230 /* ForStatement */:
20676                     case 229 /* WhileStatement */:
20677                     case 236 /* WithStatement */:
20678                     case 224 /* EmptyStatement */:
20679                     case 240 /* TryStatement */:
20680                     case 238 /* LabeledStatement */:
20681                     case 228 /* DoStatement */:
20682                     case 241 /* DebuggerStatement */:
20683                     case 254 /* ImportDeclaration */:
20684                     case 253 /* ImportEqualsDeclaration */:
20685                     case 260 /* ExportDeclaration */:
20686                     case 259 /* ExportAssignment */:
20687                     case 249 /* ModuleDeclaration */:
20688                     case 245 /* ClassDeclaration */:
20689                     case 246 /* InterfaceDeclaration */:
20690                     case 248 /* EnumDeclaration */:
20691                     case 247 /* TypeAliasDeclaration */:
20692                         return true;
20693                 }
20694             }
20695             return false;
20696         }
20697         function isReusableEnumMember(node) {
20698             return node.kind === 284 /* EnumMember */;
20699         }
20700         function isReusableTypeMember(node) {
20701             if (node) {
20702                 switch (node.kind) {
20703                     case 166 /* ConstructSignature */:
20704                     case 160 /* MethodSignature */:
20705                     case 167 /* IndexSignature */:
20706                     case 158 /* PropertySignature */:
20707                     case 165 /* CallSignature */:
20708                         return true;
20709                 }
20710             }
20711             return false;
20712         }
20713         function isReusableVariableDeclaration(node) {
20714             if (node.kind !== 242 /* VariableDeclaration */) {
20715                 return false;
20716             }
20717             // Very subtle incremental parsing bug.  Consider the following code:
20718             //
20719             //      let v = new List < A, B
20720             //
20721             // This is actually legal code.  It's a list of variable declarators "v = new List<A"
20722             // on one side and "B" on the other. If you then change that to:
20723             //
20724             //      let v = new List < A, B >()
20725             //
20726             // then we have a problem.  "v = new List<A" doesn't intersect the change range, so we
20727             // start reparsing at "B" and we completely fail to handle this properly.
20728             //
20729             // In order to prevent this, we do not allow a variable declarator to be reused if it
20730             // has an initializer.
20731             var variableDeclarator = node;
20732             return variableDeclarator.initializer === undefined;
20733         }
20734         function isReusableParameter(node) {
20735             if (node.kind !== 156 /* Parameter */) {
20736                 return false;
20737             }
20738             // See the comment in isReusableVariableDeclaration for why we do this.
20739             var parameter = node;
20740             return parameter.initializer === undefined;
20741         }
20742         // Returns true if we should abort parsing.
20743         function abortParsingListOrMoveToNextToken(kind) {
20744             parseErrorAtCurrentToken(parsingContextErrors(kind));
20745             if (isInSomeParsingContext()) {
20746                 return true;
20747             }
20748             nextToken();
20749             return false;
20750         }
20751         function parsingContextErrors(context) {
20752             switch (context) {
20753                 case 0 /* SourceElements */: return ts.Diagnostics.Declaration_or_statement_expected;
20754                 case 1 /* BlockStatements */: return ts.Diagnostics.Declaration_or_statement_expected;
20755                 case 2 /* SwitchClauses */: return ts.Diagnostics.case_or_default_expected;
20756                 case 3 /* SwitchClauseStatements */: return ts.Diagnostics.Statement_expected;
20757                 case 18 /* RestProperties */: // fallthrough
20758                 case 4 /* TypeMembers */: return ts.Diagnostics.Property_or_signature_expected;
20759                 case 5 /* ClassMembers */: return ts.Diagnostics.Unexpected_token_A_constructor_method_accessor_or_property_was_expected;
20760                 case 6 /* EnumMembers */: return ts.Diagnostics.Enum_member_expected;
20761                 case 7 /* HeritageClauseElement */: return ts.Diagnostics.Expression_expected;
20762                 case 8 /* VariableDeclarations */: return ts.Diagnostics.Variable_declaration_expected;
20763                 case 9 /* ObjectBindingElements */: return ts.Diagnostics.Property_destructuring_pattern_expected;
20764                 case 10 /* ArrayBindingElements */: return ts.Diagnostics.Array_element_destructuring_pattern_expected;
20765                 case 11 /* ArgumentExpressions */: return ts.Diagnostics.Argument_expression_expected;
20766                 case 12 /* ObjectLiteralMembers */: return ts.Diagnostics.Property_assignment_expected;
20767                 case 15 /* ArrayLiteralMembers */: return ts.Diagnostics.Expression_or_comma_expected;
20768                 case 17 /* JSDocParameters */: return ts.Diagnostics.Parameter_declaration_expected;
20769                 case 16 /* Parameters */: return ts.Diagnostics.Parameter_declaration_expected;
20770                 case 19 /* TypeParameters */: return ts.Diagnostics.Type_parameter_declaration_expected;
20771                 case 20 /* TypeArguments */: return ts.Diagnostics.Type_argument_expected;
20772                 case 21 /* TupleElementTypes */: return ts.Diagnostics.Type_expected;
20773                 case 22 /* HeritageClauses */: return ts.Diagnostics.Unexpected_token_expected;
20774                 case 23 /* ImportOrExportSpecifiers */: return ts.Diagnostics.Identifier_expected;
20775                 case 13 /* JsxAttributes */: return ts.Diagnostics.Identifier_expected;
20776                 case 14 /* JsxChildren */: return ts.Diagnostics.Identifier_expected;
20777                 default: return undefined; // TODO: GH#18217 `default: Debug.assertNever(context);`
20778             }
20779         }
20780         // Parses a comma-delimited list of elements
20781         function parseDelimitedList(kind, parseElement, considerSemicolonAsDelimiter) {
20782             var saveParsingContext = parsingContext;
20783             parsingContext |= 1 << kind;
20784             var list = [];
20785             var listPos = getNodePos();
20786             var commaStart = -1; // Meaning the previous token was not a comma
20787             while (true) {
20788                 if (isListElement(kind, /*inErrorRecovery*/ false)) {
20789                     var startPos = scanner.getStartPos();
20790                     list.push(parseListElement(kind, parseElement));
20791                     commaStart = scanner.getTokenPos();
20792                     if (parseOptional(27 /* CommaToken */)) {
20793                         // No need to check for a zero length node since we know we parsed a comma
20794                         continue;
20795                     }
20796                     commaStart = -1; // Back to the state where the last token was not a comma
20797                     if (isListTerminator(kind)) {
20798                         break;
20799                     }
20800                     // We didn't get a comma, and the list wasn't terminated, explicitly parse
20801                     // out a comma so we give a good error message.
20802                     parseExpected(27 /* CommaToken */, getExpectedCommaDiagnostic(kind));
20803                     // If the token was a semicolon, and the caller allows that, then skip it and
20804                     // continue.  This ensures we get back on track and don't result in tons of
20805                     // parse errors.  For example, this can happen when people do things like use
20806                     // a semicolon to delimit object literal members.   Note: we'll have already
20807                     // reported an error when we called parseExpected above.
20808                     if (considerSemicolonAsDelimiter && token() === 26 /* SemicolonToken */ && !scanner.hasPrecedingLineBreak()) {
20809                         nextToken();
20810                     }
20811                     if (startPos === scanner.getStartPos()) {
20812                         // What we're parsing isn't actually remotely recognizable as a element and we've consumed no tokens whatsoever
20813                         // Consume a token to advance the parser in some way and avoid an infinite loop
20814                         // This can happen when we're speculatively parsing parenthesized expressions which we think may be arrow functions,
20815                         // or when a modifier keyword which is disallowed as a parameter name (ie, `static` in strict mode) is supplied
20816                         nextToken();
20817                     }
20818                     continue;
20819                 }
20820                 if (isListTerminator(kind)) {
20821                     break;
20822                 }
20823                 if (abortParsingListOrMoveToNextToken(kind)) {
20824                     break;
20825                 }
20826             }
20827             parsingContext = saveParsingContext;
20828             var result = createNodeArray(list, listPos);
20829             // Recording the trailing comma is deliberately done after the previous
20830             // loop, and not just if we see a list terminator. This is because the list
20831             // may have ended incorrectly, but it is still important to know if there
20832             // was a trailing comma.
20833             // Check if the last token was a comma.
20834             if (commaStart >= 0) {
20835                 // Always preserve a trailing comma by marking it on the NodeArray
20836                 result.hasTrailingComma = true;
20837             }
20838             return result;
20839         }
20840         function getExpectedCommaDiagnostic(kind) {
20841             return kind === 6 /* EnumMembers */ ? ts.Diagnostics.An_enum_member_name_must_be_followed_by_a_or : undefined;
20842         }
20843         function createMissingList() {
20844             var list = createNodeArray([], getNodePos());
20845             list.isMissingList = true;
20846             return list;
20847         }
20848         function isMissingList(arr) {
20849             return !!arr.isMissingList;
20850         }
20851         function parseBracketedList(kind, parseElement, open, close) {
20852             if (parseExpected(open)) {
20853                 var result = parseDelimitedList(kind, parseElement);
20854                 parseExpected(close);
20855                 return result;
20856             }
20857             return createMissingList();
20858         }
20859         function parseEntityName(allowReservedWords, diagnosticMessage) {
20860             var entity = allowReservedWords ? parseIdentifierName(diagnosticMessage) : parseIdentifier(diagnosticMessage);
20861             var dotPos = scanner.getStartPos();
20862             while (parseOptional(24 /* DotToken */)) {
20863                 if (token() === 29 /* LessThanToken */) {
20864                     // the entity is part of a JSDoc-style generic, so record the trailing dot for later error reporting
20865                     entity.jsdocDotPos = dotPos;
20866                     break;
20867                 }
20868                 dotPos = scanner.getStartPos();
20869                 entity = createQualifiedName(entity, parseRightSideOfDot(allowReservedWords, /* allowPrivateIdentifiers */ false));
20870             }
20871             return entity;
20872         }
20873         function createQualifiedName(entity, name) {
20874             var node = createNode(153 /* QualifiedName */, entity.pos);
20875             node.left = entity;
20876             node.right = name;
20877             return finishNode(node);
20878         }
20879         function parseRightSideOfDot(allowIdentifierNames, allowPrivateIdentifiers) {
20880             // Technically a keyword is valid here as all identifiers and keywords are identifier names.
20881             // However, often we'll encounter this in error situations when the identifier or keyword
20882             // is actually starting another valid construct.
20883             //
20884             // So, we check for the following specific case:
20885             //
20886             //      name.
20887             //      identifierOrKeyword identifierNameOrKeyword
20888             //
20889             // Note: the newlines are important here.  For example, if that above code
20890             // were rewritten into:
20891             //
20892             //      name.identifierOrKeyword
20893             //      identifierNameOrKeyword
20894             //
20895             // Then we would consider it valid.  That's because ASI would take effect and
20896             // the code would be implicitly: "name.identifierOrKeyword; identifierNameOrKeyword".
20897             // In the first case though, ASI will not take effect because there is not a
20898             // line terminator after the identifier or keyword.
20899             if (scanner.hasPrecedingLineBreak() && ts.tokenIsIdentifierOrKeyword(token())) {
20900                 var matchesPattern = lookAhead(nextTokenIsIdentifierOrKeywordOnSameLine);
20901                 if (matchesPattern) {
20902                     // Report that we need an identifier.  However, report it right after the dot,
20903                     // and not on the next token.  This is because the next token might actually
20904                     // be an identifier and the error would be quite confusing.
20905                     return createMissingNode(75 /* Identifier */, /*reportAtCurrentPosition*/ true, ts.Diagnostics.Identifier_expected);
20906                 }
20907             }
20908             if (token() === 76 /* PrivateIdentifier */) {
20909                 var node = parsePrivateIdentifier();
20910                 return allowPrivateIdentifiers ? node : createMissingNode(75 /* Identifier */, /*reportAtCurrentPosition*/ true, ts.Diagnostics.Identifier_expected);
20911             }
20912             return allowIdentifierNames ? parseIdentifierName() : parseIdentifier();
20913         }
20914         function parseTemplateExpression(isTaggedTemplate) {
20915             var template = createNode(211 /* TemplateExpression */);
20916             template.head = parseTemplateHead(isTaggedTemplate);
20917             ts.Debug.assert(template.head.kind === 15 /* TemplateHead */, "Template head has wrong token kind");
20918             var list = [];
20919             var listPos = getNodePos();
20920             do {
20921                 list.push(parseTemplateSpan(isTaggedTemplate));
20922             } while (ts.last(list).literal.kind === 16 /* TemplateMiddle */);
20923             template.templateSpans = createNodeArray(list, listPos);
20924             return finishNode(template);
20925         }
20926         function parseTemplateSpan(isTaggedTemplate) {
20927             var span = createNode(221 /* TemplateSpan */);
20928             span.expression = allowInAnd(parseExpression);
20929             var literal;
20930             if (token() === 19 /* CloseBraceToken */) {
20931                 reScanTemplateToken(isTaggedTemplate);
20932                 literal = parseTemplateMiddleOrTemplateTail();
20933             }
20934             else {
20935                 literal = parseExpectedToken(17 /* TemplateTail */, ts.Diagnostics._0_expected, ts.tokenToString(19 /* CloseBraceToken */));
20936             }
20937             span.literal = literal;
20938             return finishNode(span);
20939         }
20940         function parseLiteralNode() {
20941             return parseLiteralLikeNode(token());
20942         }
20943         function parseTemplateHead(isTaggedTemplate) {
20944             if (isTaggedTemplate) {
20945                 reScanTemplateHeadOrNoSubstitutionTemplate();
20946             }
20947             var fragment = parseLiteralLikeNode(token());
20948             ts.Debug.assert(fragment.kind === 15 /* TemplateHead */, "Template head has wrong token kind");
20949             return fragment;
20950         }
20951         function parseTemplateMiddleOrTemplateTail() {
20952             var fragment = parseLiteralLikeNode(token());
20953             ts.Debug.assert(fragment.kind === 16 /* TemplateMiddle */ || fragment.kind === 17 /* TemplateTail */, "Template fragment has wrong token kind");
20954             return fragment;
20955         }
20956         function parseLiteralLikeNode(kind) {
20957             var node = createNode(kind);
20958             node.text = scanner.getTokenValue();
20959             switch (kind) {
20960                 case 14 /* NoSubstitutionTemplateLiteral */:
20961                 case 15 /* TemplateHead */:
20962                 case 16 /* TemplateMiddle */:
20963                 case 17 /* TemplateTail */:
20964                     var isLast = kind === 14 /* NoSubstitutionTemplateLiteral */ || kind === 17 /* TemplateTail */;
20965                     var tokenText = scanner.getTokenText();
20966                     node.rawText = tokenText.substring(1, tokenText.length - (scanner.isUnterminated() ? 0 : isLast ? 1 : 2));
20967                     break;
20968             }
20969             if (scanner.hasExtendedUnicodeEscape()) {
20970                 node.hasExtendedUnicodeEscape = true;
20971             }
20972             if (scanner.isUnterminated()) {
20973                 node.isUnterminated = true;
20974             }
20975             // Octal literals are not allowed in strict mode or ES5
20976             // Note that theoretically the following condition would hold true literals like 009,
20977             // which is not octal.But because of how the scanner separates the tokens, we would
20978             // never get a token like this. Instead, we would get 00 and 9 as two separate tokens.
20979             // We also do not need to check for negatives because any prefix operator would be part of a
20980             // parent unary expression.
20981             if (node.kind === 8 /* NumericLiteral */) {
20982                 node.numericLiteralFlags = scanner.getTokenFlags() & 1008 /* NumericLiteralFlags */;
20983             }
20984             if (ts.isTemplateLiteralKind(node.kind)) {
20985                 node.templateFlags = scanner.getTokenFlags() & 2048 /* ContainsInvalidEscape */;
20986             }
20987             nextToken();
20988             finishNode(node);
20989             return node;
20990         }
20991         // TYPES
20992         function parseTypeReference() {
20993             var node = createNode(169 /* TypeReference */);
20994             node.typeName = parseEntityName(/*allowReservedWords*/ true, ts.Diagnostics.Type_expected);
20995             if (!scanner.hasPrecedingLineBreak() && reScanLessThanToken() === 29 /* LessThanToken */) {
20996                 node.typeArguments = parseBracketedList(20 /* TypeArguments */, parseType, 29 /* LessThanToken */, 31 /* GreaterThanToken */);
20997             }
20998             return finishNode(node);
20999         }
21000         // If true, we should abort parsing an error function.
21001         function typeHasArrowFunctionBlockingParseError(node) {
21002             switch (node.kind) {
21003                 case 169 /* TypeReference */:
21004                     return ts.nodeIsMissing(node.typeName);
21005                 case 170 /* FunctionType */:
21006                 case 171 /* ConstructorType */: {
21007                     var _a = node, parameters = _a.parameters, type = _a.type;
21008                     return isMissingList(parameters) || typeHasArrowFunctionBlockingParseError(type);
21009                 }
21010                 case 182 /* ParenthesizedType */:
21011                     return typeHasArrowFunctionBlockingParseError(node.type);
21012                 default:
21013                     return false;
21014             }
21015         }
21016         function parseThisTypePredicate(lhs) {
21017             nextToken();
21018             var node = createNode(168 /* TypePredicate */, lhs.pos);
21019             node.parameterName = lhs;
21020             node.type = parseType();
21021             return finishNode(node);
21022         }
21023         function parseThisTypeNode() {
21024             var node = createNode(183 /* ThisType */);
21025             nextToken();
21026             return finishNode(node);
21027         }
21028         function parseJSDocAllType(postFixEquals) {
21029             var result = createNode(295 /* JSDocAllType */);
21030             if (postFixEquals) {
21031                 return createPostfixType(299 /* JSDocOptionalType */, result);
21032             }
21033             else {
21034                 nextToken();
21035             }
21036             return finishNode(result);
21037         }
21038         function parseJSDocNonNullableType() {
21039             var result = createNode(298 /* JSDocNonNullableType */);
21040             nextToken();
21041             result.type = parseNonArrayType();
21042             return finishNode(result);
21043         }
21044         function parseJSDocUnknownOrNullableType() {
21045             var pos = scanner.getStartPos();
21046             // skip the ?
21047             nextToken();
21048             // Need to lookahead to decide if this is a nullable or unknown type.
21049             // Here are cases where we'll pick the unknown type:
21050             //
21051             //      Foo(?,
21052             //      { a: ? }
21053             //      Foo(?)
21054             //      Foo<?>
21055             //      Foo(?=
21056             //      (?|
21057             if (token() === 27 /* CommaToken */ ||
21058                 token() === 19 /* CloseBraceToken */ ||
21059                 token() === 21 /* CloseParenToken */ ||
21060                 token() === 31 /* GreaterThanToken */ ||
21061                 token() === 62 /* EqualsToken */ ||
21062                 token() === 51 /* BarToken */) {
21063                 var result = createNode(296 /* JSDocUnknownType */, pos);
21064                 return finishNode(result);
21065             }
21066             else {
21067                 var result = createNode(297 /* JSDocNullableType */, pos);
21068                 result.type = parseType();
21069                 return finishNode(result);
21070             }
21071         }
21072         function parseJSDocFunctionType() {
21073             if (lookAhead(nextTokenIsOpenParen)) {
21074                 var result = createNodeWithJSDoc(300 /* JSDocFunctionType */);
21075                 nextToken();
21076                 fillSignature(58 /* ColonToken */, 4 /* Type */ | 32 /* JSDoc */, result);
21077                 return finishNode(result);
21078             }
21079             var node = createNode(169 /* TypeReference */);
21080             node.typeName = parseIdentifierName();
21081             return finishNode(node);
21082         }
21083         function parseJSDocParameter() {
21084             var parameter = createNode(156 /* Parameter */);
21085             if (token() === 104 /* ThisKeyword */ || token() === 99 /* NewKeyword */) {
21086                 parameter.name = parseIdentifierName();
21087                 parseExpected(58 /* ColonToken */);
21088             }
21089             parameter.type = parseJSDocType();
21090             return finishNode(parameter);
21091         }
21092         function parseJSDocType() {
21093             scanner.setInJSDocType(true);
21094             var moduleSpecifier = parseOptionalToken(135 /* ModuleKeyword */);
21095             if (moduleSpecifier) {
21096                 var moduleTag = createNode(302 /* JSDocNamepathType */, moduleSpecifier.pos);
21097                 terminate: while (true) {
21098                     switch (token()) {
21099                         case 19 /* CloseBraceToken */:
21100                         case 1 /* EndOfFileToken */:
21101                         case 27 /* CommaToken */:
21102                         case 5 /* WhitespaceTrivia */:
21103                             break terminate;
21104                         default:
21105                             nextTokenJSDoc();
21106                     }
21107                 }
21108                 scanner.setInJSDocType(false);
21109                 return finishNode(moduleTag);
21110             }
21111             var dotdotdot = parseOptionalToken(25 /* DotDotDotToken */);
21112             var type = parseTypeOrTypePredicate();
21113             scanner.setInJSDocType(false);
21114             if (dotdotdot) {
21115                 var variadic = createNode(301 /* JSDocVariadicType */, dotdotdot.pos);
21116                 variadic.type = type;
21117                 type = finishNode(variadic);
21118             }
21119             if (token() === 62 /* EqualsToken */) {
21120                 return createPostfixType(299 /* JSDocOptionalType */, type);
21121             }
21122             return type;
21123         }
21124         function parseTypeQuery() {
21125             var node = createNode(172 /* TypeQuery */);
21126             parseExpected(108 /* TypeOfKeyword */);
21127             node.exprName = parseEntityName(/*allowReservedWords*/ true);
21128             return finishNode(node);
21129         }
21130         function parseTypeParameter() {
21131             var node = createNode(155 /* TypeParameter */);
21132             node.name = parseIdentifier();
21133             if (parseOptional(90 /* ExtendsKeyword */)) {
21134                 // It's not uncommon for people to write improper constraints to a generic.  If the
21135                 // user writes a constraint that is an expression and not an actual type, then parse
21136                 // it out as an expression (so we can recover well), but report that a type is needed
21137                 // instead.
21138                 if (isStartOfType() || !isStartOfExpression()) {
21139                     node.constraint = parseType();
21140                 }
21141                 else {
21142                     // It was not a type, and it looked like an expression.  Parse out an expression
21143                     // here so we recover well.  Note: it is important that we call parseUnaryExpression
21144                     // and not parseExpression here.  If the user has:
21145                     //
21146                     //      <T extends "">
21147                     //
21148                     // We do *not* want to consume the `>` as we're consuming the expression for "".
21149                     node.expression = parseUnaryExpressionOrHigher();
21150                 }
21151             }
21152             if (parseOptional(62 /* EqualsToken */)) {
21153                 node.default = parseType();
21154             }
21155             return finishNode(node);
21156         }
21157         function parseTypeParameters() {
21158             if (token() === 29 /* LessThanToken */) {
21159                 return parseBracketedList(19 /* TypeParameters */, parseTypeParameter, 29 /* LessThanToken */, 31 /* GreaterThanToken */);
21160             }
21161         }
21162         function parseParameterType() {
21163             if (parseOptional(58 /* ColonToken */)) {
21164                 return parseType();
21165             }
21166             return undefined;
21167         }
21168         function isStartOfParameter(isJSDocParameter) {
21169             return token() === 25 /* DotDotDotToken */ ||
21170                 isIdentifierOrPrivateIdentifierOrPattern() ||
21171                 ts.isModifierKind(token()) ||
21172                 token() === 59 /* AtToken */ ||
21173                 isStartOfType(/*inStartOfParameter*/ !isJSDocParameter);
21174         }
21175         function parseParameter() {
21176             var node = createNodeWithJSDoc(156 /* Parameter */);
21177             if (token() === 104 /* ThisKeyword */) {
21178                 node.name = createIdentifier(/*isIdentifier*/ true);
21179                 node.type = parseParameterType();
21180                 return finishNode(node);
21181             }
21182             node.decorators = parseDecorators();
21183             node.modifiers = parseModifiers();
21184             node.dotDotDotToken = parseOptionalToken(25 /* DotDotDotToken */);
21185             // FormalParameter [Yield,Await]:
21186             //      BindingElement[?Yield,?Await]
21187             node.name = parseIdentifierOrPattern(ts.Diagnostics.Private_identifiers_cannot_be_used_as_parameters);
21188             if (ts.getFullWidth(node.name) === 0 && !node.modifiers && ts.isModifierKind(token())) {
21189                 // in cases like
21190                 // 'use strict'
21191                 // function foo(static)
21192                 // isParameter('static') === true, because of isModifier('static')
21193                 // however 'static' is not a legal identifier in a strict mode.
21194                 // so result of this function will be ParameterDeclaration (flags = 0, name = missing, type = undefined, initializer = undefined)
21195                 // and current token will not change => parsing of the enclosing parameter list will last till the end of time (or OOM)
21196                 // to avoid this we'll advance cursor to the next token.
21197                 nextToken();
21198             }
21199             node.questionToken = parseOptionalToken(57 /* QuestionToken */);
21200             node.type = parseParameterType();
21201             node.initializer = parseInitializer();
21202             return finishNode(node);
21203         }
21204         /**
21205          * Note: If returnToken is EqualsGreaterThanToken, `signature.type` will always be defined.
21206          * @returns If return type parsing succeeds
21207          */
21208         function fillSignature(returnToken, flags, signature) {
21209             if (!(flags & 32 /* JSDoc */)) {
21210                 signature.typeParameters = parseTypeParameters();
21211             }
21212             var parametersParsedSuccessfully = parseParameterList(signature, flags);
21213             if (shouldParseReturnType(returnToken, !!(flags & 4 /* Type */))) {
21214                 signature.type = parseTypeOrTypePredicate();
21215                 if (typeHasArrowFunctionBlockingParseError(signature.type))
21216                     return false;
21217             }
21218             return parametersParsedSuccessfully;
21219         }
21220         function shouldParseReturnType(returnToken, isType) {
21221             if (returnToken === 38 /* EqualsGreaterThanToken */) {
21222                 parseExpected(returnToken);
21223                 return true;
21224             }
21225             else if (parseOptional(58 /* ColonToken */)) {
21226                 return true;
21227             }
21228             else if (isType && token() === 38 /* EqualsGreaterThanToken */) {
21229                 // This is easy to get backward, especially in type contexts, so parse the type anyway
21230                 parseErrorAtCurrentToken(ts.Diagnostics._0_expected, ts.tokenToString(58 /* ColonToken */));
21231                 nextToken();
21232                 return true;
21233             }
21234             return false;
21235         }
21236         // Returns true on success.
21237         function parseParameterList(signature, flags) {
21238             // FormalParameters [Yield,Await]: (modified)
21239             //      [empty]
21240             //      FormalParameterList[?Yield,Await]
21241             //
21242             // FormalParameter[Yield,Await]: (modified)
21243             //      BindingElement[?Yield,Await]
21244             //
21245             // BindingElement [Yield,Await]: (modified)
21246             //      SingleNameBinding[?Yield,?Await]
21247             //      BindingPattern[?Yield,?Await]Initializer [In, ?Yield,?Await] opt
21248             //
21249             // SingleNameBinding [Yield,Await]:
21250             //      BindingIdentifier[?Yield,?Await]Initializer [In, ?Yield,?Await] opt
21251             if (!parseExpected(20 /* OpenParenToken */)) {
21252                 signature.parameters = createMissingList();
21253                 return false;
21254             }
21255             var savedYieldContext = inYieldContext();
21256             var savedAwaitContext = inAwaitContext();
21257             setYieldContext(!!(flags & 1 /* Yield */));
21258             setAwaitContext(!!(flags & 2 /* Await */));
21259             signature.parameters = flags & 32 /* JSDoc */ ?
21260                 parseDelimitedList(17 /* JSDocParameters */, parseJSDocParameter) :
21261                 parseDelimitedList(16 /* Parameters */, parseParameter);
21262             setYieldContext(savedYieldContext);
21263             setAwaitContext(savedAwaitContext);
21264             return parseExpected(21 /* CloseParenToken */);
21265         }
21266         function parseTypeMemberSemicolon() {
21267             // We allow type members to be separated by commas or (possibly ASI) semicolons.
21268             // First check if it was a comma.  If so, we're done with the member.
21269             if (parseOptional(27 /* CommaToken */)) {
21270                 return;
21271             }
21272             // Didn't have a comma.  We must have a (possible ASI) semicolon.
21273             parseSemicolon();
21274         }
21275         function parseSignatureMember(kind) {
21276             var node = createNodeWithJSDoc(kind);
21277             if (kind === 166 /* ConstructSignature */) {
21278                 parseExpected(99 /* NewKeyword */);
21279             }
21280             fillSignature(58 /* ColonToken */, 4 /* Type */, node);
21281             parseTypeMemberSemicolon();
21282             return finishNode(node);
21283         }
21284         function isIndexSignature() {
21285             return token() === 22 /* OpenBracketToken */ && lookAhead(isUnambiguouslyIndexSignature);
21286         }
21287         function isUnambiguouslyIndexSignature() {
21288             // The only allowed sequence is:
21289             //
21290             //   [id:
21291             //
21292             // However, for error recovery, we also check the following cases:
21293             //
21294             //   [...
21295             //   [id,
21296             //   [id?,
21297             //   [id?:
21298             //   [id?]
21299             //   [public id
21300             //   [private id
21301             //   [protected id
21302             //   []
21303             //
21304             nextToken();
21305             if (token() === 25 /* DotDotDotToken */ || token() === 23 /* CloseBracketToken */) {
21306                 return true;
21307             }
21308             if (ts.isModifierKind(token())) {
21309                 nextToken();
21310                 if (isIdentifier()) {
21311                     return true;
21312                 }
21313             }
21314             else if (!isIdentifier()) {
21315                 return false;
21316             }
21317             else {
21318                 // Skip the identifier
21319                 nextToken();
21320             }
21321             // A colon signifies a well formed indexer
21322             // A comma should be a badly formed indexer because comma expressions are not allowed
21323             // in computed properties.
21324             if (token() === 58 /* ColonToken */ || token() === 27 /* CommaToken */) {
21325                 return true;
21326             }
21327             // Question mark could be an indexer with an optional property,
21328             // or it could be a conditional expression in a computed property.
21329             if (token() !== 57 /* QuestionToken */) {
21330                 return false;
21331             }
21332             // If any of the following tokens are after the question mark, it cannot
21333             // be a conditional expression, so treat it as an indexer.
21334             nextToken();
21335             return token() === 58 /* ColonToken */ || token() === 27 /* CommaToken */ || token() === 23 /* CloseBracketToken */;
21336         }
21337         function parseIndexSignatureDeclaration(node) {
21338             node.kind = 167 /* IndexSignature */;
21339             node.parameters = parseBracketedList(16 /* Parameters */, parseParameter, 22 /* OpenBracketToken */, 23 /* CloseBracketToken */);
21340             node.type = parseTypeAnnotation();
21341             parseTypeMemberSemicolon();
21342             return finishNode(node);
21343         }
21344         function parsePropertyOrMethodSignature(node) {
21345             node.name = parsePropertyName();
21346             node.questionToken = parseOptionalToken(57 /* QuestionToken */);
21347             if (token() === 20 /* OpenParenToken */ || token() === 29 /* LessThanToken */) {
21348                 node.kind = 160 /* MethodSignature */;
21349                 // Method signatures don't exist in expression contexts.  So they have neither
21350                 // [Yield] nor [Await]
21351                 fillSignature(58 /* ColonToken */, 4 /* Type */, node);
21352             }
21353             else {
21354                 node.kind = 158 /* PropertySignature */;
21355                 node.type = parseTypeAnnotation();
21356                 if (token() === 62 /* EqualsToken */) {
21357                     // Although type literal properties cannot not have initializers, we attempt
21358                     // to parse an initializer so we can report in the checker that an interface
21359                     // property or type literal property cannot have an initializer.
21360                     node.initializer = parseInitializer();
21361                 }
21362             }
21363             parseTypeMemberSemicolon();
21364             return finishNode(node);
21365         }
21366         function isTypeMemberStart() {
21367             // Return true if we have the start of a signature member
21368             if (token() === 20 /* OpenParenToken */ || token() === 29 /* LessThanToken */) {
21369                 return true;
21370             }
21371             var idToken = false;
21372             // Eat up all modifiers, but hold on to the last one in case it is actually an identifier
21373             while (ts.isModifierKind(token())) {
21374                 idToken = true;
21375                 nextToken();
21376             }
21377             // Index signatures and computed property names are type members
21378             if (token() === 22 /* OpenBracketToken */) {
21379                 return true;
21380             }
21381             // Try to get the first property-like token following all modifiers
21382             if (isLiteralPropertyName()) {
21383                 idToken = true;
21384                 nextToken();
21385             }
21386             // If we were able to get any potential identifier, check that it is
21387             // the start of a member declaration
21388             if (idToken) {
21389                 return token() === 20 /* OpenParenToken */ ||
21390                     token() === 29 /* LessThanToken */ ||
21391                     token() === 57 /* QuestionToken */ ||
21392                     token() === 58 /* ColonToken */ ||
21393                     token() === 27 /* CommaToken */ ||
21394                     canParseSemicolon();
21395             }
21396             return false;
21397         }
21398         function parseTypeMember() {
21399             if (token() === 20 /* OpenParenToken */ || token() === 29 /* LessThanToken */) {
21400                 return parseSignatureMember(165 /* CallSignature */);
21401             }
21402             if (token() === 99 /* NewKeyword */ && lookAhead(nextTokenIsOpenParenOrLessThan)) {
21403                 return parseSignatureMember(166 /* ConstructSignature */);
21404             }
21405             var node = createNodeWithJSDoc(0 /* Unknown */);
21406             node.modifiers = parseModifiers();
21407             if (isIndexSignature()) {
21408                 return parseIndexSignatureDeclaration(node);
21409             }
21410             return parsePropertyOrMethodSignature(node);
21411         }
21412         function nextTokenIsOpenParenOrLessThan() {
21413             nextToken();
21414             return token() === 20 /* OpenParenToken */ || token() === 29 /* LessThanToken */;
21415         }
21416         function nextTokenIsDot() {
21417             return nextToken() === 24 /* DotToken */;
21418         }
21419         function nextTokenIsOpenParenOrLessThanOrDot() {
21420             switch (nextToken()) {
21421                 case 20 /* OpenParenToken */:
21422                 case 29 /* LessThanToken */:
21423                 case 24 /* DotToken */:
21424                     return true;
21425             }
21426             return false;
21427         }
21428         function parseTypeLiteral() {
21429             var node = createNode(173 /* TypeLiteral */);
21430             node.members = parseObjectTypeMembers();
21431             return finishNode(node);
21432         }
21433         function parseObjectTypeMembers() {
21434             var members;
21435             if (parseExpected(18 /* OpenBraceToken */)) {
21436                 members = parseList(4 /* TypeMembers */, parseTypeMember);
21437                 parseExpected(19 /* CloseBraceToken */);
21438             }
21439             else {
21440                 members = createMissingList();
21441             }
21442             return members;
21443         }
21444         function isStartOfMappedType() {
21445             nextToken();
21446             if (token() === 39 /* PlusToken */ || token() === 40 /* MinusToken */) {
21447                 return nextToken() === 138 /* ReadonlyKeyword */;
21448             }
21449             if (token() === 138 /* ReadonlyKeyword */) {
21450                 nextToken();
21451             }
21452             return token() === 22 /* OpenBracketToken */ && nextTokenIsIdentifier() && nextToken() === 97 /* InKeyword */;
21453         }
21454         function parseMappedTypeParameter() {
21455             var node = createNode(155 /* TypeParameter */);
21456             node.name = parseIdentifier();
21457             parseExpected(97 /* InKeyword */);
21458             node.constraint = parseType();
21459             return finishNode(node);
21460         }
21461         function parseMappedType() {
21462             var node = createNode(186 /* MappedType */);
21463             parseExpected(18 /* OpenBraceToken */);
21464             if (token() === 138 /* ReadonlyKeyword */ || token() === 39 /* PlusToken */ || token() === 40 /* MinusToken */) {
21465                 node.readonlyToken = parseTokenNode();
21466                 if (node.readonlyToken.kind !== 138 /* ReadonlyKeyword */) {
21467                     parseExpectedToken(138 /* ReadonlyKeyword */);
21468                 }
21469             }
21470             parseExpected(22 /* OpenBracketToken */);
21471             node.typeParameter = parseMappedTypeParameter();
21472             parseExpected(23 /* CloseBracketToken */);
21473             if (token() === 57 /* QuestionToken */ || token() === 39 /* PlusToken */ || token() === 40 /* MinusToken */) {
21474                 node.questionToken = parseTokenNode();
21475                 if (node.questionToken.kind !== 57 /* QuestionToken */) {
21476                     parseExpectedToken(57 /* QuestionToken */);
21477                 }
21478             }
21479             node.type = parseTypeAnnotation();
21480             parseSemicolon();
21481             parseExpected(19 /* CloseBraceToken */);
21482             return finishNode(node);
21483         }
21484         function parseTupleElementType() {
21485             var pos = getNodePos();
21486             if (parseOptional(25 /* DotDotDotToken */)) {
21487                 var node = createNode(177 /* RestType */, pos);
21488                 node.type = parseType();
21489                 return finishNode(node);
21490             }
21491             var type = parseType();
21492             if (!(contextFlags & 4194304 /* JSDoc */) && type.kind === 297 /* JSDocNullableType */ && type.pos === type.type.pos) {
21493                 type.kind = 176 /* OptionalType */;
21494             }
21495             return type;
21496         }
21497         function parseTupleType() {
21498             var node = createNode(175 /* TupleType */);
21499             node.elementTypes = parseBracketedList(21 /* TupleElementTypes */, parseTupleElementType, 22 /* OpenBracketToken */, 23 /* CloseBracketToken */);
21500             return finishNode(node);
21501         }
21502         function parseParenthesizedType() {
21503             var node = createNode(182 /* ParenthesizedType */);
21504             parseExpected(20 /* OpenParenToken */);
21505             node.type = parseType();
21506             parseExpected(21 /* CloseParenToken */);
21507             return finishNode(node);
21508         }
21509         function parseFunctionOrConstructorType() {
21510             var pos = getNodePos();
21511             var kind = parseOptional(99 /* NewKeyword */) ? 171 /* ConstructorType */ : 170 /* FunctionType */;
21512             var node = createNodeWithJSDoc(kind, pos);
21513             fillSignature(38 /* EqualsGreaterThanToken */, 4 /* Type */, node);
21514             return finishNode(node);
21515         }
21516         function parseKeywordAndNoDot() {
21517             var node = parseTokenNode();
21518             return token() === 24 /* DotToken */ ? undefined : node;
21519         }
21520         function parseLiteralTypeNode(negative) {
21521             var node = createNode(187 /* LiteralType */);
21522             var unaryMinusExpression;
21523             if (negative) {
21524                 unaryMinusExpression = createNode(207 /* PrefixUnaryExpression */);
21525                 unaryMinusExpression.operator = 40 /* MinusToken */;
21526                 nextToken();
21527             }
21528             var expression = token() === 106 /* TrueKeyword */ || token() === 91 /* FalseKeyword */
21529                 ? parseTokenNode()
21530                 : parseLiteralLikeNode(token());
21531             if (negative) {
21532                 unaryMinusExpression.operand = expression;
21533                 finishNode(unaryMinusExpression);
21534                 expression = unaryMinusExpression;
21535             }
21536             node.literal = expression;
21537             return finishNode(node);
21538         }
21539         function isStartOfTypeOfImportType() {
21540             nextToken();
21541             return token() === 96 /* ImportKeyword */;
21542         }
21543         function parseImportType() {
21544             sourceFile.flags |= 1048576 /* PossiblyContainsDynamicImport */;
21545             var node = createNode(188 /* ImportType */);
21546             if (parseOptional(108 /* TypeOfKeyword */)) {
21547                 node.isTypeOf = true;
21548             }
21549             parseExpected(96 /* ImportKeyword */);
21550             parseExpected(20 /* OpenParenToken */);
21551             node.argument = parseType();
21552             parseExpected(21 /* CloseParenToken */);
21553             if (parseOptional(24 /* DotToken */)) {
21554                 node.qualifier = parseEntityName(/*allowReservedWords*/ true, ts.Diagnostics.Type_expected);
21555             }
21556             if (!scanner.hasPrecedingLineBreak() && reScanLessThanToken() === 29 /* LessThanToken */) {
21557                 node.typeArguments = parseBracketedList(20 /* TypeArguments */, parseType, 29 /* LessThanToken */, 31 /* GreaterThanToken */);
21558             }
21559             return finishNode(node);
21560         }
21561         function nextTokenIsNumericOrBigIntLiteral() {
21562             nextToken();
21563             return token() === 8 /* NumericLiteral */ || token() === 9 /* BigIntLiteral */;
21564         }
21565         function parseNonArrayType() {
21566             switch (token()) {
21567                 case 125 /* AnyKeyword */:
21568                 case 148 /* UnknownKeyword */:
21569                 case 143 /* StringKeyword */:
21570                 case 140 /* NumberKeyword */:
21571                 case 151 /* BigIntKeyword */:
21572                 case 144 /* SymbolKeyword */:
21573                 case 128 /* BooleanKeyword */:
21574                 case 146 /* UndefinedKeyword */:
21575                 case 137 /* NeverKeyword */:
21576                 case 141 /* ObjectKeyword */:
21577                     // If these are followed by a dot, then parse these out as a dotted type reference instead.
21578                     return tryParse(parseKeywordAndNoDot) || parseTypeReference();
21579                 case 41 /* AsteriskToken */:
21580                     return parseJSDocAllType(/*postfixEquals*/ false);
21581                 case 65 /* AsteriskEqualsToken */:
21582                     return parseJSDocAllType(/*postfixEquals*/ true);
21583                 case 60 /* QuestionQuestionToken */:
21584                     // If there is '??', consider that is prefix '?' in JSDoc type.
21585                     scanner.reScanQuestionToken();
21586                 // falls through
21587                 case 57 /* QuestionToken */:
21588                     return parseJSDocUnknownOrNullableType();
21589                 case 94 /* FunctionKeyword */:
21590                     return parseJSDocFunctionType();
21591                 case 53 /* ExclamationToken */:
21592                     return parseJSDocNonNullableType();
21593                 case 14 /* NoSubstitutionTemplateLiteral */:
21594                 case 10 /* StringLiteral */:
21595                 case 8 /* NumericLiteral */:
21596                 case 9 /* BigIntLiteral */:
21597                 case 106 /* TrueKeyword */:
21598                 case 91 /* FalseKeyword */:
21599                     return parseLiteralTypeNode();
21600                 case 40 /* MinusToken */:
21601                     return lookAhead(nextTokenIsNumericOrBigIntLiteral) ? parseLiteralTypeNode(/*negative*/ true) : parseTypeReference();
21602                 case 110 /* VoidKeyword */:
21603                 case 100 /* NullKeyword */:
21604                     return parseTokenNode();
21605                 case 104 /* ThisKeyword */: {
21606                     var thisKeyword = parseThisTypeNode();
21607                     if (token() === 133 /* IsKeyword */ && !scanner.hasPrecedingLineBreak()) {
21608                         return parseThisTypePredicate(thisKeyword);
21609                     }
21610                     else {
21611                         return thisKeyword;
21612                     }
21613                 }
21614                 case 108 /* TypeOfKeyword */:
21615                     return lookAhead(isStartOfTypeOfImportType) ? parseImportType() : parseTypeQuery();
21616                 case 18 /* OpenBraceToken */:
21617                     return lookAhead(isStartOfMappedType) ? parseMappedType() : parseTypeLiteral();
21618                 case 22 /* OpenBracketToken */:
21619                     return parseTupleType();
21620                 case 20 /* OpenParenToken */:
21621                     return parseParenthesizedType();
21622                 case 96 /* ImportKeyword */:
21623                     return parseImportType();
21624                 case 124 /* AssertsKeyword */:
21625                     return lookAhead(nextTokenIsIdentifierOrKeywordOnSameLine) ? parseAssertsTypePredicate() : parseTypeReference();
21626                 default:
21627                     return parseTypeReference();
21628             }
21629         }
21630         function isStartOfType(inStartOfParameter) {
21631             switch (token()) {
21632                 case 125 /* AnyKeyword */:
21633                 case 148 /* UnknownKeyword */:
21634                 case 143 /* StringKeyword */:
21635                 case 140 /* NumberKeyword */:
21636                 case 151 /* BigIntKeyword */:
21637                 case 128 /* BooleanKeyword */:
21638                 case 138 /* ReadonlyKeyword */:
21639                 case 144 /* SymbolKeyword */:
21640                 case 147 /* UniqueKeyword */:
21641                 case 110 /* VoidKeyword */:
21642                 case 146 /* UndefinedKeyword */:
21643                 case 100 /* NullKeyword */:
21644                 case 104 /* ThisKeyword */:
21645                 case 108 /* TypeOfKeyword */:
21646                 case 137 /* NeverKeyword */:
21647                 case 18 /* OpenBraceToken */:
21648                 case 22 /* OpenBracketToken */:
21649                 case 29 /* LessThanToken */:
21650                 case 51 /* BarToken */:
21651                 case 50 /* AmpersandToken */:
21652                 case 99 /* NewKeyword */:
21653                 case 10 /* StringLiteral */:
21654                 case 8 /* NumericLiteral */:
21655                 case 9 /* BigIntLiteral */:
21656                 case 106 /* TrueKeyword */:
21657                 case 91 /* FalseKeyword */:
21658                 case 141 /* ObjectKeyword */:
21659                 case 41 /* AsteriskToken */:
21660                 case 57 /* QuestionToken */:
21661                 case 53 /* ExclamationToken */:
21662                 case 25 /* DotDotDotToken */:
21663                 case 132 /* InferKeyword */:
21664                 case 96 /* ImportKeyword */:
21665                 case 124 /* AssertsKeyword */:
21666                     return true;
21667                 case 94 /* FunctionKeyword */:
21668                     return !inStartOfParameter;
21669                 case 40 /* MinusToken */:
21670                     return !inStartOfParameter && lookAhead(nextTokenIsNumericOrBigIntLiteral);
21671                 case 20 /* OpenParenToken */:
21672                     // Only consider '(' the start of a type if followed by ')', '...', an identifier, a modifier,
21673                     // or something that starts a type. We don't want to consider things like '(1)' a type.
21674                     return !inStartOfParameter && lookAhead(isStartOfParenthesizedOrFunctionType);
21675                 default:
21676                     return isIdentifier();
21677             }
21678         }
21679         function isStartOfParenthesizedOrFunctionType() {
21680             nextToken();
21681             return token() === 21 /* CloseParenToken */ || isStartOfParameter(/*isJSDocParameter*/ false) || isStartOfType();
21682         }
21683         function parsePostfixTypeOrHigher() {
21684             var type = parseNonArrayType();
21685             while (!scanner.hasPrecedingLineBreak()) {
21686                 switch (token()) {
21687                     case 53 /* ExclamationToken */:
21688                         type = createPostfixType(298 /* JSDocNonNullableType */, type);
21689                         break;
21690                     case 57 /* QuestionToken */:
21691                         // If not in JSDoc and next token is start of a type we have a conditional type
21692                         if (!(contextFlags & 4194304 /* JSDoc */) && lookAhead(nextTokenIsStartOfType)) {
21693                             return type;
21694                         }
21695                         type = createPostfixType(297 /* JSDocNullableType */, type);
21696                         break;
21697                     case 22 /* OpenBracketToken */:
21698                         parseExpected(22 /* OpenBracketToken */);
21699                         if (isStartOfType()) {
21700                             var node = createNode(185 /* IndexedAccessType */, type.pos);
21701                             node.objectType = type;
21702                             node.indexType = parseType();
21703                             parseExpected(23 /* CloseBracketToken */);
21704                             type = finishNode(node);
21705                         }
21706                         else {
21707                             var node = createNode(174 /* ArrayType */, type.pos);
21708                             node.elementType = type;
21709                             parseExpected(23 /* CloseBracketToken */);
21710                             type = finishNode(node);
21711                         }
21712                         break;
21713                     default:
21714                         return type;
21715                 }
21716             }
21717             return type;
21718         }
21719         function createPostfixType(kind, type) {
21720             nextToken();
21721             var postfix = createNode(kind, type.pos);
21722             postfix.type = type;
21723             return finishNode(postfix);
21724         }
21725         function parseTypeOperator(operator) {
21726             var node = createNode(184 /* TypeOperator */);
21727             parseExpected(operator);
21728             node.operator = operator;
21729             node.type = parseTypeOperatorOrHigher();
21730             return finishNode(node);
21731         }
21732         function parseInferType() {
21733             var node = createNode(181 /* InferType */);
21734             parseExpected(132 /* InferKeyword */);
21735             var typeParameter = createNode(155 /* TypeParameter */);
21736             typeParameter.name = parseIdentifier();
21737             node.typeParameter = finishNode(typeParameter);
21738             return finishNode(node);
21739         }
21740         function parseTypeOperatorOrHigher() {
21741             var operator = token();
21742             switch (operator) {
21743                 case 134 /* KeyOfKeyword */:
21744                 case 147 /* UniqueKeyword */:
21745                 case 138 /* ReadonlyKeyword */:
21746                     return parseTypeOperator(operator);
21747                 case 132 /* InferKeyword */:
21748                     return parseInferType();
21749             }
21750             return parsePostfixTypeOrHigher();
21751         }
21752         function parseUnionOrIntersectionType(kind, parseConstituentType, operator) {
21753             var start = scanner.getStartPos();
21754             var hasLeadingOperator = parseOptional(operator);
21755             var type = parseConstituentType();
21756             if (token() === operator || hasLeadingOperator) {
21757                 var types = [type];
21758                 while (parseOptional(operator)) {
21759                     types.push(parseConstituentType());
21760                 }
21761                 var node = createNode(kind, start);
21762                 node.types = createNodeArray(types, start);
21763                 type = finishNode(node);
21764             }
21765             return type;
21766         }
21767         function parseIntersectionTypeOrHigher() {
21768             return parseUnionOrIntersectionType(179 /* IntersectionType */, parseTypeOperatorOrHigher, 50 /* AmpersandToken */);
21769         }
21770         function parseUnionTypeOrHigher() {
21771             return parseUnionOrIntersectionType(178 /* UnionType */, parseIntersectionTypeOrHigher, 51 /* BarToken */);
21772         }
21773         function isStartOfFunctionType() {
21774             if (token() === 29 /* LessThanToken */) {
21775                 return true;
21776             }
21777             return token() === 20 /* OpenParenToken */ && lookAhead(isUnambiguouslyStartOfFunctionType);
21778         }
21779         function skipParameterStart() {
21780             if (ts.isModifierKind(token())) {
21781                 // Skip modifiers
21782                 parseModifiers();
21783             }
21784             if (isIdentifier() || token() === 104 /* ThisKeyword */) {
21785                 nextToken();
21786                 return true;
21787             }
21788             if (token() === 22 /* OpenBracketToken */ || token() === 18 /* OpenBraceToken */) {
21789                 // Return true if we can parse an array or object binding pattern with no errors
21790                 var previousErrorCount = parseDiagnostics.length;
21791                 parseIdentifierOrPattern();
21792                 return previousErrorCount === parseDiagnostics.length;
21793             }
21794             return false;
21795         }
21796         function isUnambiguouslyStartOfFunctionType() {
21797             nextToken();
21798             if (token() === 21 /* CloseParenToken */ || token() === 25 /* DotDotDotToken */) {
21799                 // ( )
21800                 // ( ...
21801                 return true;
21802             }
21803             if (skipParameterStart()) {
21804                 // We successfully skipped modifiers (if any) and an identifier or binding pattern,
21805                 // now see if we have something that indicates a parameter declaration
21806                 if (token() === 58 /* ColonToken */ || token() === 27 /* CommaToken */ ||
21807                     token() === 57 /* QuestionToken */ || token() === 62 /* EqualsToken */) {
21808                     // ( xxx :
21809                     // ( xxx ,
21810                     // ( xxx ?
21811                     // ( xxx =
21812                     return true;
21813                 }
21814                 if (token() === 21 /* CloseParenToken */) {
21815                     nextToken();
21816                     if (token() === 38 /* EqualsGreaterThanToken */) {
21817                         // ( xxx ) =>
21818                         return true;
21819                     }
21820                 }
21821             }
21822             return false;
21823         }
21824         function parseTypeOrTypePredicate() {
21825             var typePredicateVariable = isIdentifier() && tryParse(parseTypePredicatePrefix);
21826             var type = parseType();
21827             if (typePredicateVariable) {
21828                 var node = createNode(168 /* TypePredicate */, typePredicateVariable.pos);
21829                 node.assertsModifier = undefined;
21830                 node.parameterName = typePredicateVariable;
21831                 node.type = type;
21832                 return finishNode(node);
21833             }
21834             else {
21835                 return type;
21836             }
21837         }
21838         function parseTypePredicatePrefix() {
21839             var id = parseIdentifier();
21840             if (token() === 133 /* IsKeyword */ && !scanner.hasPrecedingLineBreak()) {
21841                 nextToken();
21842                 return id;
21843             }
21844         }
21845         function parseAssertsTypePredicate() {
21846             var node = createNode(168 /* TypePredicate */);
21847             node.assertsModifier = parseExpectedToken(124 /* AssertsKeyword */);
21848             node.parameterName = token() === 104 /* ThisKeyword */ ? parseThisTypeNode() : parseIdentifier();
21849             node.type = parseOptional(133 /* IsKeyword */) ? parseType() : undefined;
21850             return finishNode(node);
21851         }
21852         function parseType() {
21853             // The rules about 'yield' only apply to actual code/expression contexts.  They don't
21854             // apply to 'type' contexts.  So we disable these parameters here before moving on.
21855             return doOutsideOfContext(40960 /* TypeExcludesFlags */, parseTypeWorker);
21856         }
21857         function parseTypeWorker(noConditionalTypes) {
21858             if (isStartOfFunctionType() || token() === 99 /* NewKeyword */) {
21859                 return parseFunctionOrConstructorType();
21860             }
21861             var type = parseUnionTypeOrHigher();
21862             if (!noConditionalTypes && !scanner.hasPrecedingLineBreak() && parseOptional(90 /* ExtendsKeyword */)) {
21863                 var node = createNode(180 /* ConditionalType */, type.pos);
21864                 node.checkType = type;
21865                 // The type following 'extends' is not permitted to be another conditional type
21866                 node.extendsType = parseTypeWorker(/*noConditionalTypes*/ true);
21867                 parseExpected(57 /* QuestionToken */);
21868                 node.trueType = parseTypeWorker();
21869                 parseExpected(58 /* ColonToken */);
21870                 node.falseType = parseTypeWorker();
21871                 return finishNode(node);
21872             }
21873             return type;
21874         }
21875         function parseTypeAnnotation() {
21876             return parseOptional(58 /* ColonToken */) ? parseType() : undefined;
21877         }
21878         // EXPRESSIONS
21879         function isStartOfLeftHandSideExpression() {
21880             switch (token()) {
21881                 case 104 /* ThisKeyword */:
21882                 case 102 /* SuperKeyword */:
21883                 case 100 /* NullKeyword */:
21884                 case 106 /* TrueKeyword */:
21885                 case 91 /* FalseKeyword */:
21886                 case 8 /* NumericLiteral */:
21887                 case 9 /* BigIntLiteral */:
21888                 case 10 /* StringLiteral */:
21889                 case 14 /* NoSubstitutionTemplateLiteral */:
21890                 case 15 /* TemplateHead */:
21891                 case 20 /* OpenParenToken */:
21892                 case 22 /* OpenBracketToken */:
21893                 case 18 /* OpenBraceToken */:
21894                 case 94 /* FunctionKeyword */:
21895                 case 80 /* ClassKeyword */:
21896                 case 99 /* NewKeyword */:
21897                 case 43 /* SlashToken */:
21898                 case 67 /* SlashEqualsToken */:
21899                 case 75 /* Identifier */:
21900                     return true;
21901                 case 96 /* ImportKeyword */:
21902                     return lookAhead(nextTokenIsOpenParenOrLessThanOrDot);
21903                 default:
21904                     return isIdentifier();
21905             }
21906         }
21907         function isStartOfExpression() {
21908             if (isStartOfLeftHandSideExpression()) {
21909                 return true;
21910             }
21911             switch (token()) {
21912                 case 39 /* PlusToken */:
21913                 case 40 /* MinusToken */:
21914                 case 54 /* TildeToken */:
21915                 case 53 /* ExclamationToken */:
21916                 case 85 /* DeleteKeyword */:
21917                 case 108 /* TypeOfKeyword */:
21918                 case 110 /* VoidKeyword */:
21919                 case 45 /* PlusPlusToken */:
21920                 case 46 /* MinusMinusToken */:
21921                 case 29 /* LessThanToken */:
21922                 case 127 /* AwaitKeyword */:
21923                 case 121 /* YieldKeyword */:
21924                 case 76 /* PrivateIdentifier */:
21925                     // Yield/await always starts an expression.  Either it is an identifier (in which case
21926                     // it is definitely an expression).  Or it's a keyword (either because we're in
21927                     // a generator or async function, or in strict mode (or both)) and it started a yield or await expression.
21928                     return true;
21929                 default:
21930                     // Error tolerance.  If we see the start of some binary operator, we consider
21931                     // that the start of an expression.  That way we'll parse out a missing identifier,
21932                     // give a good message about an identifier being missing, and then consume the
21933                     // rest of the binary expression.
21934                     if (isBinaryOperator()) {
21935                         return true;
21936                     }
21937                     return isIdentifier();
21938             }
21939         }
21940         function isStartOfExpressionStatement() {
21941             // As per the grammar, none of '{' or 'function' or 'class' can start an expression statement.
21942             return token() !== 18 /* OpenBraceToken */ &&
21943                 token() !== 94 /* FunctionKeyword */ &&
21944                 token() !== 80 /* ClassKeyword */ &&
21945                 token() !== 59 /* AtToken */ &&
21946                 isStartOfExpression();
21947         }
21948         function parseExpression() {
21949             // Expression[in]:
21950             //      AssignmentExpression[in]
21951             //      Expression[in] , AssignmentExpression[in]
21952             // clear the decorator context when parsing Expression, as it should be unambiguous when parsing a decorator
21953             var saveDecoratorContext = inDecoratorContext();
21954             if (saveDecoratorContext) {
21955                 setDecoratorContext(/*val*/ false);
21956             }
21957             var expr = parseAssignmentExpressionOrHigher();
21958             var operatorToken;
21959             while ((operatorToken = parseOptionalToken(27 /* CommaToken */))) {
21960                 expr = makeBinaryExpression(expr, operatorToken, parseAssignmentExpressionOrHigher());
21961             }
21962             if (saveDecoratorContext) {
21963                 setDecoratorContext(/*val*/ true);
21964             }
21965             return expr;
21966         }
21967         function parseInitializer() {
21968             return parseOptional(62 /* EqualsToken */) ? parseAssignmentExpressionOrHigher() : undefined;
21969         }
21970         function parseAssignmentExpressionOrHigher() {
21971             //  AssignmentExpression[in,yield]:
21972             //      1) ConditionalExpression[?in,?yield]
21973             //      2) LeftHandSideExpression = AssignmentExpression[?in,?yield]
21974             //      3) LeftHandSideExpression AssignmentOperator AssignmentExpression[?in,?yield]
21975             //      4) ArrowFunctionExpression[?in,?yield]
21976             //      5) AsyncArrowFunctionExpression[in,yield,await]
21977             //      6) [+Yield] YieldExpression[?In]
21978             //
21979             // Note: for ease of implementation we treat productions '2' and '3' as the same thing.
21980             // (i.e. they're both BinaryExpressions with an assignment operator in it).
21981             // First, do the simple check if we have a YieldExpression (production '6').
21982             if (isYieldExpression()) {
21983                 return parseYieldExpression();
21984             }
21985             // Then, check if we have an arrow function (production '4' and '5') that starts with a parenthesized
21986             // parameter list or is an async arrow function.
21987             // AsyncArrowFunctionExpression:
21988             //      1) async[no LineTerminator here]AsyncArrowBindingIdentifier[?Yield][no LineTerminator here]=>AsyncConciseBody[?In]
21989             //      2) CoverCallExpressionAndAsyncArrowHead[?Yield, ?Await][no LineTerminator here]=>AsyncConciseBody[?In]
21990             // Production (1) of AsyncArrowFunctionExpression is parsed in "tryParseAsyncSimpleArrowFunctionExpression".
21991             // And production (2) is parsed in "tryParseParenthesizedArrowFunctionExpression".
21992             //
21993             // If we do successfully parse arrow-function, we must *not* recurse for productions 1, 2 or 3. An ArrowFunction is
21994             // not a LeftHandSideExpression, nor does it start a ConditionalExpression.  So we are done
21995             // with AssignmentExpression if we see one.
21996             var arrowExpression = tryParseParenthesizedArrowFunctionExpression() || tryParseAsyncSimpleArrowFunctionExpression();
21997             if (arrowExpression) {
21998                 return arrowExpression;
21999             }
22000             // Now try to see if we're in production '1', '2' or '3'.  A conditional expression can
22001             // start with a LogicalOrExpression, while the assignment productions can only start with
22002             // LeftHandSideExpressions.
22003             //
22004             // So, first, we try to just parse out a BinaryExpression.  If we get something that is a
22005             // LeftHandSide or higher, then we can try to parse out the assignment expression part.
22006             // Otherwise, we try to parse out the conditional expression bit.  We want to allow any
22007             // binary expression here, so we pass in the 'lowest' precedence here so that it matches
22008             // and consumes anything.
22009             var expr = parseBinaryExpressionOrHigher(/*precedence*/ 0);
22010             // To avoid a look-ahead, we did not handle the case of an arrow function with a single un-parenthesized
22011             // parameter ('x => ...') above. We handle it here by checking if the parsed expression was a single
22012             // identifier and the current token is an arrow.
22013             if (expr.kind === 75 /* Identifier */ && token() === 38 /* EqualsGreaterThanToken */) {
22014                 return parseSimpleArrowFunctionExpression(expr);
22015             }
22016             // Now see if we might be in cases '2' or '3'.
22017             // If the expression was a LHS expression, and we have an assignment operator, then
22018             // we're in '2' or '3'. Consume the assignment and return.
22019             //
22020             // Note: we call reScanGreaterToken so that we get an appropriately merged token
22021             // for cases like `> > =` becoming `>>=`
22022             if (ts.isLeftHandSideExpression(expr) && ts.isAssignmentOperator(reScanGreaterToken())) {
22023                 return makeBinaryExpression(expr, parseTokenNode(), parseAssignmentExpressionOrHigher());
22024             }
22025             // It wasn't an assignment or a lambda.  This is a conditional expression:
22026             return parseConditionalExpressionRest(expr);
22027         }
22028         function isYieldExpression() {
22029             if (token() === 121 /* YieldKeyword */) {
22030                 // If we have a 'yield' keyword, and this is a context where yield expressions are
22031                 // allowed, then definitely parse out a yield expression.
22032                 if (inYieldContext()) {
22033                     return true;
22034                 }
22035                 // We're in a context where 'yield expr' is not allowed.  However, if we can
22036                 // definitely tell that the user was trying to parse a 'yield expr' and not
22037                 // just a normal expr that start with a 'yield' identifier, then parse out
22038                 // a 'yield expr'.  We can then report an error later that they are only
22039                 // allowed in generator expressions.
22040                 //
22041                 // for example, if we see 'yield(foo)', then we'll have to treat that as an
22042                 // invocation expression of something called 'yield'.  However, if we have
22043                 // 'yield foo' then that is not legal as a normal expression, so we can
22044                 // definitely recognize this as a yield expression.
22045                 //
22046                 // for now we just check if the next token is an identifier.  More heuristics
22047                 // can be added here later as necessary.  We just need to make sure that we
22048                 // don't accidentally consume something legal.
22049                 return lookAhead(nextTokenIsIdentifierOrKeywordOrLiteralOnSameLine);
22050             }
22051             return false;
22052         }
22053         function nextTokenIsIdentifierOnSameLine() {
22054             nextToken();
22055             return !scanner.hasPrecedingLineBreak() && isIdentifier();
22056         }
22057         function parseYieldExpression() {
22058             var node = createNode(212 /* YieldExpression */);
22059             // YieldExpression[In] :
22060             //      yield
22061             //      yield [no LineTerminator here] [Lexical goal InputElementRegExp]AssignmentExpression[?In, Yield]
22062             //      yield [no LineTerminator here] * [Lexical goal InputElementRegExp]AssignmentExpression[?In, Yield]
22063             nextToken();
22064             if (!scanner.hasPrecedingLineBreak() &&
22065                 (token() === 41 /* AsteriskToken */ || isStartOfExpression())) {
22066                 node.asteriskToken = parseOptionalToken(41 /* AsteriskToken */);
22067                 node.expression = parseAssignmentExpressionOrHigher();
22068                 return finishNode(node);
22069             }
22070             else {
22071                 // if the next token is not on the same line as yield.  or we don't have an '*' or
22072                 // the start of an expression, then this is just a simple "yield" expression.
22073                 return finishNode(node);
22074             }
22075         }
22076         function parseSimpleArrowFunctionExpression(identifier, asyncModifier) {
22077             ts.Debug.assert(token() === 38 /* EqualsGreaterThanToken */, "parseSimpleArrowFunctionExpression should only have been called if we had a =>");
22078             var node;
22079             if (asyncModifier) {
22080                 node = createNode(202 /* ArrowFunction */, asyncModifier.pos);
22081                 node.modifiers = asyncModifier;
22082             }
22083             else {
22084                 node = createNode(202 /* ArrowFunction */, identifier.pos);
22085             }
22086             var parameter = createNode(156 /* Parameter */, identifier.pos);
22087             parameter.name = identifier;
22088             finishNode(parameter);
22089             node.parameters = createNodeArray([parameter], parameter.pos, parameter.end);
22090             node.equalsGreaterThanToken = parseExpectedToken(38 /* EqualsGreaterThanToken */);
22091             node.body = parseArrowFunctionExpressionBody(/*isAsync*/ !!asyncModifier);
22092             return addJSDocComment(finishNode(node));
22093         }
22094         function tryParseParenthesizedArrowFunctionExpression() {
22095             var triState = isParenthesizedArrowFunctionExpression();
22096             if (triState === 0 /* False */) {
22097                 // It's definitely not a parenthesized arrow function expression.
22098                 return undefined;
22099             }
22100             // If we definitely have an arrow function, then we can just parse one, not requiring a
22101             // following => or { token. Otherwise, we *might* have an arrow function.  Try to parse
22102             // it out, but don't allow any ambiguity, and return 'undefined' if this could be an
22103             // expression instead.
22104             var arrowFunction = triState === 1 /* True */
22105                 ? parseParenthesizedArrowFunctionExpressionHead(/*allowAmbiguity*/ true)
22106                 : tryParse(parsePossibleParenthesizedArrowFunctionExpressionHead);
22107             if (!arrowFunction) {
22108                 // Didn't appear to actually be a parenthesized arrow function.  Just bail out.
22109                 return undefined;
22110             }
22111             var isAsync = hasModifierOfKind(arrowFunction, 126 /* AsyncKeyword */);
22112             // If we have an arrow, then try to parse the body. Even if not, try to parse if we
22113             // have an opening brace, just in case we're in an error state.
22114             var lastToken = token();
22115             arrowFunction.equalsGreaterThanToken = parseExpectedToken(38 /* EqualsGreaterThanToken */);
22116             arrowFunction.body = (lastToken === 38 /* EqualsGreaterThanToken */ || lastToken === 18 /* OpenBraceToken */)
22117                 ? parseArrowFunctionExpressionBody(isAsync)
22118                 : parseIdentifier();
22119             return finishNode(arrowFunction);
22120         }
22121         //  True        -> We definitely expect a parenthesized arrow function here.
22122         //  False       -> There *cannot* be a parenthesized arrow function here.
22123         //  Unknown     -> There *might* be a parenthesized arrow function here.
22124         //                 Speculatively look ahead to be sure, and rollback if not.
22125         function isParenthesizedArrowFunctionExpression() {
22126             if (token() === 20 /* OpenParenToken */ || token() === 29 /* LessThanToken */ || token() === 126 /* AsyncKeyword */) {
22127                 return lookAhead(isParenthesizedArrowFunctionExpressionWorker);
22128             }
22129             if (token() === 38 /* EqualsGreaterThanToken */) {
22130                 // ERROR RECOVERY TWEAK:
22131                 // If we see a standalone => try to parse it as an arrow function expression as that's
22132                 // likely what the user intended to write.
22133                 return 1 /* True */;
22134             }
22135             // Definitely not a parenthesized arrow function.
22136             return 0 /* False */;
22137         }
22138         function isParenthesizedArrowFunctionExpressionWorker() {
22139             if (token() === 126 /* AsyncKeyword */) {
22140                 nextToken();
22141                 if (scanner.hasPrecedingLineBreak()) {
22142                     return 0 /* False */;
22143                 }
22144                 if (token() !== 20 /* OpenParenToken */ && token() !== 29 /* LessThanToken */) {
22145                     return 0 /* False */;
22146                 }
22147             }
22148             var first = token();
22149             var second = nextToken();
22150             if (first === 20 /* OpenParenToken */) {
22151                 if (second === 21 /* CloseParenToken */) {
22152                     // Simple cases: "() =>", "(): ", and "() {".
22153                     // This is an arrow function with no parameters.
22154                     // The last one is not actually an arrow function,
22155                     // but this is probably what the user intended.
22156                     var third = nextToken();
22157                     switch (third) {
22158                         case 38 /* EqualsGreaterThanToken */:
22159                         case 58 /* ColonToken */:
22160                         case 18 /* OpenBraceToken */:
22161                             return 1 /* True */;
22162                         default:
22163                             return 0 /* False */;
22164                     }
22165                 }
22166                 // If encounter "([" or "({", this could be the start of a binding pattern.
22167                 // Examples:
22168                 //      ([ x ]) => { }
22169                 //      ({ x }) => { }
22170                 //      ([ x ])
22171                 //      ({ x })
22172                 if (second === 22 /* OpenBracketToken */ || second === 18 /* OpenBraceToken */) {
22173                     return 2 /* Unknown */;
22174                 }
22175                 // Simple case: "(..."
22176                 // This is an arrow function with a rest parameter.
22177                 if (second === 25 /* DotDotDotToken */) {
22178                     return 1 /* True */;
22179                 }
22180                 // Check for "(xxx yyy", where xxx is a modifier and yyy is an identifier. This
22181                 // isn't actually allowed, but we want to treat it as a lambda so we can provide
22182                 // a good error message.
22183                 if (ts.isModifierKind(second) && second !== 126 /* AsyncKeyword */ && lookAhead(nextTokenIsIdentifier)) {
22184                     return 1 /* True */;
22185                 }
22186                 // If we had "(" followed by something that's not an identifier,
22187                 // then this definitely doesn't look like a lambda.  "this" is not
22188                 // valid, but we want to parse it and then give a semantic error.
22189                 if (!isIdentifier() && second !== 104 /* ThisKeyword */) {
22190                     return 0 /* False */;
22191                 }
22192                 switch (nextToken()) {
22193                     case 58 /* ColonToken */:
22194                         // If we have something like "(a:", then we must have a
22195                         // type-annotated parameter in an arrow function expression.
22196                         return 1 /* True */;
22197                     case 57 /* QuestionToken */:
22198                         nextToken();
22199                         // If we have "(a?:" or "(a?," or "(a?=" or "(a?)" then it is definitely a lambda.
22200                         if (token() === 58 /* ColonToken */ || token() === 27 /* CommaToken */ || token() === 62 /* EqualsToken */ || token() === 21 /* CloseParenToken */) {
22201                             return 1 /* True */;
22202                         }
22203                         // Otherwise it is definitely not a lambda.
22204                         return 0 /* False */;
22205                     case 27 /* CommaToken */:
22206                     case 62 /* EqualsToken */:
22207                     case 21 /* CloseParenToken */:
22208                         // If we have "(a," or "(a=" or "(a)" this *could* be an arrow function
22209                         return 2 /* Unknown */;
22210                 }
22211                 // It is definitely not an arrow function
22212                 return 0 /* False */;
22213             }
22214             else {
22215                 ts.Debug.assert(first === 29 /* LessThanToken */);
22216                 // If we have "<" not followed by an identifier,
22217                 // then this definitely is not an arrow function.
22218                 if (!isIdentifier()) {
22219                     return 0 /* False */;
22220                 }
22221                 // JSX overrides
22222                 if (sourceFile.languageVariant === 1 /* JSX */) {
22223                     var isArrowFunctionInJsx = lookAhead(function () {
22224                         var third = nextToken();
22225                         if (third === 90 /* ExtendsKeyword */) {
22226                             var fourth = nextToken();
22227                             switch (fourth) {
22228                                 case 62 /* EqualsToken */:
22229                                 case 31 /* GreaterThanToken */:
22230                                     return false;
22231                                 default:
22232                                     return true;
22233                             }
22234                         }
22235                         else if (third === 27 /* CommaToken */) {
22236                             return true;
22237                         }
22238                         return false;
22239                     });
22240                     if (isArrowFunctionInJsx) {
22241                         return 1 /* True */;
22242                     }
22243                     return 0 /* False */;
22244                 }
22245                 // This *could* be a parenthesized arrow function.
22246                 return 2 /* Unknown */;
22247             }
22248         }
22249         function parsePossibleParenthesizedArrowFunctionExpressionHead() {
22250             var tokenPos = scanner.getTokenPos();
22251             if (notParenthesizedArrow && notParenthesizedArrow.has(tokenPos.toString())) {
22252                 return undefined;
22253             }
22254             var result = parseParenthesizedArrowFunctionExpressionHead(/*allowAmbiguity*/ false);
22255             if (!result) {
22256                 (notParenthesizedArrow || (notParenthesizedArrow = ts.createMap())).set(tokenPos.toString(), true);
22257             }
22258             return result;
22259         }
22260         function tryParseAsyncSimpleArrowFunctionExpression() {
22261             // We do a check here so that we won't be doing unnecessarily call to "lookAhead"
22262             if (token() === 126 /* AsyncKeyword */) {
22263                 if (lookAhead(isUnParenthesizedAsyncArrowFunctionWorker) === 1 /* True */) {
22264                     var asyncModifier = parseModifiersForArrowFunction();
22265                     var expr = parseBinaryExpressionOrHigher(/*precedence*/ 0);
22266                     return parseSimpleArrowFunctionExpression(expr, asyncModifier);
22267                 }
22268             }
22269             return undefined;
22270         }
22271         function isUnParenthesizedAsyncArrowFunctionWorker() {
22272             // AsyncArrowFunctionExpression:
22273             //      1) async[no LineTerminator here]AsyncArrowBindingIdentifier[?Yield][no LineTerminator here]=>AsyncConciseBody[?In]
22274             //      2) CoverCallExpressionAndAsyncArrowHead[?Yield, ?Await][no LineTerminator here]=>AsyncConciseBody[?In]
22275             if (token() === 126 /* AsyncKeyword */) {
22276                 nextToken();
22277                 // If the "async" is followed by "=>" token then it is not a beginning of an async arrow-function
22278                 // but instead a simple arrow-function which will be parsed inside "parseAssignmentExpressionOrHigher"
22279                 if (scanner.hasPrecedingLineBreak() || token() === 38 /* EqualsGreaterThanToken */) {
22280                     return 0 /* False */;
22281                 }
22282                 // Check for un-parenthesized AsyncArrowFunction
22283                 var expr = parseBinaryExpressionOrHigher(/*precedence*/ 0);
22284                 if (!scanner.hasPrecedingLineBreak() && expr.kind === 75 /* Identifier */ && token() === 38 /* EqualsGreaterThanToken */) {
22285                     return 1 /* True */;
22286                 }
22287             }
22288             return 0 /* False */;
22289         }
22290         function parseParenthesizedArrowFunctionExpressionHead(allowAmbiguity) {
22291             var node = createNodeWithJSDoc(202 /* ArrowFunction */);
22292             node.modifiers = parseModifiersForArrowFunction();
22293             var isAsync = hasModifierOfKind(node, 126 /* AsyncKeyword */) ? 2 /* Await */ : 0 /* None */;
22294             // Arrow functions are never generators.
22295             //
22296             // If we're speculatively parsing a signature for a parenthesized arrow function, then
22297             // we have to have a complete parameter list.  Otherwise we might see something like
22298             // a => (b => c)
22299             // And think that "(b =>" was actually a parenthesized arrow function with a missing
22300             // close paren.
22301             if (!fillSignature(58 /* ColonToken */, isAsync, node) && !allowAmbiguity) {
22302                 return undefined;
22303             }
22304             // Parsing a signature isn't enough.
22305             // Parenthesized arrow signatures often look like other valid expressions.
22306             // For instance:
22307             //  - "(x = 10)" is an assignment expression parsed as a signature with a default parameter value.
22308             //  - "(x,y)" is a comma expression parsed as a signature with two parameters.
22309             //  - "a ? (b): c" will have "(b):" parsed as a signature with a return type annotation.
22310             //  - "a ? (b): function() {}" will too, since function() is a valid JSDoc function type.
22311             //
22312             // So we need just a bit of lookahead to ensure that it can only be a signature.
22313             var hasJSDocFunctionType = node.type && ts.isJSDocFunctionType(node.type);
22314             if (!allowAmbiguity && token() !== 38 /* EqualsGreaterThanToken */ && (hasJSDocFunctionType || token() !== 18 /* OpenBraceToken */)) {
22315                 // Returning undefined here will cause our caller to rewind to where we started from.
22316                 return undefined;
22317             }
22318             return node;
22319         }
22320         function parseArrowFunctionExpressionBody(isAsync) {
22321             if (token() === 18 /* OpenBraceToken */) {
22322                 return parseFunctionBlock(isAsync ? 2 /* Await */ : 0 /* None */);
22323             }
22324             if (token() !== 26 /* SemicolonToken */ &&
22325                 token() !== 94 /* FunctionKeyword */ &&
22326                 token() !== 80 /* ClassKeyword */ &&
22327                 isStartOfStatement() &&
22328                 !isStartOfExpressionStatement()) {
22329                 // Check if we got a plain statement (i.e. no expression-statements, no function/class expressions/declarations)
22330                 //
22331                 // Here we try to recover from a potential error situation in the case where the
22332                 // user meant to supply a block. For example, if the user wrote:
22333                 //
22334                 //  a =>
22335                 //      let v = 0;
22336                 //  }
22337                 //
22338                 // they may be missing an open brace.  Check to see if that's the case so we can
22339                 // try to recover better.  If we don't do this, then the next close curly we see may end
22340                 // up preemptively closing the containing construct.
22341                 //
22342                 // Note: even when 'IgnoreMissingOpenBrace' is passed, parseBody will still error.
22343                 return parseFunctionBlock(16 /* IgnoreMissingOpenBrace */ | (isAsync ? 2 /* Await */ : 0 /* None */));
22344             }
22345             return isAsync
22346                 ? doInAwaitContext(parseAssignmentExpressionOrHigher)
22347                 : doOutsideOfAwaitContext(parseAssignmentExpressionOrHigher);
22348         }
22349         function parseConditionalExpressionRest(leftOperand) {
22350             // Note: we are passed in an expression which was produced from parseBinaryExpressionOrHigher.
22351             var questionToken = parseOptionalToken(57 /* QuestionToken */);
22352             if (!questionToken) {
22353                 return leftOperand;
22354             }
22355             // Note: we explicitly 'allowIn' in the whenTrue part of the condition expression, and
22356             // we do not that for the 'whenFalse' part.
22357             var node = createNode(210 /* ConditionalExpression */, leftOperand.pos);
22358             node.condition = leftOperand;
22359             node.questionToken = questionToken;
22360             node.whenTrue = doOutsideOfContext(disallowInAndDecoratorContext, parseAssignmentExpressionOrHigher);
22361             node.colonToken = parseExpectedToken(58 /* ColonToken */);
22362             node.whenFalse = ts.nodeIsPresent(node.colonToken)
22363                 ? parseAssignmentExpressionOrHigher()
22364                 : createMissingNode(75 /* Identifier */, /*reportAtCurrentPosition*/ false, ts.Diagnostics._0_expected, ts.tokenToString(58 /* ColonToken */));
22365             return finishNode(node);
22366         }
22367         function parseBinaryExpressionOrHigher(precedence) {
22368             var leftOperand = parseUnaryExpressionOrHigher();
22369             return parseBinaryExpressionRest(precedence, leftOperand);
22370         }
22371         function isInOrOfKeyword(t) {
22372             return t === 97 /* InKeyword */ || t === 152 /* OfKeyword */;
22373         }
22374         function parseBinaryExpressionRest(precedence, leftOperand) {
22375             while (true) {
22376                 // We either have a binary operator here, or we're finished.  We call
22377                 // reScanGreaterToken so that we merge token sequences like > and = into >=
22378                 reScanGreaterToken();
22379                 var newPrecedence = ts.getBinaryOperatorPrecedence(token());
22380                 // Check the precedence to see if we should "take" this operator
22381                 // - For left associative operator (all operator but **), consume the operator,
22382                 //   recursively call the function below, and parse binaryExpression as a rightOperand
22383                 //   of the caller if the new precedence of the operator is greater then or equal to the current precedence.
22384                 //   For example:
22385                 //      a - b - c;
22386                 //            ^token; leftOperand = b. Return b to the caller as a rightOperand
22387                 //      a * b - c
22388                 //            ^token; leftOperand = b. Return b to the caller as a rightOperand
22389                 //      a - b * c;
22390                 //            ^token; leftOperand = b. Return b * c to the caller as a rightOperand
22391                 // - For right associative operator (**), consume the operator, recursively call the function
22392                 //   and parse binaryExpression as a rightOperand of the caller if the new precedence of
22393                 //   the operator is strictly grater than the current precedence
22394                 //   For example:
22395                 //      a ** b ** c;
22396                 //             ^^token; leftOperand = b. Return b ** c to the caller as a rightOperand
22397                 //      a - b ** c;
22398                 //            ^^token; leftOperand = b. Return b ** c to the caller as a rightOperand
22399                 //      a ** b - c
22400                 //             ^token; leftOperand = b. Return b to the caller as a rightOperand
22401                 var consumeCurrentOperator = token() === 42 /* AsteriskAsteriskToken */ ?
22402                     newPrecedence >= precedence :
22403                     newPrecedence > precedence;
22404                 if (!consumeCurrentOperator) {
22405                     break;
22406                 }
22407                 if (token() === 97 /* InKeyword */ && inDisallowInContext()) {
22408                     break;
22409                 }
22410                 if (token() === 123 /* AsKeyword */) {
22411                     // Make sure we *do* perform ASI for constructs like this:
22412                     //    var x = foo
22413                     //    as (Bar)
22414                     // This should be parsed as an initialized variable, followed
22415                     // by a function call to 'as' with the argument 'Bar'
22416                     if (scanner.hasPrecedingLineBreak()) {
22417                         break;
22418                     }
22419                     else {
22420                         nextToken();
22421                         leftOperand = makeAsExpression(leftOperand, parseType());
22422                     }
22423                 }
22424                 else {
22425                     leftOperand = makeBinaryExpression(leftOperand, parseTokenNode(), parseBinaryExpressionOrHigher(newPrecedence));
22426                 }
22427             }
22428             return leftOperand;
22429         }
22430         function isBinaryOperator() {
22431             if (inDisallowInContext() && token() === 97 /* InKeyword */) {
22432                 return false;
22433             }
22434             return ts.getBinaryOperatorPrecedence(token()) > 0;
22435         }
22436         function makeBinaryExpression(left, operatorToken, right) {
22437             var node = createNode(209 /* BinaryExpression */, left.pos);
22438             node.left = left;
22439             node.operatorToken = operatorToken;
22440             node.right = right;
22441             return finishNode(node);
22442         }
22443         function makeAsExpression(left, right) {
22444             var node = createNode(217 /* AsExpression */, left.pos);
22445             node.expression = left;
22446             node.type = right;
22447             return finishNode(node);
22448         }
22449         function parsePrefixUnaryExpression() {
22450             var node = createNode(207 /* PrefixUnaryExpression */);
22451             node.operator = token();
22452             nextToken();
22453             node.operand = parseSimpleUnaryExpression();
22454             return finishNode(node);
22455         }
22456         function parseDeleteExpression() {
22457             var node = createNode(203 /* DeleteExpression */);
22458             nextToken();
22459             node.expression = parseSimpleUnaryExpression();
22460             return finishNode(node);
22461         }
22462         function parseTypeOfExpression() {
22463             var node = createNode(204 /* TypeOfExpression */);
22464             nextToken();
22465             node.expression = parseSimpleUnaryExpression();
22466             return finishNode(node);
22467         }
22468         function parseVoidExpression() {
22469             var node = createNode(205 /* VoidExpression */);
22470             nextToken();
22471             node.expression = parseSimpleUnaryExpression();
22472             return finishNode(node);
22473         }
22474         function isAwaitExpression() {
22475             if (token() === 127 /* AwaitKeyword */) {
22476                 if (inAwaitContext()) {
22477                     return true;
22478                 }
22479                 // here we are using similar heuristics as 'isYieldExpression'
22480                 return lookAhead(nextTokenIsIdentifierOrKeywordOrLiteralOnSameLine);
22481             }
22482             return false;
22483         }
22484         function parseAwaitExpression() {
22485             var node = createNode(206 /* AwaitExpression */);
22486             nextToken();
22487             node.expression = parseSimpleUnaryExpression();
22488             return finishNode(node);
22489         }
22490         /**
22491          * Parse ES7 exponential expression and await expression
22492          *
22493          * ES7 ExponentiationExpression:
22494          *      1) UnaryExpression[?Yield]
22495          *      2) UpdateExpression[?Yield] ** ExponentiationExpression[?Yield]
22496          *
22497          */
22498         function parseUnaryExpressionOrHigher() {
22499             /**
22500              * ES7 UpdateExpression:
22501              *      1) LeftHandSideExpression[?Yield]
22502              *      2) LeftHandSideExpression[?Yield][no LineTerminator here]++
22503              *      3) LeftHandSideExpression[?Yield][no LineTerminator here]--
22504              *      4) ++UnaryExpression[?Yield]
22505              *      5) --UnaryExpression[?Yield]
22506              */
22507             if (isUpdateExpression()) {
22508                 var updateExpression = parseUpdateExpression();
22509                 return token() === 42 /* AsteriskAsteriskToken */ ?
22510                     parseBinaryExpressionRest(ts.getBinaryOperatorPrecedence(token()), updateExpression) :
22511                     updateExpression;
22512             }
22513             /**
22514              * ES7 UnaryExpression:
22515              *      1) UpdateExpression[?yield]
22516              *      2) delete UpdateExpression[?yield]
22517              *      3) void UpdateExpression[?yield]
22518              *      4) typeof UpdateExpression[?yield]
22519              *      5) + UpdateExpression[?yield]
22520              *      6) - UpdateExpression[?yield]
22521              *      7) ~ UpdateExpression[?yield]
22522              *      8) ! UpdateExpression[?yield]
22523              */
22524             var unaryOperator = token();
22525             var simpleUnaryExpression = parseSimpleUnaryExpression();
22526             if (token() === 42 /* AsteriskAsteriskToken */) {
22527                 var pos = ts.skipTrivia(sourceText, simpleUnaryExpression.pos);
22528                 var end = simpleUnaryExpression.end;
22529                 if (simpleUnaryExpression.kind === 199 /* TypeAssertionExpression */) {
22530                     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);
22531                 }
22532                 else {
22533                     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));
22534                 }
22535             }
22536             return simpleUnaryExpression;
22537         }
22538         /**
22539          * Parse ES7 simple-unary expression or higher:
22540          *
22541          * ES7 UnaryExpression:
22542          *      1) UpdateExpression[?yield]
22543          *      2) delete UnaryExpression[?yield]
22544          *      3) void UnaryExpression[?yield]
22545          *      4) typeof UnaryExpression[?yield]
22546          *      5) + UnaryExpression[?yield]
22547          *      6) - UnaryExpression[?yield]
22548          *      7) ~ UnaryExpression[?yield]
22549          *      8) ! UnaryExpression[?yield]
22550          *      9) [+Await] await UnaryExpression[?yield]
22551          */
22552         function parseSimpleUnaryExpression() {
22553             switch (token()) {
22554                 case 39 /* PlusToken */:
22555                 case 40 /* MinusToken */:
22556                 case 54 /* TildeToken */:
22557                 case 53 /* ExclamationToken */:
22558                     return parsePrefixUnaryExpression();
22559                 case 85 /* DeleteKeyword */:
22560                     return parseDeleteExpression();
22561                 case 108 /* TypeOfKeyword */:
22562                     return parseTypeOfExpression();
22563                 case 110 /* VoidKeyword */:
22564                     return parseVoidExpression();
22565                 case 29 /* LessThanToken */:
22566                     // This is modified UnaryExpression grammar in TypeScript
22567                     //  UnaryExpression (modified):
22568                     //      < type > UnaryExpression
22569                     return parseTypeAssertion();
22570                 case 127 /* AwaitKeyword */:
22571                     if (isAwaitExpression()) {
22572                         return parseAwaitExpression();
22573                     }
22574                 // falls through
22575                 default:
22576                     return parseUpdateExpression();
22577             }
22578         }
22579         /**
22580          * Check if the current token can possibly be an ES7 increment expression.
22581          *
22582          * ES7 UpdateExpression:
22583          *      LeftHandSideExpression[?Yield]
22584          *      LeftHandSideExpression[?Yield][no LineTerminator here]++
22585          *      LeftHandSideExpression[?Yield][no LineTerminator here]--
22586          *      ++LeftHandSideExpression[?Yield]
22587          *      --LeftHandSideExpression[?Yield]
22588          */
22589         function isUpdateExpression() {
22590             // This function is called inside parseUnaryExpression to decide
22591             // whether to call parseSimpleUnaryExpression or call parseUpdateExpression directly
22592             switch (token()) {
22593                 case 39 /* PlusToken */:
22594                 case 40 /* MinusToken */:
22595                 case 54 /* TildeToken */:
22596                 case 53 /* ExclamationToken */:
22597                 case 85 /* DeleteKeyword */:
22598                 case 108 /* TypeOfKeyword */:
22599                 case 110 /* VoidKeyword */:
22600                 case 127 /* AwaitKeyword */:
22601                     return false;
22602                 case 29 /* LessThanToken */:
22603                     // If we are not in JSX context, we are parsing TypeAssertion which is an UnaryExpression
22604                     if (sourceFile.languageVariant !== 1 /* JSX */) {
22605                         return false;
22606                     }
22607                 // We are in JSX context and the token is part of JSXElement.
22608                 // falls through
22609                 default:
22610                     return true;
22611             }
22612         }
22613         /**
22614          * Parse ES7 UpdateExpression. UpdateExpression is used instead of ES6's PostFixExpression.
22615          *
22616          * ES7 UpdateExpression[yield]:
22617          *      1) LeftHandSideExpression[?yield]
22618          *      2) LeftHandSideExpression[?yield] [[no LineTerminator here]]++
22619          *      3) LeftHandSideExpression[?yield] [[no LineTerminator here]]--
22620          *      4) ++LeftHandSideExpression[?yield]
22621          *      5) --LeftHandSideExpression[?yield]
22622          * In TypeScript (2), (3) are parsed as PostfixUnaryExpression. (4), (5) are parsed as PrefixUnaryExpression
22623          */
22624         function parseUpdateExpression() {
22625             if (token() === 45 /* PlusPlusToken */ || token() === 46 /* MinusMinusToken */) {
22626                 var node = createNode(207 /* PrefixUnaryExpression */);
22627                 node.operator = token();
22628                 nextToken();
22629                 node.operand = parseLeftHandSideExpressionOrHigher();
22630                 return finishNode(node);
22631             }
22632             else if (sourceFile.languageVariant === 1 /* JSX */ && token() === 29 /* LessThanToken */ && lookAhead(nextTokenIsIdentifierOrKeywordOrGreaterThan)) {
22633                 // JSXElement is part of primaryExpression
22634                 return parseJsxElementOrSelfClosingElementOrFragment(/*inExpressionContext*/ true);
22635             }
22636             var expression = parseLeftHandSideExpressionOrHigher();
22637             ts.Debug.assert(ts.isLeftHandSideExpression(expression));
22638             if ((token() === 45 /* PlusPlusToken */ || token() === 46 /* MinusMinusToken */) && !scanner.hasPrecedingLineBreak()) {
22639                 var node = createNode(208 /* PostfixUnaryExpression */, expression.pos);
22640                 node.operand = expression;
22641                 node.operator = token();
22642                 nextToken();
22643                 return finishNode(node);
22644             }
22645             return expression;
22646         }
22647         function parseLeftHandSideExpressionOrHigher() {
22648             // Original Ecma:
22649             // LeftHandSideExpression: See 11.2
22650             //      NewExpression
22651             //      CallExpression
22652             //
22653             // Our simplification:
22654             //
22655             // LeftHandSideExpression: See 11.2
22656             //      MemberExpression
22657             //      CallExpression
22658             //
22659             // See comment in parseMemberExpressionOrHigher on how we replaced NewExpression with
22660             // MemberExpression to make our lives easier.
22661             //
22662             // to best understand the below code, it's important to see how CallExpression expands
22663             // out into its own productions:
22664             //
22665             // CallExpression:
22666             //      MemberExpression Arguments
22667             //      CallExpression Arguments
22668             //      CallExpression[Expression]
22669             //      CallExpression.IdentifierName
22670             //      import (AssignmentExpression)
22671             //      super Arguments
22672             //      super.IdentifierName
22673             //
22674             // Because of the recursion in these calls, we need to bottom out first. There are three
22675             // bottom out states we can run into: 1) We see 'super' which must start either of
22676             // the last two CallExpression productions. 2) We see 'import' which must start import call.
22677             // 3)we have a MemberExpression which either completes the LeftHandSideExpression,
22678             // or starts the beginning of the first four CallExpression productions.
22679             var expression;
22680             if (token() === 96 /* ImportKeyword */) {
22681                 if (lookAhead(nextTokenIsOpenParenOrLessThan)) {
22682                     // We don't want to eagerly consume all import keyword as import call expression so we look ahead to find "("
22683                     // For example:
22684                     //      var foo3 = require("subfolder
22685                     //      import * as foo1 from "module-from-node
22686                     // We want this import to be a statement rather than import call expression
22687                     sourceFile.flags |= 1048576 /* PossiblyContainsDynamicImport */;
22688                     expression = parseTokenNode();
22689                 }
22690                 else if (lookAhead(nextTokenIsDot)) {
22691                     // This is an 'import.*' metaproperty (i.e. 'import.meta')
22692                     var fullStart = scanner.getStartPos();
22693                     nextToken(); // advance past the 'import'
22694                     nextToken(); // advance past the dot
22695                     var node = createNode(219 /* MetaProperty */, fullStart);
22696                     node.keywordToken = 96 /* ImportKeyword */;
22697                     node.name = parseIdentifierName();
22698                     expression = finishNode(node);
22699                     sourceFile.flags |= 2097152 /* PossiblyContainsImportMeta */;
22700                 }
22701                 else {
22702                     expression = parseMemberExpressionOrHigher();
22703                 }
22704             }
22705             else {
22706                 expression = token() === 102 /* SuperKeyword */ ? parseSuperExpression() : parseMemberExpressionOrHigher();
22707             }
22708             // Now, we *may* be complete.  However, we might have consumed the start of a
22709             // CallExpression or OptionalExpression.  As such, we need to consume the rest
22710             // of it here to be complete.
22711             return parseCallExpressionRest(expression);
22712         }
22713         function parseMemberExpressionOrHigher() {
22714             // Note: to make our lives simpler, we decompose the NewExpression productions and
22715             // place ObjectCreationExpression and FunctionExpression into PrimaryExpression.
22716             // like so:
22717             //
22718             //   PrimaryExpression : See 11.1
22719             //      this
22720             //      Identifier
22721             //      Literal
22722             //      ArrayLiteral
22723             //      ObjectLiteral
22724             //      (Expression)
22725             //      FunctionExpression
22726             //      new MemberExpression Arguments?
22727             //
22728             //   MemberExpression : See 11.2
22729             //      PrimaryExpression
22730             //      MemberExpression[Expression]
22731             //      MemberExpression.IdentifierName
22732             //
22733             //   CallExpression : See 11.2
22734             //      MemberExpression
22735             //      CallExpression Arguments
22736             //      CallExpression[Expression]
22737             //      CallExpression.IdentifierName
22738             //
22739             // Technically this is ambiguous.  i.e. CallExpression defines:
22740             //
22741             //   CallExpression:
22742             //      CallExpression Arguments
22743             //
22744             // If you see: "new Foo()"
22745             //
22746             // Then that could be treated as a single ObjectCreationExpression, or it could be
22747             // treated as the invocation of "new Foo".  We disambiguate that in code (to match
22748             // the original grammar) by making sure that if we see an ObjectCreationExpression
22749             // we always consume arguments if they are there. So we treat "new Foo()" as an
22750             // object creation only, and not at all as an invocation.  Another way to think
22751             // about this is that for every "new" that we see, we will consume an argument list if
22752             // it is there as part of the *associated* object creation node.  Any additional
22753             // argument lists we see, will become invocation expressions.
22754             //
22755             // Because there are no other places in the grammar now that refer to FunctionExpression
22756             // or ObjectCreationExpression, it is safe to push down into the PrimaryExpression
22757             // production.
22758             //
22759             // Because CallExpression and MemberExpression are left recursive, we need to bottom out
22760             // of the recursion immediately.  So we parse out a primary expression to start with.
22761             var expression = parsePrimaryExpression();
22762             return parseMemberExpressionRest(expression, /*allowOptionalChain*/ true);
22763         }
22764         function parseSuperExpression() {
22765             var expression = parseTokenNode();
22766             if (token() === 29 /* LessThanToken */) {
22767                 var startPos = getNodePos();
22768                 var typeArguments = tryParse(parseTypeArgumentsInExpression);
22769                 if (typeArguments !== undefined) {
22770                     parseErrorAt(startPos, getNodePos(), ts.Diagnostics.super_may_not_use_type_arguments);
22771                 }
22772             }
22773             if (token() === 20 /* OpenParenToken */ || token() === 24 /* DotToken */ || token() === 22 /* OpenBracketToken */) {
22774                 return expression;
22775             }
22776             // If we have seen "super" it must be followed by '(' or '.'.
22777             // If it wasn't then just try to parse out a '.' and report an error.
22778             var node = createNode(194 /* PropertyAccessExpression */, expression.pos);
22779             node.expression = expression;
22780             parseExpectedToken(24 /* DotToken */, ts.Diagnostics.super_must_be_followed_by_an_argument_list_or_member_access);
22781             // private names will never work with `super` (`super.#foo`), but that's a semantic error, not syntactic
22782             node.name = parseRightSideOfDot(/*allowIdentifierNames*/ true, /*allowPrivateIdentifiers*/ true);
22783             return finishNode(node);
22784         }
22785         function parseJsxElementOrSelfClosingElementOrFragment(inExpressionContext) {
22786             var opening = parseJsxOpeningOrSelfClosingElementOrOpeningFragment(inExpressionContext);
22787             var result;
22788             if (opening.kind === 268 /* JsxOpeningElement */) {
22789                 var node = createNode(266 /* JsxElement */, opening.pos);
22790                 node.openingElement = opening;
22791                 node.children = parseJsxChildren(node.openingElement);
22792                 node.closingElement = parseJsxClosingElement(inExpressionContext);
22793                 if (!tagNamesAreEquivalent(node.openingElement.tagName, node.closingElement.tagName)) {
22794                     parseErrorAtRange(node.closingElement, ts.Diagnostics.Expected_corresponding_JSX_closing_tag_for_0, ts.getTextOfNodeFromSourceText(sourceText, node.openingElement.tagName));
22795                 }
22796                 result = finishNode(node);
22797             }
22798             else if (opening.kind === 271 /* JsxOpeningFragment */) {
22799                 var node = createNode(270 /* JsxFragment */, opening.pos);
22800                 node.openingFragment = opening;
22801                 node.children = parseJsxChildren(node.openingFragment);
22802                 node.closingFragment = parseJsxClosingFragment(inExpressionContext);
22803                 result = finishNode(node);
22804             }
22805             else {
22806                 ts.Debug.assert(opening.kind === 267 /* JsxSelfClosingElement */);
22807                 // Nothing else to do for self-closing elements
22808                 result = opening;
22809             }
22810             // If the user writes the invalid code '<div></div><div></div>' in an expression context (i.e. not wrapped in
22811             // an enclosing tag), we'll naively try to parse   ^ this as a 'less than' operator and the remainder of the tag
22812             // as garbage, which will cause the formatter to badly mangle the JSX. Perform a speculative parse of a JSX
22813             // element if we see a < token so that we can wrap it in a synthetic binary expression so the formatter
22814             // does less damage and we can report a better error.
22815             // Since JSX elements are invalid < operands anyway, this lookahead parse will only occur in error scenarios
22816             // of one sort or another.
22817             if (inExpressionContext && token() === 29 /* LessThanToken */) {
22818                 var invalidElement = tryParse(function () { return parseJsxElementOrSelfClosingElementOrFragment(/*inExpressionContext*/ true); });
22819                 if (invalidElement) {
22820                     parseErrorAtCurrentToken(ts.Diagnostics.JSX_expressions_must_have_one_parent_element);
22821                     var badNode = createNode(209 /* BinaryExpression */, result.pos);
22822                     badNode.end = invalidElement.end;
22823                     badNode.left = result;
22824                     badNode.right = invalidElement;
22825                     badNode.operatorToken = createMissingNode(27 /* CommaToken */, /*reportAtCurrentPosition*/ false);
22826                     badNode.operatorToken.pos = badNode.operatorToken.end = badNode.right.pos;
22827                     return badNode;
22828                 }
22829             }
22830             return result;
22831         }
22832         function parseJsxText() {
22833             var node = createNode(11 /* JsxText */);
22834             node.text = scanner.getTokenValue();
22835             node.containsOnlyTriviaWhiteSpaces = currentToken === 12 /* JsxTextAllWhiteSpaces */;
22836             currentToken = scanner.scanJsxToken();
22837             return finishNode(node);
22838         }
22839         function parseJsxChild(openingTag, token) {
22840             switch (token) {
22841                 case 1 /* EndOfFileToken */:
22842                     // If we hit EOF, issue the error at the tag that lacks the closing element
22843                     // rather than at the end of the file (which is useless)
22844                     if (ts.isJsxOpeningFragment(openingTag)) {
22845                         parseErrorAtRange(openingTag, ts.Diagnostics.JSX_fragment_has_no_corresponding_closing_tag);
22846                     }
22847                     else {
22848                         // We want the error span to cover only 'Foo.Bar' in < Foo.Bar >
22849                         // or to cover only 'Foo' in < Foo >
22850                         var tag = openingTag.tagName;
22851                         var start = ts.skipTrivia(sourceText, tag.pos);
22852                         parseErrorAt(start, tag.end, ts.Diagnostics.JSX_element_0_has_no_corresponding_closing_tag, ts.getTextOfNodeFromSourceText(sourceText, openingTag.tagName));
22853                     }
22854                     return undefined;
22855                 case 30 /* LessThanSlashToken */:
22856                 case 7 /* ConflictMarkerTrivia */:
22857                     return undefined;
22858                 case 11 /* JsxText */:
22859                 case 12 /* JsxTextAllWhiteSpaces */:
22860                     return parseJsxText();
22861                 case 18 /* OpenBraceToken */:
22862                     return parseJsxExpression(/*inExpressionContext*/ false);
22863                 case 29 /* LessThanToken */:
22864                     return parseJsxElementOrSelfClosingElementOrFragment(/*inExpressionContext*/ false);
22865                 default:
22866                     return ts.Debug.assertNever(token);
22867             }
22868         }
22869         function parseJsxChildren(openingTag) {
22870             var list = [];
22871             var listPos = getNodePos();
22872             var saveParsingContext = parsingContext;
22873             parsingContext |= 1 << 14 /* JsxChildren */;
22874             while (true) {
22875                 var child = parseJsxChild(openingTag, currentToken = scanner.reScanJsxToken());
22876                 if (!child)
22877                     break;
22878                 list.push(child);
22879             }
22880             parsingContext = saveParsingContext;
22881             return createNodeArray(list, listPos);
22882         }
22883         function parseJsxAttributes() {
22884             var jsxAttributes = createNode(274 /* JsxAttributes */);
22885             jsxAttributes.properties = parseList(13 /* JsxAttributes */, parseJsxAttribute);
22886             return finishNode(jsxAttributes);
22887         }
22888         function parseJsxOpeningOrSelfClosingElementOrOpeningFragment(inExpressionContext) {
22889             var fullStart = scanner.getStartPos();
22890             parseExpected(29 /* LessThanToken */);
22891             if (token() === 31 /* GreaterThanToken */) {
22892                 // See below for explanation of scanJsxText
22893                 var node_1 = createNode(271 /* JsxOpeningFragment */, fullStart);
22894                 scanJsxText();
22895                 return finishNode(node_1);
22896             }
22897             var tagName = parseJsxElementName();
22898             var typeArguments = tryParseTypeArguments();
22899             var attributes = parseJsxAttributes();
22900             var node;
22901             if (token() === 31 /* GreaterThanToken */) {
22902                 // Closing tag, so scan the immediately-following text with the JSX scanning instead
22903                 // of regular scanning to avoid treating illegal characters (e.g. '#') as immediate
22904                 // scanning errors
22905                 node = createNode(268 /* JsxOpeningElement */, fullStart);
22906                 scanJsxText();
22907             }
22908             else {
22909                 parseExpected(43 /* SlashToken */);
22910                 if (inExpressionContext) {
22911                     parseExpected(31 /* GreaterThanToken */);
22912                 }
22913                 else {
22914                     parseExpected(31 /* GreaterThanToken */, /*diagnostic*/ undefined, /*shouldAdvance*/ false);
22915                     scanJsxText();
22916                 }
22917                 node = createNode(267 /* JsxSelfClosingElement */, fullStart);
22918             }
22919             node.tagName = tagName;
22920             node.typeArguments = typeArguments;
22921             node.attributes = attributes;
22922             return finishNode(node);
22923         }
22924         function parseJsxElementName() {
22925             scanJsxIdentifier();
22926             // JsxElement can have name in the form of
22927             //      propertyAccessExpression
22928             //      primaryExpression in the form of an identifier and "this" keyword
22929             // We can't just simply use parseLeftHandSideExpressionOrHigher because then we will start consider class,function etc as a keyword
22930             // We only want to consider "this" as a primaryExpression
22931             var expression = token() === 104 /* ThisKeyword */ ?
22932                 parseTokenNode() : parseIdentifierName();
22933             while (parseOptional(24 /* DotToken */)) {
22934                 var propertyAccess = createNode(194 /* PropertyAccessExpression */, expression.pos);
22935                 propertyAccess.expression = expression;
22936                 propertyAccess.name = parseRightSideOfDot(/*allowIdentifierNames*/ true, /*allowPrivateIdentifiers*/ false);
22937                 expression = finishNode(propertyAccess);
22938             }
22939             return expression;
22940         }
22941         function parseJsxExpression(inExpressionContext) {
22942             var node = createNode(276 /* JsxExpression */);
22943             if (!parseExpected(18 /* OpenBraceToken */)) {
22944                 return undefined;
22945             }
22946             if (token() !== 19 /* CloseBraceToken */) {
22947                 node.dotDotDotToken = parseOptionalToken(25 /* DotDotDotToken */);
22948                 // Only an AssignmentExpression is valid here per the JSX spec,
22949                 // but we can unambiguously parse a comma sequence and provide
22950                 // a better error message in grammar checking.
22951                 node.expression = parseExpression();
22952             }
22953             if (inExpressionContext) {
22954                 parseExpected(19 /* CloseBraceToken */);
22955             }
22956             else {
22957                 if (parseExpected(19 /* CloseBraceToken */, /*message*/ undefined, /*shouldAdvance*/ false)) {
22958                     scanJsxText();
22959                 }
22960             }
22961             return finishNode(node);
22962         }
22963         function parseJsxAttribute() {
22964             if (token() === 18 /* OpenBraceToken */) {
22965                 return parseJsxSpreadAttribute();
22966             }
22967             scanJsxIdentifier();
22968             var node = createNode(273 /* JsxAttribute */);
22969             node.name = parseIdentifierName();
22970             if (token() === 62 /* EqualsToken */) {
22971                 switch (scanJsxAttributeValue()) {
22972                     case 10 /* StringLiteral */:
22973                         node.initializer = parseLiteralNode();
22974                         break;
22975                     default:
22976                         node.initializer = parseJsxExpression(/*inExpressionContext*/ true);
22977                         break;
22978                 }
22979             }
22980             return finishNode(node);
22981         }
22982         function parseJsxSpreadAttribute() {
22983             var node = createNode(275 /* JsxSpreadAttribute */);
22984             parseExpected(18 /* OpenBraceToken */);
22985             parseExpected(25 /* DotDotDotToken */);
22986             node.expression = parseExpression();
22987             parseExpected(19 /* CloseBraceToken */);
22988             return finishNode(node);
22989         }
22990         function parseJsxClosingElement(inExpressionContext) {
22991             var node = createNode(269 /* JsxClosingElement */);
22992             parseExpected(30 /* LessThanSlashToken */);
22993             node.tagName = parseJsxElementName();
22994             if (inExpressionContext) {
22995                 parseExpected(31 /* GreaterThanToken */);
22996             }
22997             else {
22998                 parseExpected(31 /* GreaterThanToken */, /*diagnostic*/ undefined, /*shouldAdvance*/ false);
22999                 scanJsxText();
23000             }
23001             return finishNode(node);
23002         }
23003         function parseJsxClosingFragment(inExpressionContext) {
23004             var node = createNode(272 /* JsxClosingFragment */);
23005             parseExpected(30 /* LessThanSlashToken */);
23006             if (ts.tokenIsIdentifierOrKeyword(token())) {
23007                 parseErrorAtRange(parseJsxElementName(), ts.Diagnostics.Expected_corresponding_closing_tag_for_JSX_fragment);
23008             }
23009             if (inExpressionContext) {
23010                 parseExpected(31 /* GreaterThanToken */);
23011             }
23012             else {
23013                 parseExpected(31 /* GreaterThanToken */, /*diagnostic*/ undefined, /*shouldAdvance*/ false);
23014                 scanJsxText();
23015             }
23016             return finishNode(node);
23017         }
23018         function parseTypeAssertion() {
23019             var node = createNode(199 /* TypeAssertionExpression */);
23020             parseExpected(29 /* LessThanToken */);
23021             node.type = parseType();
23022             parseExpected(31 /* GreaterThanToken */);
23023             node.expression = parseSimpleUnaryExpression();
23024             return finishNode(node);
23025         }
23026         function nextTokenIsIdentifierOrKeywordOrOpenBracketOrTemplate() {
23027             nextToken();
23028             return ts.tokenIsIdentifierOrKeyword(token())
23029                 || token() === 22 /* OpenBracketToken */
23030                 || isTemplateStartOfTaggedTemplate();
23031         }
23032         function isStartOfOptionalPropertyOrElementAccessChain() {
23033             return token() === 28 /* QuestionDotToken */
23034                 && lookAhead(nextTokenIsIdentifierOrKeywordOrOpenBracketOrTemplate);
23035         }
23036         function tryReparseOptionalChain(node) {
23037             if (node.flags & 32 /* OptionalChain */) {
23038                 return true;
23039             }
23040             // check for an optional chain in a non-null expression
23041             if (ts.isNonNullExpression(node)) {
23042                 var expr = node.expression;
23043                 while (ts.isNonNullExpression(expr) && !(expr.flags & 32 /* OptionalChain */)) {
23044                     expr = expr.expression;
23045                 }
23046                 if (expr.flags & 32 /* OptionalChain */) {
23047                     // this is part of an optional chain. Walk down from `node` to `expression` and set the flag.
23048                     while (ts.isNonNullExpression(node)) {
23049                         node.flags |= 32 /* OptionalChain */;
23050                         node = node.expression;
23051                     }
23052                     return true;
23053                 }
23054             }
23055             return false;
23056         }
23057         function parsePropertyAccessExpressionRest(expression, questionDotToken) {
23058             var propertyAccess = createNode(194 /* PropertyAccessExpression */, expression.pos);
23059             propertyAccess.expression = expression;
23060             propertyAccess.questionDotToken = questionDotToken;
23061             propertyAccess.name = parseRightSideOfDot(/*allowIdentifierNames*/ true, /*allowPrivateIdentifiers*/ true);
23062             if (questionDotToken || tryReparseOptionalChain(expression)) {
23063                 propertyAccess.flags |= 32 /* OptionalChain */;
23064                 if (ts.isPrivateIdentifier(propertyAccess.name)) {
23065                     parseErrorAtRange(propertyAccess.name, ts.Diagnostics.An_optional_chain_cannot_contain_private_identifiers);
23066                 }
23067             }
23068             return finishNode(propertyAccess);
23069         }
23070         function parseElementAccessExpressionRest(expression, questionDotToken) {
23071             var indexedAccess = createNode(195 /* ElementAccessExpression */, expression.pos);
23072             indexedAccess.expression = expression;
23073             indexedAccess.questionDotToken = questionDotToken;
23074             if (token() === 23 /* CloseBracketToken */) {
23075                 indexedAccess.argumentExpression = createMissingNode(75 /* Identifier */, /*reportAtCurrentPosition*/ true, ts.Diagnostics.An_element_access_expression_should_take_an_argument);
23076             }
23077             else {
23078                 var argument = allowInAnd(parseExpression);
23079                 if (ts.isStringOrNumericLiteralLike(argument)) {
23080                     argument.text = internIdentifier(argument.text);
23081                 }
23082                 indexedAccess.argumentExpression = argument;
23083             }
23084             parseExpected(23 /* CloseBracketToken */);
23085             if (questionDotToken || tryReparseOptionalChain(expression)) {
23086                 indexedAccess.flags |= 32 /* OptionalChain */;
23087             }
23088             return finishNode(indexedAccess);
23089         }
23090         function parseMemberExpressionRest(expression, allowOptionalChain) {
23091             while (true) {
23092                 var questionDotToken = void 0;
23093                 var isPropertyAccess = false;
23094                 if (allowOptionalChain && isStartOfOptionalPropertyOrElementAccessChain()) {
23095                     questionDotToken = parseExpectedToken(28 /* QuestionDotToken */);
23096                     isPropertyAccess = ts.tokenIsIdentifierOrKeyword(token());
23097                 }
23098                 else {
23099                     isPropertyAccess = parseOptional(24 /* DotToken */);
23100                 }
23101                 if (isPropertyAccess) {
23102                     expression = parsePropertyAccessExpressionRest(expression, questionDotToken);
23103                     continue;
23104                 }
23105                 if (!questionDotToken && token() === 53 /* ExclamationToken */ && !scanner.hasPrecedingLineBreak()) {
23106                     nextToken();
23107                     var nonNullExpression = createNode(218 /* NonNullExpression */, expression.pos);
23108                     nonNullExpression.expression = expression;
23109                     expression = finishNode(nonNullExpression);
23110                     continue;
23111                 }
23112                 // when in the [Decorator] context, we do not parse ElementAccess as it could be part of a ComputedPropertyName
23113                 if ((questionDotToken || !inDecoratorContext()) && parseOptional(22 /* OpenBracketToken */)) {
23114                     expression = parseElementAccessExpressionRest(expression, questionDotToken);
23115                     continue;
23116                 }
23117                 if (isTemplateStartOfTaggedTemplate()) {
23118                     expression = parseTaggedTemplateRest(expression, questionDotToken, /*typeArguments*/ undefined);
23119                     continue;
23120                 }
23121                 return expression;
23122             }
23123         }
23124         function isTemplateStartOfTaggedTemplate() {
23125             return token() === 14 /* NoSubstitutionTemplateLiteral */ || token() === 15 /* TemplateHead */;
23126         }
23127         function parseTaggedTemplateRest(tag, questionDotToken, typeArguments) {
23128             var tagExpression = createNode(198 /* TaggedTemplateExpression */, tag.pos);
23129             tagExpression.tag = tag;
23130             tagExpression.questionDotToken = questionDotToken;
23131             tagExpression.typeArguments = typeArguments;
23132             tagExpression.template = token() === 14 /* NoSubstitutionTemplateLiteral */
23133                 ? (reScanTemplateHeadOrNoSubstitutionTemplate(), parseLiteralNode())
23134                 : parseTemplateExpression(/*isTaggedTemplate*/ true);
23135             if (questionDotToken || tag.flags & 32 /* OptionalChain */) {
23136                 tagExpression.flags |= 32 /* OptionalChain */;
23137             }
23138             return finishNode(tagExpression);
23139         }
23140         function parseCallExpressionRest(expression) {
23141             while (true) {
23142                 expression = parseMemberExpressionRest(expression, /*allowOptionalChain*/ true);
23143                 var questionDotToken = parseOptionalToken(28 /* QuestionDotToken */);
23144                 // handle 'foo<<T>()'
23145                 if (token() === 29 /* LessThanToken */ || token() === 47 /* LessThanLessThanToken */) {
23146                     // See if this is the start of a generic invocation.  If so, consume it and
23147                     // keep checking for postfix expressions.  Otherwise, it's just a '<' that's
23148                     // part of an arithmetic expression.  Break out so we consume it higher in the
23149                     // stack.
23150                     var typeArguments = tryParse(parseTypeArgumentsInExpression);
23151                     if (typeArguments) {
23152                         if (isTemplateStartOfTaggedTemplate()) {
23153                             expression = parseTaggedTemplateRest(expression, questionDotToken, typeArguments);
23154                             continue;
23155                         }
23156                         var callExpr = createNode(196 /* CallExpression */, expression.pos);
23157                         callExpr.expression = expression;
23158                         callExpr.questionDotToken = questionDotToken;
23159                         callExpr.typeArguments = typeArguments;
23160                         callExpr.arguments = parseArgumentList();
23161                         if (questionDotToken || tryReparseOptionalChain(expression)) {
23162                             callExpr.flags |= 32 /* OptionalChain */;
23163                         }
23164                         expression = finishNode(callExpr);
23165                         continue;
23166                     }
23167                 }
23168                 else if (token() === 20 /* OpenParenToken */) {
23169                     var callExpr = createNode(196 /* CallExpression */, expression.pos);
23170                     callExpr.expression = expression;
23171                     callExpr.questionDotToken = questionDotToken;
23172                     callExpr.arguments = parseArgumentList();
23173                     if (questionDotToken || tryReparseOptionalChain(expression)) {
23174                         callExpr.flags |= 32 /* OptionalChain */;
23175                     }
23176                     expression = finishNode(callExpr);
23177                     continue;
23178                 }
23179                 if (questionDotToken) {
23180                     // We failed to parse anything, so report a missing identifier here.
23181                     var propertyAccess = createNode(194 /* PropertyAccessExpression */, expression.pos);
23182                     propertyAccess.expression = expression;
23183                     propertyAccess.questionDotToken = questionDotToken;
23184                     propertyAccess.name = createMissingNode(75 /* Identifier */, /*reportAtCurrentPosition*/ false, ts.Diagnostics.Identifier_expected);
23185                     propertyAccess.flags |= 32 /* OptionalChain */;
23186                     expression = finishNode(propertyAccess);
23187                 }
23188                 break;
23189             }
23190             return expression;
23191         }
23192         function parseArgumentList() {
23193             parseExpected(20 /* OpenParenToken */);
23194             var result = parseDelimitedList(11 /* ArgumentExpressions */, parseArgumentExpression);
23195             parseExpected(21 /* CloseParenToken */);
23196             return result;
23197         }
23198         function parseTypeArgumentsInExpression() {
23199             if (reScanLessThanToken() !== 29 /* LessThanToken */) {
23200                 return undefined;
23201             }
23202             nextToken();
23203             var typeArguments = parseDelimitedList(20 /* TypeArguments */, parseType);
23204             if (!parseExpected(31 /* GreaterThanToken */)) {
23205                 // If it doesn't have the closing `>` then it's definitely not an type argument list.
23206                 return undefined;
23207             }
23208             // If we have a '<', then only parse this as a argument list if the type arguments
23209             // are complete and we have an open paren.  if we don't, rewind and return nothing.
23210             return typeArguments && canFollowTypeArgumentsInExpression()
23211                 ? typeArguments
23212                 : undefined;
23213         }
23214         function canFollowTypeArgumentsInExpression() {
23215             switch (token()) {
23216                 case 20 /* OpenParenToken */: // foo<x>(
23217                 case 14 /* NoSubstitutionTemplateLiteral */: // foo<T> `...`
23218                 case 15 /* TemplateHead */: // foo<T> `...${100}...`
23219                 // these are the only tokens can legally follow a type argument
23220                 // list. So we definitely want to treat them as type arg lists.
23221                 // falls through
23222                 case 24 /* DotToken */: // foo<x>.
23223                 case 21 /* CloseParenToken */: // foo<x>)
23224                 case 23 /* CloseBracketToken */: // foo<x>]
23225                 case 58 /* ColonToken */: // foo<x>:
23226                 case 26 /* SemicolonToken */: // foo<x>;
23227                 case 57 /* QuestionToken */: // foo<x>?
23228                 case 34 /* EqualsEqualsToken */: // foo<x> ==
23229                 case 36 /* EqualsEqualsEqualsToken */: // foo<x> ===
23230                 case 35 /* ExclamationEqualsToken */: // foo<x> !=
23231                 case 37 /* ExclamationEqualsEqualsToken */: // foo<x> !==
23232                 case 55 /* AmpersandAmpersandToken */: // foo<x> &&
23233                 case 56 /* BarBarToken */: // foo<x> ||
23234                 case 60 /* QuestionQuestionToken */: // foo<x> ??
23235                 case 52 /* CaretToken */: // foo<x> ^
23236                 case 50 /* AmpersandToken */: // foo<x> &
23237                 case 51 /* BarToken */: // foo<x> |
23238                 case 19 /* CloseBraceToken */: // foo<x> }
23239                 case 1 /* EndOfFileToken */: // foo<x>
23240                     // these cases can't legally follow a type arg list.  However, they're not legal
23241                     // expressions either.  The user is probably in the middle of a generic type. So
23242                     // treat it as such.
23243                     return true;
23244                 case 27 /* CommaToken */: // foo<x>,
23245                 case 18 /* OpenBraceToken */: // foo<x> {
23246                 // We don't want to treat these as type arguments.  Otherwise we'll parse this
23247                 // as an invocation expression.  Instead, we want to parse out the expression
23248                 // in isolation from the type arguments.
23249                 // falls through
23250                 default:
23251                     // Anything else treat as an expression.
23252                     return false;
23253             }
23254         }
23255         function parsePrimaryExpression() {
23256             switch (token()) {
23257                 case 8 /* NumericLiteral */:
23258                 case 9 /* BigIntLiteral */:
23259                 case 10 /* StringLiteral */:
23260                 case 14 /* NoSubstitutionTemplateLiteral */:
23261                     return parseLiteralNode();
23262                 case 104 /* ThisKeyword */:
23263                 case 102 /* SuperKeyword */:
23264                 case 100 /* NullKeyword */:
23265                 case 106 /* TrueKeyword */:
23266                 case 91 /* FalseKeyword */:
23267                     return parseTokenNode();
23268                 case 20 /* OpenParenToken */:
23269                     return parseParenthesizedExpression();
23270                 case 22 /* OpenBracketToken */:
23271                     return parseArrayLiteralExpression();
23272                 case 18 /* OpenBraceToken */:
23273                     return parseObjectLiteralExpression();
23274                 case 126 /* AsyncKeyword */:
23275                     // Async arrow functions are parsed earlier in parseAssignmentExpressionOrHigher.
23276                     // If we encounter `async [no LineTerminator here] function` then this is an async
23277                     // function; otherwise, its an identifier.
23278                     if (!lookAhead(nextTokenIsFunctionKeywordOnSameLine)) {
23279                         break;
23280                     }
23281                     return parseFunctionExpression();
23282                 case 80 /* ClassKeyword */:
23283                     return parseClassExpression();
23284                 case 94 /* FunctionKeyword */:
23285                     return parseFunctionExpression();
23286                 case 99 /* NewKeyword */:
23287                     return parseNewExpressionOrNewDotTarget();
23288                 case 43 /* SlashToken */:
23289                 case 67 /* SlashEqualsToken */:
23290                     if (reScanSlashToken() === 13 /* RegularExpressionLiteral */) {
23291                         return parseLiteralNode();
23292                     }
23293                     break;
23294                 case 15 /* TemplateHead */:
23295                     return parseTemplateExpression(/* isTaggedTemplate */ false);
23296             }
23297             return parseIdentifier(ts.Diagnostics.Expression_expected);
23298         }
23299         function parseParenthesizedExpression() {
23300             var node = createNodeWithJSDoc(200 /* ParenthesizedExpression */);
23301             parseExpected(20 /* OpenParenToken */);
23302             node.expression = allowInAnd(parseExpression);
23303             parseExpected(21 /* CloseParenToken */);
23304             return finishNode(node);
23305         }
23306         function parseSpreadElement() {
23307             var node = createNode(213 /* SpreadElement */);
23308             parseExpected(25 /* DotDotDotToken */);
23309             node.expression = parseAssignmentExpressionOrHigher();
23310             return finishNode(node);
23311         }
23312         function parseArgumentOrArrayLiteralElement() {
23313             return token() === 25 /* DotDotDotToken */ ? parseSpreadElement() :
23314                 token() === 27 /* CommaToken */ ? createNode(215 /* OmittedExpression */) :
23315                     parseAssignmentExpressionOrHigher();
23316         }
23317         function parseArgumentExpression() {
23318             return doOutsideOfContext(disallowInAndDecoratorContext, parseArgumentOrArrayLiteralElement);
23319         }
23320         function parseArrayLiteralExpression() {
23321             var node = createNode(192 /* ArrayLiteralExpression */);
23322             parseExpected(22 /* OpenBracketToken */);
23323             if (scanner.hasPrecedingLineBreak()) {
23324                 node.multiLine = true;
23325             }
23326             node.elements = parseDelimitedList(15 /* ArrayLiteralMembers */, parseArgumentOrArrayLiteralElement);
23327             parseExpected(23 /* CloseBracketToken */);
23328             return finishNode(node);
23329         }
23330         function parseObjectLiteralElement() {
23331             var node = createNodeWithJSDoc(0 /* Unknown */);
23332             if (parseOptionalToken(25 /* DotDotDotToken */)) {
23333                 node.kind = 283 /* SpreadAssignment */;
23334                 node.expression = parseAssignmentExpressionOrHigher();
23335                 return finishNode(node);
23336             }
23337             node.decorators = parseDecorators();
23338             node.modifiers = parseModifiers();
23339             if (parseContextualModifier(131 /* GetKeyword */)) {
23340                 return parseAccessorDeclaration(node, 163 /* GetAccessor */);
23341             }
23342             if (parseContextualModifier(142 /* SetKeyword */)) {
23343                 return parseAccessorDeclaration(node, 164 /* SetAccessor */);
23344             }
23345             var asteriskToken = parseOptionalToken(41 /* AsteriskToken */);
23346             var tokenIsIdentifier = isIdentifier();
23347             node.name = parsePropertyName();
23348             // Disallowing of optional property assignments and definite assignment assertion happens in the grammar checker.
23349             node.questionToken = parseOptionalToken(57 /* QuestionToken */);
23350             node.exclamationToken = parseOptionalToken(53 /* ExclamationToken */);
23351             if (asteriskToken || token() === 20 /* OpenParenToken */ || token() === 29 /* LessThanToken */) {
23352                 return parseMethodDeclaration(node, asteriskToken);
23353             }
23354             // check if it is short-hand property assignment or normal property assignment
23355             // NOTE: if token is EqualsToken it is interpreted as CoverInitializedName production
23356             // CoverInitializedName[Yield] :
23357             //     IdentifierReference[?Yield] Initializer[In, ?Yield]
23358             // this is necessary because ObjectLiteral productions are also used to cover grammar for ObjectAssignmentPattern
23359             var isShorthandPropertyAssignment = tokenIsIdentifier && (token() !== 58 /* ColonToken */);
23360             if (isShorthandPropertyAssignment) {
23361                 node.kind = 282 /* ShorthandPropertyAssignment */;
23362                 var equalsToken = parseOptionalToken(62 /* EqualsToken */);
23363                 if (equalsToken) {
23364                     node.equalsToken = equalsToken;
23365                     node.objectAssignmentInitializer = allowInAnd(parseAssignmentExpressionOrHigher);
23366                 }
23367             }
23368             else {
23369                 node.kind = 281 /* PropertyAssignment */;
23370                 parseExpected(58 /* ColonToken */);
23371                 node.initializer = allowInAnd(parseAssignmentExpressionOrHigher);
23372             }
23373             return finishNode(node);
23374         }
23375         function parseObjectLiteralExpression() {
23376             var node = createNode(193 /* ObjectLiteralExpression */);
23377             var openBracePosition = scanner.getTokenPos();
23378             parseExpected(18 /* OpenBraceToken */);
23379             if (scanner.hasPrecedingLineBreak()) {
23380                 node.multiLine = true;
23381             }
23382             node.properties = parseDelimitedList(12 /* ObjectLiteralMembers */, parseObjectLiteralElement, /*considerSemicolonAsDelimiter*/ true);
23383             if (!parseExpected(19 /* CloseBraceToken */)) {
23384                 var lastError = ts.lastOrUndefined(parseDiagnostics);
23385                 if (lastError && lastError.code === ts.Diagnostics._0_expected.code) {
23386                     ts.addRelatedInfo(lastError, ts.createFileDiagnostic(sourceFile, openBracePosition, 1, ts.Diagnostics.The_parser_expected_to_find_a_to_match_the_token_here));
23387                 }
23388             }
23389             return finishNode(node);
23390         }
23391         function parseFunctionExpression() {
23392             // GeneratorExpression:
23393             //      function* BindingIdentifier [Yield][opt](FormalParameters[Yield]){ GeneratorBody }
23394             //
23395             // FunctionExpression:
23396             //      function BindingIdentifier[opt](FormalParameters){ FunctionBody }
23397             var saveDecoratorContext = inDecoratorContext();
23398             if (saveDecoratorContext) {
23399                 setDecoratorContext(/*val*/ false);
23400             }
23401             var node = createNodeWithJSDoc(201 /* FunctionExpression */);
23402             node.modifiers = parseModifiers();
23403             parseExpected(94 /* FunctionKeyword */);
23404             node.asteriskToken = parseOptionalToken(41 /* AsteriskToken */);
23405             var isGenerator = node.asteriskToken ? 1 /* Yield */ : 0 /* None */;
23406             var isAsync = hasModifierOfKind(node, 126 /* AsyncKeyword */) ? 2 /* Await */ : 0 /* None */;
23407             node.name =
23408                 isGenerator && isAsync ? doInYieldAndAwaitContext(parseOptionalIdentifier) :
23409                     isGenerator ? doInYieldContext(parseOptionalIdentifier) :
23410                         isAsync ? doInAwaitContext(parseOptionalIdentifier) :
23411                             parseOptionalIdentifier();
23412             fillSignature(58 /* ColonToken */, isGenerator | isAsync, node);
23413             node.body = parseFunctionBlock(isGenerator | isAsync);
23414             if (saveDecoratorContext) {
23415                 setDecoratorContext(/*val*/ true);
23416             }
23417             return finishNode(node);
23418         }
23419         function parseOptionalIdentifier() {
23420             return isIdentifier() ? parseIdentifier() : undefined;
23421         }
23422         function parseNewExpressionOrNewDotTarget() {
23423             var fullStart = scanner.getStartPos();
23424             parseExpected(99 /* NewKeyword */);
23425             if (parseOptional(24 /* DotToken */)) {
23426                 var node_2 = createNode(219 /* MetaProperty */, fullStart);
23427                 node_2.keywordToken = 99 /* NewKeyword */;
23428                 node_2.name = parseIdentifierName();
23429                 return finishNode(node_2);
23430             }
23431             var expression = parsePrimaryExpression();
23432             var typeArguments;
23433             while (true) {
23434                 expression = parseMemberExpressionRest(expression, /*allowOptionalChain*/ false);
23435                 typeArguments = tryParse(parseTypeArgumentsInExpression);
23436                 if (isTemplateStartOfTaggedTemplate()) {
23437                     ts.Debug.assert(!!typeArguments, "Expected a type argument list; all plain tagged template starts should be consumed in 'parseMemberExpressionRest'");
23438                     expression = parseTaggedTemplateRest(expression, /*optionalChain*/ undefined, typeArguments);
23439                     typeArguments = undefined;
23440                 }
23441                 break;
23442             }
23443             var node = createNode(197 /* NewExpression */, fullStart);
23444             node.expression = expression;
23445             node.typeArguments = typeArguments;
23446             if (token() === 20 /* OpenParenToken */) {
23447                 node.arguments = parseArgumentList();
23448             }
23449             else if (node.typeArguments) {
23450                 parseErrorAt(fullStart, scanner.getStartPos(), ts.Diagnostics.A_new_expression_with_type_arguments_must_always_be_followed_by_a_parenthesized_argument_list);
23451             }
23452             return finishNode(node);
23453         }
23454         // STATEMENTS
23455         function parseBlock(ignoreMissingOpenBrace, diagnosticMessage) {
23456             var node = createNode(223 /* Block */);
23457             var openBracePosition = scanner.getTokenPos();
23458             if (parseExpected(18 /* OpenBraceToken */, diagnosticMessage) || ignoreMissingOpenBrace) {
23459                 if (scanner.hasPrecedingLineBreak()) {
23460                     node.multiLine = true;
23461                 }
23462                 node.statements = parseList(1 /* BlockStatements */, parseStatement);
23463                 if (!parseExpected(19 /* CloseBraceToken */)) {
23464                     var lastError = ts.lastOrUndefined(parseDiagnostics);
23465                     if (lastError && lastError.code === ts.Diagnostics._0_expected.code) {
23466                         ts.addRelatedInfo(lastError, ts.createFileDiagnostic(sourceFile, openBracePosition, 1, ts.Diagnostics.The_parser_expected_to_find_a_to_match_the_token_here));
23467                     }
23468                 }
23469             }
23470             else {
23471                 node.statements = createMissingList();
23472             }
23473             return finishNode(node);
23474         }
23475         function parseFunctionBlock(flags, diagnosticMessage) {
23476             var savedYieldContext = inYieldContext();
23477             setYieldContext(!!(flags & 1 /* Yield */));
23478             var savedAwaitContext = inAwaitContext();
23479             setAwaitContext(!!(flags & 2 /* Await */));
23480             // We may be in a [Decorator] context when parsing a function expression or
23481             // arrow function. The body of the function is not in [Decorator] context.
23482             var saveDecoratorContext = inDecoratorContext();
23483             if (saveDecoratorContext) {
23484                 setDecoratorContext(/*val*/ false);
23485             }
23486             var block = parseBlock(!!(flags & 16 /* IgnoreMissingOpenBrace */), diagnosticMessage);
23487             if (saveDecoratorContext) {
23488                 setDecoratorContext(/*val*/ true);
23489             }
23490             setYieldContext(savedYieldContext);
23491             setAwaitContext(savedAwaitContext);
23492             return block;
23493         }
23494         function parseEmptyStatement() {
23495             var node = createNode(224 /* EmptyStatement */);
23496             parseExpected(26 /* SemicolonToken */);
23497             return finishNode(node);
23498         }
23499         function parseIfStatement() {
23500             var node = createNode(227 /* IfStatement */);
23501             parseExpected(95 /* IfKeyword */);
23502             parseExpected(20 /* OpenParenToken */);
23503             node.expression = allowInAnd(parseExpression);
23504             parseExpected(21 /* CloseParenToken */);
23505             node.thenStatement = parseStatement();
23506             node.elseStatement = parseOptional(87 /* ElseKeyword */) ? parseStatement() : undefined;
23507             return finishNode(node);
23508         }
23509         function parseDoStatement() {
23510             var node = createNode(228 /* DoStatement */);
23511             parseExpected(86 /* DoKeyword */);
23512             node.statement = parseStatement();
23513             parseExpected(111 /* WhileKeyword */);
23514             parseExpected(20 /* OpenParenToken */);
23515             node.expression = allowInAnd(parseExpression);
23516             parseExpected(21 /* CloseParenToken */);
23517             // From: https://mail.mozilla.org/pipermail/es-discuss/2011-August/016188.html
23518             // 157 min --- All allen at wirfs-brock.com CONF --- "do{;}while(false)false" prohibited in
23519             // spec but allowed in consensus reality. Approved -- this is the de-facto standard whereby
23520             //  do;while(0)x will have a semicolon inserted before x.
23521             parseOptional(26 /* SemicolonToken */);
23522             return finishNode(node);
23523         }
23524         function parseWhileStatement() {
23525             var node = createNode(229 /* WhileStatement */);
23526             parseExpected(111 /* WhileKeyword */);
23527             parseExpected(20 /* OpenParenToken */);
23528             node.expression = allowInAnd(parseExpression);
23529             parseExpected(21 /* CloseParenToken */);
23530             node.statement = parseStatement();
23531             return finishNode(node);
23532         }
23533         function parseForOrForInOrForOfStatement() {
23534             var pos = getNodePos();
23535             parseExpected(93 /* ForKeyword */);
23536             var awaitToken = parseOptionalToken(127 /* AwaitKeyword */);
23537             parseExpected(20 /* OpenParenToken */);
23538             var initializer;
23539             if (token() !== 26 /* SemicolonToken */) {
23540                 if (token() === 109 /* VarKeyword */ || token() === 115 /* LetKeyword */ || token() === 81 /* ConstKeyword */) {
23541                     initializer = parseVariableDeclarationList(/*inForStatementInitializer*/ true);
23542                 }
23543                 else {
23544                     initializer = disallowInAnd(parseExpression);
23545                 }
23546             }
23547             var forOrForInOrForOfStatement;
23548             if (awaitToken ? parseExpected(152 /* OfKeyword */) : parseOptional(152 /* OfKeyword */)) {
23549                 var forOfStatement = createNode(232 /* ForOfStatement */, pos);
23550                 forOfStatement.awaitModifier = awaitToken;
23551                 forOfStatement.initializer = initializer;
23552                 forOfStatement.expression = allowInAnd(parseAssignmentExpressionOrHigher);
23553                 parseExpected(21 /* CloseParenToken */);
23554                 forOrForInOrForOfStatement = forOfStatement;
23555             }
23556             else if (parseOptional(97 /* InKeyword */)) {
23557                 var forInStatement = createNode(231 /* ForInStatement */, pos);
23558                 forInStatement.initializer = initializer;
23559                 forInStatement.expression = allowInAnd(parseExpression);
23560                 parseExpected(21 /* CloseParenToken */);
23561                 forOrForInOrForOfStatement = forInStatement;
23562             }
23563             else {
23564                 var forStatement = createNode(230 /* ForStatement */, pos);
23565                 forStatement.initializer = initializer;
23566                 parseExpected(26 /* SemicolonToken */);
23567                 if (token() !== 26 /* SemicolonToken */ && token() !== 21 /* CloseParenToken */) {
23568                     forStatement.condition = allowInAnd(parseExpression);
23569                 }
23570                 parseExpected(26 /* SemicolonToken */);
23571                 if (token() !== 21 /* CloseParenToken */) {
23572                     forStatement.incrementor = allowInAnd(parseExpression);
23573                 }
23574                 parseExpected(21 /* CloseParenToken */);
23575                 forOrForInOrForOfStatement = forStatement;
23576             }
23577             forOrForInOrForOfStatement.statement = parseStatement();
23578             return finishNode(forOrForInOrForOfStatement);
23579         }
23580         function parseBreakOrContinueStatement(kind) {
23581             var node = createNode(kind);
23582             parseExpected(kind === 234 /* BreakStatement */ ? 77 /* BreakKeyword */ : 82 /* ContinueKeyword */);
23583             if (!canParseSemicolon()) {
23584                 node.label = parseIdentifier();
23585             }
23586             parseSemicolon();
23587             return finishNode(node);
23588         }
23589         function parseReturnStatement() {
23590             var node = createNode(235 /* ReturnStatement */);
23591             parseExpected(101 /* ReturnKeyword */);
23592             if (!canParseSemicolon()) {
23593                 node.expression = allowInAnd(parseExpression);
23594             }
23595             parseSemicolon();
23596             return finishNode(node);
23597         }
23598         function parseWithStatement() {
23599             var node = createNode(236 /* WithStatement */);
23600             parseExpected(112 /* WithKeyword */);
23601             parseExpected(20 /* OpenParenToken */);
23602             node.expression = allowInAnd(parseExpression);
23603             parseExpected(21 /* CloseParenToken */);
23604             node.statement = doInsideOfContext(16777216 /* InWithStatement */, parseStatement);
23605             return finishNode(node);
23606         }
23607         function parseCaseClause() {
23608             var node = createNode(277 /* CaseClause */);
23609             parseExpected(78 /* CaseKeyword */);
23610             node.expression = allowInAnd(parseExpression);
23611             parseExpected(58 /* ColonToken */);
23612             node.statements = parseList(3 /* SwitchClauseStatements */, parseStatement);
23613             return finishNode(node);
23614         }
23615         function parseDefaultClause() {
23616             var node = createNode(278 /* DefaultClause */);
23617             parseExpected(84 /* DefaultKeyword */);
23618             parseExpected(58 /* ColonToken */);
23619             node.statements = parseList(3 /* SwitchClauseStatements */, parseStatement);
23620             return finishNode(node);
23621         }
23622         function parseCaseOrDefaultClause() {
23623             return token() === 78 /* CaseKeyword */ ? parseCaseClause() : parseDefaultClause();
23624         }
23625         function parseSwitchStatement() {
23626             var node = createNode(237 /* SwitchStatement */);
23627             parseExpected(103 /* SwitchKeyword */);
23628             parseExpected(20 /* OpenParenToken */);
23629             node.expression = allowInAnd(parseExpression);
23630             parseExpected(21 /* CloseParenToken */);
23631             var caseBlock = createNode(251 /* CaseBlock */);
23632             parseExpected(18 /* OpenBraceToken */);
23633             caseBlock.clauses = parseList(2 /* SwitchClauses */, parseCaseOrDefaultClause);
23634             parseExpected(19 /* CloseBraceToken */);
23635             node.caseBlock = finishNode(caseBlock);
23636             return finishNode(node);
23637         }
23638         function parseThrowStatement() {
23639             // ThrowStatement[Yield] :
23640             //      throw [no LineTerminator here]Expression[In, ?Yield];
23641             // Because of automatic semicolon insertion, we need to report error if this
23642             // throw could be terminated with a semicolon.  Note: we can't call 'parseExpression'
23643             // directly as that might consume an expression on the following line.
23644             // We just return 'undefined' in that case.  The actual error will be reported in the
23645             // grammar walker.
23646             var node = createNode(239 /* ThrowStatement */);
23647             parseExpected(105 /* ThrowKeyword */);
23648             node.expression = scanner.hasPrecedingLineBreak() ? undefined : allowInAnd(parseExpression);
23649             parseSemicolon();
23650             return finishNode(node);
23651         }
23652         // TODO: Review for error recovery
23653         function parseTryStatement() {
23654             var node = createNode(240 /* TryStatement */);
23655             parseExpected(107 /* TryKeyword */);
23656             node.tryBlock = parseBlock(/*ignoreMissingOpenBrace*/ false);
23657             node.catchClause = token() === 79 /* CatchKeyword */ ? parseCatchClause() : undefined;
23658             // If we don't have a catch clause, then we must have a finally clause.  Try to parse
23659             // one out no matter what.
23660             if (!node.catchClause || token() === 92 /* FinallyKeyword */) {
23661                 parseExpected(92 /* FinallyKeyword */);
23662                 node.finallyBlock = parseBlock(/*ignoreMissingOpenBrace*/ false);
23663             }
23664             return finishNode(node);
23665         }
23666         function parseCatchClause() {
23667             var result = createNode(280 /* CatchClause */);
23668             parseExpected(79 /* CatchKeyword */);
23669             if (parseOptional(20 /* OpenParenToken */)) {
23670                 result.variableDeclaration = parseVariableDeclaration();
23671                 parseExpected(21 /* CloseParenToken */);
23672             }
23673             else {
23674                 // Keep shape of node to avoid degrading performance.
23675                 result.variableDeclaration = undefined;
23676             }
23677             result.block = parseBlock(/*ignoreMissingOpenBrace*/ false);
23678             return finishNode(result);
23679         }
23680         function parseDebuggerStatement() {
23681             var node = createNode(241 /* DebuggerStatement */);
23682             parseExpected(83 /* DebuggerKeyword */);
23683             parseSemicolon();
23684             return finishNode(node);
23685         }
23686         function parseExpressionOrLabeledStatement() {
23687             // Avoiding having to do the lookahead for a labeled statement by just trying to parse
23688             // out an expression, seeing if it is identifier and then seeing if it is followed by
23689             // a colon.
23690             var node = createNodeWithJSDoc(token() === 75 /* Identifier */ ? 0 /* Unknown */ : 226 /* ExpressionStatement */);
23691             var expression = allowInAnd(parseExpression);
23692             if (expression.kind === 75 /* Identifier */ && parseOptional(58 /* ColonToken */)) {
23693                 node.kind = 238 /* LabeledStatement */;
23694                 node.label = expression;
23695                 node.statement = parseStatement();
23696             }
23697             else {
23698                 node.kind = 226 /* ExpressionStatement */;
23699                 node.expression = expression;
23700                 parseSemicolon();
23701             }
23702             return finishNode(node);
23703         }
23704         function nextTokenIsIdentifierOrKeywordOnSameLine() {
23705             nextToken();
23706             return ts.tokenIsIdentifierOrKeyword(token()) && !scanner.hasPrecedingLineBreak();
23707         }
23708         function nextTokenIsClassKeywordOnSameLine() {
23709             nextToken();
23710             return token() === 80 /* ClassKeyword */ && !scanner.hasPrecedingLineBreak();
23711         }
23712         function nextTokenIsFunctionKeywordOnSameLine() {
23713             nextToken();
23714             return token() === 94 /* FunctionKeyword */ && !scanner.hasPrecedingLineBreak();
23715         }
23716         function nextTokenIsIdentifierOrKeywordOrLiteralOnSameLine() {
23717             nextToken();
23718             return (ts.tokenIsIdentifierOrKeyword(token()) || token() === 8 /* NumericLiteral */ || token() === 9 /* BigIntLiteral */ || token() === 10 /* StringLiteral */) && !scanner.hasPrecedingLineBreak();
23719         }
23720         function isDeclaration() {
23721             while (true) {
23722                 switch (token()) {
23723                     case 109 /* VarKeyword */:
23724                     case 115 /* LetKeyword */:
23725                     case 81 /* ConstKeyword */:
23726                     case 94 /* FunctionKeyword */:
23727                     case 80 /* ClassKeyword */:
23728                     case 88 /* EnumKeyword */:
23729                         return true;
23730                     // 'declare', 'module', 'namespace', 'interface'* and 'type' are all legal JavaScript identifiers;
23731                     // however, an identifier cannot be followed by another identifier on the same line. This is what we
23732                     // count on to parse out the respective declarations. For instance, we exploit this to say that
23733                     //
23734                     //    namespace n
23735                     //
23736                     // can be none other than the beginning of a namespace declaration, but need to respect that JavaScript sees
23737                     //
23738                     //    namespace
23739                     //    n
23740                     //
23741                     // as the identifier 'namespace' on one line followed by the identifier 'n' on another.
23742                     // We need to look one token ahead to see if it permissible to try parsing a declaration.
23743                     //
23744                     // *Note*: 'interface' is actually a strict mode reserved word. So while
23745                     //
23746                     //   "use strict"
23747                     //   interface
23748                     //   I {}
23749                     //
23750                     // could be legal, it would add complexity for very little gain.
23751                     case 114 /* InterfaceKeyword */:
23752                     case 145 /* TypeKeyword */:
23753                         return nextTokenIsIdentifierOnSameLine();
23754                     case 135 /* ModuleKeyword */:
23755                     case 136 /* NamespaceKeyword */:
23756                         return nextTokenIsIdentifierOrStringLiteralOnSameLine();
23757                     case 122 /* AbstractKeyword */:
23758                     case 126 /* AsyncKeyword */:
23759                     case 130 /* DeclareKeyword */:
23760                     case 117 /* PrivateKeyword */:
23761                     case 118 /* ProtectedKeyword */:
23762                     case 119 /* PublicKeyword */:
23763                     case 138 /* ReadonlyKeyword */:
23764                         nextToken();
23765                         // ASI takes effect for this modifier.
23766                         if (scanner.hasPrecedingLineBreak()) {
23767                             return false;
23768                         }
23769                         continue;
23770                     case 150 /* GlobalKeyword */:
23771                         nextToken();
23772                         return token() === 18 /* OpenBraceToken */ || token() === 75 /* Identifier */ || token() === 89 /* ExportKeyword */;
23773                     case 96 /* ImportKeyword */:
23774                         nextToken();
23775                         return token() === 10 /* StringLiteral */ || token() === 41 /* AsteriskToken */ ||
23776                             token() === 18 /* OpenBraceToken */ || ts.tokenIsIdentifierOrKeyword(token());
23777                     case 89 /* ExportKeyword */:
23778                         var currentToken_1 = nextToken();
23779                         if (currentToken_1 === 145 /* TypeKeyword */) {
23780                             currentToken_1 = lookAhead(nextToken);
23781                         }
23782                         if (currentToken_1 === 62 /* EqualsToken */ || currentToken_1 === 41 /* AsteriskToken */ ||
23783                             currentToken_1 === 18 /* OpenBraceToken */ || currentToken_1 === 84 /* DefaultKeyword */ ||
23784                             currentToken_1 === 123 /* AsKeyword */) {
23785                             return true;
23786                         }
23787                         continue;
23788                     case 120 /* StaticKeyword */:
23789                         nextToken();
23790                         continue;
23791                     default:
23792                         return false;
23793                 }
23794             }
23795         }
23796         function isStartOfDeclaration() {
23797             return lookAhead(isDeclaration);
23798         }
23799         function isStartOfStatement() {
23800             switch (token()) {
23801                 case 59 /* AtToken */:
23802                 case 26 /* SemicolonToken */:
23803                 case 18 /* OpenBraceToken */:
23804                 case 109 /* VarKeyword */:
23805                 case 115 /* LetKeyword */:
23806                 case 94 /* FunctionKeyword */:
23807                 case 80 /* ClassKeyword */:
23808                 case 88 /* EnumKeyword */:
23809                 case 95 /* IfKeyword */:
23810                 case 86 /* DoKeyword */:
23811                 case 111 /* WhileKeyword */:
23812                 case 93 /* ForKeyword */:
23813                 case 82 /* ContinueKeyword */:
23814                 case 77 /* BreakKeyword */:
23815                 case 101 /* ReturnKeyword */:
23816                 case 112 /* WithKeyword */:
23817                 case 103 /* SwitchKeyword */:
23818                 case 105 /* ThrowKeyword */:
23819                 case 107 /* TryKeyword */:
23820                 case 83 /* DebuggerKeyword */:
23821                 // 'catch' and 'finally' do not actually indicate that the code is part of a statement,
23822                 // however, we say they are here so that we may gracefully parse them and error later.
23823                 // falls through
23824                 case 79 /* CatchKeyword */:
23825                 case 92 /* FinallyKeyword */:
23826                     return true;
23827                 case 96 /* ImportKeyword */:
23828                     return isStartOfDeclaration() || lookAhead(nextTokenIsOpenParenOrLessThanOrDot);
23829                 case 81 /* ConstKeyword */:
23830                 case 89 /* ExportKeyword */:
23831                     return isStartOfDeclaration();
23832                 case 126 /* AsyncKeyword */:
23833                 case 130 /* DeclareKeyword */:
23834                 case 114 /* InterfaceKeyword */:
23835                 case 135 /* ModuleKeyword */:
23836                 case 136 /* NamespaceKeyword */:
23837                 case 145 /* TypeKeyword */:
23838                 case 150 /* GlobalKeyword */:
23839                     // When these don't start a declaration, they're an identifier in an expression statement
23840                     return true;
23841                 case 119 /* PublicKeyword */:
23842                 case 117 /* PrivateKeyword */:
23843                 case 118 /* ProtectedKeyword */:
23844                 case 120 /* StaticKeyword */:
23845                 case 138 /* ReadonlyKeyword */:
23846                     // When these don't start a declaration, they may be the start of a class member if an identifier
23847                     // immediately follows. Otherwise they're an identifier in an expression statement.
23848                     return isStartOfDeclaration() || !lookAhead(nextTokenIsIdentifierOrKeywordOnSameLine);
23849                 default:
23850                     return isStartOfExpression();
23851             }
23852         }
23853         function nextTokenIsIdentifierOrStartOfDestructuring() {
23854             nextToken();
23855             return isIdentifier() || token() === 18 /* OpenBraceToken */ || token() === 22 /* OpenBracketToken */;
23856         }
23857         function isLetDeclaration() {
23858             // In ES6 'let' always starts a lexical declaration if followed by an identifier or {
23859             // or [.
23860             return lookAhead(nextTokenIsIdentifierOrStartOfDestructuring);
23861         }
23862         function parseStatement() {
23863             switch (token()) {
23864                 case 26 /* SemicolonToken */:
23865                     return parseEmptyStatement();
23866                 case 18 /* OpenBraceToken */:
23867                     return parseBlock(/*ignoreMissingOpenBrace*/ false);
23868                 case 109 /* VarKeyword */:
23869                     return parseVariableStatement(createNodeWithJSDoc(242 /* VariableDeclaration */));
23870                 case 115 /* LetKeyword */:
23871                     if (isLetDeclaration()) {
23872                         return parseVariableStatement(createNodeWithJSDoc(242 /* VariableDeclaration */));
23873                     }
23874                     break;
23875                 case 94 /* FunctionKeyword */:
23876                     return parseFunctionDeclaration(createNodeWithJSDoc(244 /* FunctionDeclaration */));
23877                 case 80 /* ClassKeyword */:
23878                     return parseClassDeclaration(createNodeWithJSDoc(245 /* ClassDeclaration */));
23879                 case 95 /* IfKeyword */:
23880                     return parseIfStatement();
23881                 case 86 /* DoKeyword */:
23882                     return parseDoStatement();
23883                 case 111 /* WhileKeyword */:
23884                     return parseWhileStatement();
23885                 case 93 /* ForKeyword */:
23886                     return parseForOrForInOrForOfStatement();
23887                 case 82 /* ContinueKeyword */:
23888                     return parseBreakOrContinueStatement(233 /* ContinueStatement */);
23889                 case 77 /* BreakKeyword */:
23890                     return parseBreakOrContinueStatement(234 /* BreakStatement */);
23891                 case 101 /* ReturnKeyword */:
23892                     return parseReturnStatement();
23893                 case 112 /* WithKeyword */:
23894                     return parseWithStatement();
23895                 case 103 /* SwitchKeyword */:
23896                     return parseSwitchStatement();
23897                 case 105 /* ThrowKeyword */:
23898                     return parseThrowStatement();
23899                 case 107 /* TryKeyword */:
23900                 // Include 'catch' and 'finally' for error recovery.
23901                 // falls through
23902                 case 79 /* CatchKeyword */:
23903                 case 92 /* FinallyKeyword */:
23904                     return parseTryStatement();
23905                 case 83 /* DebuggerKeyword */:
23906                     return parseDebuggerStatement();
23907                 case 59 /* AtToken */:
23908                     return parseDeclaration();
23909                 case 126 /* AsyncKeyword */:
23910                 case 114 /* InterfaceKeyword */:
23911                 case 145 /* TypeKeyword */:
23912                 case 135 /* ModuleKeyword */:
23913                 case 136 /* NamespaceKeyword */:
23914                 case 130 /* DeclareKeyword */:
23915                 case 81 /* ConstKeyword */:
23916                 case 88 /* EnumKeyword */:
23917                 case 89 /* ExportKeyword */:
23918                 case 96 /* ImportKeyword */:
23919                 case 117 /* PrivateKeyword */:
23920                 case 118 /* ProtectedKeyword */:
23921                 case 119 /* PublicKeyword */:
23922                 case 122 /* AbstractKeyword */:
23923                 case 120 /* StaticKeyword */:
23924                 case 138 /* ReadonlyKeyword */:
23925                 case 150 /* GlobalKeyword */:
23926                     if (isStartOfDeclaration()) {
23927                         return parseDeclaration();
23928                     }
23929                     break;
23930             }
23931             return parseExpressionOrLabeledStatement();
23932         }
23933         function isDeclareModifier(modifier) {
23934             return modifier.kind === 130 /* DeclareKeyword */;
23935         }
23936         function parseDeclaration() {
23937             var modifiers = lookAhead(function () { return (parseDecorators(), parseModifiers()); });
23938             // `parseListElement` attempted to get the reused node at this position,
23939             // but the ambient context flag was not yet set, so the node appeared
23940             // not reusable in that context.
23941             var isAmbient = ts.some(modifiers, isDeclareModifier);
23942             if (isAmbient) {
23943                 var node_3 = tryReuseAmbientDeclaration();
23944                 if (node_3) {
23945                     return node_3;
23946                 }
23947             }
23948             var node = createNodeWithJSDoc(0 /* Unknown */);
23949             node.decorators = parseDecorators();
23950             node.modifiers = parseModifiers();
23951             if (isAmbient) {
23952                 for (var _i = 0, _a = node.modifiers; _i < _a.length; _i++) {
23953                     var m = _a[_i];
23954                     m.flags |= 8388608 /* Ambient */;
23955                 }
23956                 return doInsideOfContext(8388608 /* Ambient */, function () { return parseDeclarationWorker(node); });
23957             }
23958             else {
23959                 return parseDeclarationWorker(node);
23960             }
23961         }
23962         function tryReuseAmbientDeclaration() {
23963             return doInsideOfContext(8388608 /* Ambient */, function () {
23964                 var node = currentNode(parsingContext);
23965                 if (node) {
23966                     return consumeNode(node);
23967                 }
23968             });
23969         }
23970         function parseDeclarationWorker(node) {
23971             switch (token()) {
23972                 case 109 /* VarKeyword */:
23973                 case 115 /* LetKeyword */:
23974                 case 81 /* ConstKeyword */:
23975                     return parseVariableStatement(node);
23976                 case 94 /* FunctionKeyword */:
23977                     return parseFunctionDeclaration(node);
23978                 case 80 /* ClassKeyword */:
23979                     return parseClassDeclaration(node);
23980                 case 114 /* InterfaceKeyword */:
23981                     return parseInterfaceDeclaration(node);
23982                 case 145 /* TypeKeyword */:
23983                     return parseTypeAliasDeclaration(node);
23984                 case 88 /* EnumKeyword */:
23985                     return parseEnumDeclaration(node);
23986                 case 150 /* GlobalKeyword */:
23987                 case 135 /* ModuleKeyword */:
23988                 case 136 /* NamespaceKeyword */:
23989                     return parseModuleDeclaration(node);
23990                 case 96 /* ImportKeyword */:
23991                     return parseImportDeclarationOrImportEqualsDeclaration(node);
23992                 case 89 /* ExportKeyword */:
23993                     nextToken();
23994                     switch (token()) {
23995                         case 84 /* DefaultKeyword */:
23996                         case 62 /* EqualsToken */:
23997                             return parseExportAssignment(node);
23998                         case 123 /* AsKeyword */:
23999                             return parseNamespaceExportDeclaration(node);
24000                         default:
24001                             return parseExportDeclaration(node);
24002                     }
24003                 default:
24004                     if (node.decorators || node.modifiers) {
24005                         // We reached this point because we encountered decorators and/or modifiers and assumed a declaration
24006                         // would follow. For recovery and error reporting purposes, return an incomplete declaration.
24007                         var missing = createMissingNode(264 /* MissingDeclaration */, /*reportAtCurrentPosition*/ true, ts.Diagnostics.Declaration_expected);
24008                         missing.pos = node.pos;
24009                         missing.decorators = node.decorators;
24010                         missing.modifiers = node.modifiers;
24011                         return finishNode(missing);
24012                     }
24013                     return undefined; // TODO: GH#18217
24014             }
24015         }
24016         function nextTokenIsIdentifierOrStringLiteralOnSameLine() {
24017             nextToken();
24018             return !scanner.hasPrecedingLineBreak() && (isIdentifier() || token() === 10 /* StringLiteral */);
24019         }
24020         function parseFunctionBlockOrSemicolon(flags, diagnosticMessage) {
24021             if (token() !== 18 /* OpenBraceToken */ && canParseSemicolon()) {
24022                 parseSemicolon();
24023                 return;
24024             }
24025             return parseFunctionBlock(flags, diagnosticMessage);
24026         }
24027         // DECLARATIONS
24028         function parseArrayBindingElement() {
24029             if (token() === 27 /* CommaToken */) {
24030                 return createNode(215 /* OmittedExpression */);
24031             }
24032             var node = createNode(191 /* BindingElement */);
24033             node.dotDotDotToken = parseOptionalToken(25 /* DotDotDotToken */);
24034             node.name = parseIdentifierOrPattern();
24035             node.initializer = parseInitializer();
24036             return finishNode(node);
24037         }
24038         function parseObjectBindingElement() {
24039             var node = createNode(191 /* BindingElement */);
24040             node.dotDotDotToken = parseOptionalToken(25 /* DotDotDotToken */);
24041             var tokenIsIdentifier = isIdentifier();
24042             var propertyName = parsePropertyName();
24043             if (tokenIsIdentifier && token() !== 58 /* ColonToken */) {
24044                 node.name = propertyName;
24045             }
24046             else {
24047                 parseExpected(58 /* ColonToken */);
24048                 node.propertyName = propertyName;
24049                 node.name = parseIdentifierOrPattern();
24050             }
24051             node.initializer = parseInitializer();
24052             return finishNode(node);
24053         }
24054         function parseObjectBindingPattern() {
24055             var node = createNode(189 /* ObjectBindingPattern */);
24056             parseExpected(18 /* OpenBraceToken */);
24057             node.elements = parseDelimitedList(9 /* ObjectBindingElements */, parseObjectBindingElement);
24058             parseExpected(19 /* CloseBraceToken */);
24059             return finishNode(node);
24060         }
24061         function parseArrayBindingPattern() {
24062             var node = createNode(190 /* ArrayBindingPattern */);
24063             parseExpected(22 /* OpenBracketToken */);
24064             node.elements = parseDelimitedList(10 /* ArrayBindingElements */, parseArrayBindingElement);
24065             parseExpected(23 /* CloseBracketToken */);
24066             return finishNode(node);
24067         }
24068         function isIdentifierOrPrivateIdentifierOrPattern() {
24069             return token() === 18 /* OpenBraceToken */
24070                 || token() === 22 /* OpenBracketToken */
24071                 || token() === 76 /* PrivateIdentifier */
24072                 || isIdentifier();
24073         }
24074         function parseIdentifierOrPattern(privateIdentifierDiagnosticMessage) {
24075             if (token() === 22 /* OpenBracketToken */) {
24076                 return parseArrayBindingPattern();
24077             }
24078             if (token() === 18 /* OpenBraceToken */) {
24079                 return parseObjectBindingPattern();
24080             }
24081             return parseIdentifier(/*diagnosticMessage*/ undefined, privateIdentifierDiagnosticMessage);
24082         }
24083         function parseVariableDeclarationAllowExclamation() {
24084             return parseVariableDeclaration(/*allowExclamation*/ true);
24085         }
24086         function parseVariableDeclaration(allowExclamation) {
24087             var node = createNode(242 /* VariableDeclaration */);
24088             node.name = parseIdentifierOrPattern(ts.Diagnostics.Private_identifiers_are_not_allowed_in_variable_declarations);
24089             if (allowExclamation && node.name.kind === 75 /* Identifier */ &&
24090                 token() === 53 /* ExclamationToken */ && !scanner.hasPrecedingLineBreak()) {
24091                 node.exclamationToken = parseTokenNode();
24092             }
24093             node.type = parseTypeAnnotation();
24094             if (!isInOrOfKeyword(token())) {
24095                 node.initializer = parseInitializer();
24096             }
24097             return finishNode(node);
24098         }
24099         function parseVariableDeclarationList(inForStatementInitializer) {
24100             var node = createNode(243 /* VariableDeclarationList */);
24101             switch (token()) {
24102                 case 109 /* VarKeyword */:
24103                     break;
24104                 case 115 /* LetKeyword */:
24105                     node.flags |= 1 /* Let */;
24106                     break;
24107                 case 81 /* ConstKeyword */:
24108                     node.flags |= 2 /* Const */;
24109                     break;
24110                 default:
24111                     ts.Debug.fail();
24112             }
24113             nextToken();
24114             // The user may have written the following:
24115             //
24116             //    for (let of X) { }
24117             //
24118             // In this case, we want to parse an empty declaration list, and then parse 'of'
24119             // as a keyword. The reason this is not automatic is that 'of' is a valid identifier.
24120             // So we need to look ahead to determine if 'of' should be treated as a keyword in
24121             // this context.
24122             // The checker will then give an error that there is an empty declaration list.
24123             if (token() === 152 /* OfKeyword */ && lookAhead(canFollowContextualOfKeyword)) {
24124                 node.declarations = createMissingList();
24125             }
24126             else {
24127                 var savedDisallowIn = inDisallowInContext();
24128                 setDisallowInContext(inForStatementInitializer);
24129                 node.declarations = parseDelimitedList(8 /* VariableDeclarations */, inForStatementInitializer ? parseVariableDeclaration : parseVariableDeclarationAllowExclamation);
24130                 setDisallowInContext(savedDisallowIn);
24131             }
24132             return finishNode(node);
24133         }
24134         function canFollowContextualOfKeyword() {
24135             return nextTokenIsIdentifier() && nextToken() === 21 /* CloseParenToken */;
24136         }
24137         function parseVariableStatement(node) {
24138             node.kind = 225 /* VariableStatement */;
24139             node.declarationList = parseVariableDeclarationList(/*inForStatementInitializer*/ false);
24140             parseSemicolon();
24141             return finishNode(node);
24142         }
24143         function parseFunctionDeclaration(node) {
24144             node.kind = 244 /* FunctionDeclaration */;
24145             parseExpected(94 /* FunctionKeyword */);
24146             node.asteriskToken = parseOptionalToken(41 /* AsteriskToken */);
24147             node.name = hasModifierOfKind(node, 84 /* DefaultKeyword */) ? parseOptionalIdentifier() : parseIdentifier();
24148             var isGenerator = node.asteriskToken ? 1 /* Yield */ : 0 /* None */;
24149             var isAsync = hasModifierOfKind(node, 126 /* AsyncKeyword */) ? 2 /* Await */ : 0 /* None */;
24150             fillSignature(58 /* ColonToken */, isGenerator | isAsync, node);
24151             node.body = parseFunctionBlockOrSemicolon(isGenerator | isAsync, ts.Diagnostics.or_expected);
24152             return finishNode(node);
24153         }
24154         function parseConstructorName() {
24155             if (token() === 129 /* ConstructorKeyword */) {
24156                 return parseExpected(129 /* ConstructorKeyword */);
24157             }
24158             if (token() === 10 /* StringLiteral */ && lookAhead(nextToken) === 20 /* OpenParenToken */) {
24159                 return tryParse(function () {
24160                     var literalNode = parseLiteralNode();
24161                     return literalNode.text === "constructor" ? literalNode : undefined;
24162                 });
24163             }
24164         }
24165         function tryParseConstructorDeclaration(node) {
24166             return tryParse(function () {
24167                 if (parseConstructorName()) {
24168                     node.kind = 162 /* Constructor */;
24169                     fillSignature(58 /* ColonToken */, 0 /* None */, node);
24170                     node.body = parseFunctionBlockOrSemicolon(0 /* None */, ts.Diagnostics.or_expected);
24171                     return finishNode(node);
24172                 }
24173             });
24174         }
24175         function parseMethodDeclaration(node, asteriskToken, diagnosticMessage) {
24176             node.kind = 161 /* MethodDeclaration */;
24177             node.asteriskToken = asteriskToken;
24178             var isGenerator = asteriskToken ? 1 /* Yield */ : 0 /* None */;
24179             var isAsync = hasModifierOfKind(node, 126 /* AsyncKeyword */) ? 2 /* Await */ : 0 /* None */;
24180             fillSignature(58 /* ColonToken */, isGenerator | isAsync, node);
24181             node.body = parseFunctionBlockOrSemicolon(isGenerator | isAsync, diagnosticMessage);
24182             return finishNode(node);
24183         }
24184         function parsePropertyDeclaration(node) {
24185             node.kind = 159 /* PropertyDeclaration */;
24186             if (!node.questionToken && token() === 53 /* ExclamationToken */ && !scanner.hasPrecedingLineBreak()) {
24187                 node.exclamationToken = parseTokenNode();
24188             }
24189             node.type = parseTypeAnnotation();
24190             node.initializer = doOutsideOfContext(8192 /* YieldContext */ | 32768 /* AwaitContext */ | 4096 /* DisallowInContext */, parseInitializer);
24191             parseSemicolon();
24192             return finishNode(node);
24193         }
24194         function parsePropertyOrMethodDeclaration(node) {
24195             var asteriskToken = parseOptionalToken(41 /* AsteriskToken */);
24196             node.name = parsePropertyName();
24197             // Note: this is not legal as per the grammar.  But we allow it in the parser and
24198             // report an error in the grammar checker.
24199             node.questionToken = parseOptionalToken(57 /* QuestionToken */);
24200             if (asteriskToken || token() === 20 /* OpenParenToken */ || token() === 29 /* LessThanToken */) {
24201                 return parseMethodDeclaration(node, asteriskToken, ts.Diagnostics.or_expected);
24202             }
24203             return parsePropertyDeclaration(node);
24204         }
24205         function parseAccessorDeclaration(node, kind) {
24206             node.kind = kind;
24207             node.name = parsePropertyName();
24208             fillSignature(58 /* ColonToken */, 0 /* None */, node);
24209             node.body = parseFunctionBlockOrSemicolon(0 /* None */);
24210             return finishNode(node);
24211         }
24212         function isClassMemberStart() {
24213             var idToken;
24214             if (token() === 59 /* AtToken */) {
24215                 return true;
24216             }
24217             // Eat up all modifiers, but hold on to the last one in case it is actually an identifier.
24218             while (ts.isModifierKind(token())) {
24219                 idToken = token();
24220                 // If the idToken is a class modifier (protected, private, public, and static), it is
24221                 // certain that we are starting to parse class member. This allows better error recovery
24222                 // Example:
24223                 //      public foo() ...     // true
24224                 //      public @dec blah ... // true; we will then report an error later
24225                 //      export public ...    // true; we will then report an error later
24226                 if (ts.isClassMemberModifier(idToken)) {
24227                     return true;
24228                 }
24229                 nextToken();
24230             }
24231             if (token() === 41 /* AsteriskToken */) {
24232                 return true;
24233             }
24234             // Try to get the first property-like token following all modifiers.
24235             // This can either be an identifier or the 'get' or 'set' keywords.
24236             if (isLiteralPropertyName()) {
24237                 idToken = token();
24238                 nextToken();
24239             }
24240             // Index signatures and computed properties are class members; we can parse.
24241             if (token() === 22 /* OpenBracketToken */) {
24242                 return true;
24243             }
24244             // If we were able to get any potential identifier...
24245             if (idToken !== undefined) {
24246                 // If we have a non-keyword identifier, or if we have an accessor, then it's safe to parse.
24247                 if (!ts.isKeyword(idToken) || idToken === 142 /* SetKeyword */ || idToken === 131 /* GetKeyword */) {
24248                     return true;
24249                 }
24250                 // If it *is* a keyword, but not an accessor, check a little farther along
24251                 // to see if it should actually be parsed as a class member.
24252                 switch (token()) {
24253                     case 20 /* OpenParenToken */: // Method declaration
24254                     case 29 /* LessThanToken */: // Generic Method declaration
24255                     case 53 /* ExclamationToken */: // Non-null assertion on property name
24256                     case 58 /* ColonToken */: // Type Annotation for declaration
24257                     case 62 /* EqualsToken */: // Initializer for declaration
24258                     case 57 /* QuestionToken */: // Not valid, but permitted so that it gets caught later on.
24259                         return true;
24260                     default:
24261                         // Covers
24262                         //  - Semicolons     (declaration termination)
24263                         //  - Closing braces (end-of-class, must be declaration)
24264                         //  - End-of-files   (not valid, but permitted so that it gets caught later on)
24265                         //  - Line-breaks    (enabling *automatic semicolon insertion*)
24266                         return canParseSemicolon();
24267                 }
24268             }
24269             return false;
24270         }
24271         function parseDecorators() {
24272             var list;
24273             var listPos = getNodePos();
24274             while (true) {
24275                 var decoratorStart = getNodePos();
24276                 if (!parseOptional(59 /* AtToken */)) {
24277                     break;
24278                 }
24279                 var decorator = createNode(157 /* Decorator */, decoratorStart);
24280                 decorator.expression = doInDecoratorContext(parseLeftHandSideExpressionOrHigher);
24281                 finishNode(decorator);
24282                 (list || (list = [])).push(decorator);
24283             }
24284             return list && createNodeArray(list, listPos);
24285         }
24286         /*
24287          * There are situations in which a modifier like 'const' will appear unexpectedly, such as on a class member.
24288          * In those situations, if we are entirely sure that 'const' is not valid on its own (such as when ASI takes effect
24289          * and turns it into a standalone declaration), then it is better to parse it and report an error later.
24290          *
24291          * In such situations, 'permitInvalidConstAsModifier' should be set to true.
24292          */
24293         function parseModifiers(permitInvalidConstAsModifier) {
24294             var list;
24295             var listPos = getNodePos();
24296             while (true) {
24297                 var modifierStart = scanner.getStartPos();
24298                 var modifierKind = token();
24299                 if (token() === 81 /* ConstKeyword */ && permitInvalidConstAsModifier) {
24300                     // We need to ensure that any subsequent modifiers appear on the same line
24301                     // so that when 'const' is a standalone declaration, we don't issue an error.
24302                     if (!tryParse(nextTokenIsOnSameLineAndCanFollowModifier)) {
24303                         break;
24304                     }
24305                 }
24306                 else {
24307                     if (!parseAnyContextualModifier()) {
24308                         break;
24309                     }
24310                 }
24311                 var modifier = finishNode(createNode(modifierKind, modifierStart));
24312                 (list || (list = [])).push(modifier);
24313             }
24314             return list && createNodeArray(list, listPos);
24315         }
24316         function parseModifiersForArrowFunction() {
24317             var modifiers;
24318             if (token() === 126 /* AsyncKeyword */) {
24319                 var modifierStart = scanner.getStartPos();
24320                 var modifierKind = token();
24321                 nextToken();
24322                 var modifier = finishNode(createNode(modifierKind, modifierStart));
24323                 modifiers = createNodeArray([modifier], modifierStart);
24324             }
24325             return modifiers;
24326         }
24327         function parseClassElement() {
24328             if (token() === 26 /* SemicolonToken */) {
24329                 var result = createNode(222 /* SemicolonClassElement */);
24330                 nextToken();
24331                 return finishNode(result);
24332             }
24333             var node = createNodeWithJSDoc(0 /* Unknown */);
24334             node.decorators = parseDecorators();
24335             node.modifiers = parseModifiers(/*permitInvalidConstAsModifier*/ true);
24336             if (parseContextualModifier(131 /* GetKeyword */)) {
24337                 return parseAccessorDeclaration(node, 163 /* GetAccessor */);
24338             }
24339             if (parseContextualModifier(142 /* SetKeyword */)) {
24340                 return parseAccessorDeclaration(node, 164 /* SetAccessor */);
24341             }
24342             if (token() === 129 /* ConstructorKeyword */ || token() === 10 /* StringLiteral */) {
24343                 var constructorDeclaration = tryParseConstructorDeclaration(node);
24344                 if (constructorDeclaration) {
24345                     return constructorDeclaration;
24346                 }
24347             }
24348             if (isIndexSignature()) {
24349                 return parseIndexSignatureDeclaration(node);
24350             }
24351             // It is very important that we check this *after* checking indexers because
24352             // the [ token can start an index signature or a computed property name
24353             if (ts.tokenIsIdentifierOrKeyword(token()) ||
24354                 token() === 10 /* StringLiteral */ ||
24355                 token() === 8 /* NumericLiteral */ ||
24356                 token() === 41 /* AsteriskToken */ ||
24357                 token() === 22 /* OpenBracketToken */) {
24358                 var isAmbient = node.modifiers && ts.some(node.modifiers, isDeclareModifier);
24359                 if (isAmbient) {
24360                     for (var _i = 0, _a = node.modifiers; _i < _a.length; _i++) {
24361                         var m = _a[_i];
24362                         m.flags |= 8388608 /* Ambient */;
24363                     }
24364                     return doInsideOfContext(8388608 /* Ambient */, function () { return parsePropertyOrMethodDeclaration(node); });
24365                 }
24366                 else {
24367                     return parsePropertyOrMethodDeclaration(node);
24368                 }
24369             }
24370             if (node.decorators || node.modifiers) {
24371                 // treat this as a property declaration with a missing name.
24372                 node.name = createMissingNode(75 /* Identifier */, /*reportAtCurrentPosition*/ true, ts.Diagnostics.Declaration_expected);
24373                 return parsePropertyDeclaration(node);
24374             }
24375             // 'isClassMemberStart' should have hinted not to attempt parsing.
24376             return ts.Debug.fail("Should not have attempted to parse class member declaration.");
24377         }
24378         function parseClassExpression() {
24379             return parseClassDeclarationOrExpression(createNodeWithJSDoc(0 /* Unknown */), 214 /* ClassExpression */);
24380         }
24381         function parseClassDeclaration(node) {
24382             return parseClassDeclarationOrExpression(node, 245 /* ClassDeclaration */);
24383         }
24384         function parseClassDeclarationOrExpression(node, kind) {
24385             node.kind = kind;
24386             parseExpected(80 /* ClassKeyword */);
24387             node.name = parseNameOfClassDeclarationOrExpression();
24388             node.typeParameters = parseTypeParameters();
24389             node.heritageClauses = parseHeritageClauses();
24390             if (parseExpected(18 /* OpenBraceToken */)) {
24391                 // ClassTail[Yield,Await] : (Modified) See 14.5
24392                 //      ClassHeritage[?Yield,?Await]opt { ClassBody[?Yield,?Await]opt }
24393                 node.members = parseClassMembers();
24394                 parseExpected(19 /* CloseBraceToken */);
24395             }
24396             else {
24397                 node.members = createMissingList();
24398             }
24399             return finishNode(node);
24400         }
24401         function parseNameOfClassDeclarationOrExpression() {
24402             // implements is a future reserved word so
24403             // 'class implements' might mean either
24404             // - class expression with omitted name, 'implements' starts heritage clause
24405             // - class with name 'implements'
24406             // 'isImplementsClause' helps to disambiguate between these two cases
24407             return isIdentifier() && !isImplementsClause()
24408                 ? parseIdentifier()
24409                 : undefined;
24410         }
24411         function isImplementsClause() {
24412             return token() === 113 /* ImplementsKeyword */ && lookAhead(nextTokenIsIdentifierOrKeyword);
24413         }
24414         function parseHeritageClauses() {
24415             // ClassTail[Yield,Await] : (Modified) See 14.5
24416             //      ClassHeritage[?Yield,?Await]opt { ClassBody[?Yield,?Await]opt }
24417             if (isHeritageClause()) {
24418                 return parseList(22 /* HeritageClauses */, parseHeritageClause);
24419             }
24420             return undefined;
24421         }
24422         function parseHeritageClause() {
24423             var tok = token();
24424             ts.Debug.assert(tok === 90 /* ExtendsKeyword */ || tok === 113 /* ImplementsKeyword */); // isListElement() should ensure this.
24425             var node = createNode(279 /* HeritageClause */);
24426             node.token = tok;
24427             nextToken();
24428             node.types = parseDelimitedList(7 /* HeritageClauseElement */, parseExpressionWithTypeArguments);
24429             return finishNode(node);
24430         }
24431         function parseExpressionWithTypeArguments() {
24432             var node = createNode(216 /* ExpressionWithTypeArguments */);
24433             node.expression = parseLeftHandSideExpressionOrHigher();
24434             node.typeArguments = tryParseTypeArguments();
24435             return finishNode(node);
24436         }
24437         function tryParseTypeArguments() {
24438             return token() === 29 /* LessThanToken */ ?
24439                 parseBracketedList(20 /* TypeArguments */, parseType, 29 /* LessThanToken */, 31 /* GreaterThanToken */) : undefined;
24440         }
24441         function isHeritageClause() {
24442             return token() === 90 /* ExtendsKeyword */ || token() === 113 /* ImplementsKeyword */;
24443         }
24444         function parseClassMembers() {
24445             return parseList(5 /* ClassMembers */, parseClassElement);
24446         }
24447         function parseInterfaceDeclaration(node) {
24448             node.kind = 246 /* InterfaceDeclaration */;
24449             parseExpected(114 /* InterfaceKeyword */);
24450             node.name = parseIdentifier();
24451             node.typeParameters = parseTypeParameters();
24452             node.heritageClauses = parseHeritageClauses();
24453             node.members = parseObjectTypeMembers();
24454             return finishNode(node);
24455         }
24456         function parseTypeAliasDeclaration(node) {
24457             node.kind = 247 /* TypeAliasDeclaration */;
24458             parseExpected(145 /* TypeKeyword */);
24459             node.name = parseIdentifier();
24460             node.typeParameters = parseTypeParameters();
24461             parseExpected(62 /* EqualsToken */);
24462             node.type = parseType();
24463             parseSemicolon();
24464             return finishNode(node);
24465         }
24466         // In an ambient declaration, the grammar only allows integer literals as initializers.
24467         // In a non-ambient declaration, the grammar allows uninitialized members only in a
24468         // ConstantEnumMemberSection, which starts at the beginning of an enum declaration
24469         // or any time an integer literal initializer is encountered.
24470         function parseEnumMember() {
24471             var node = createNodeWithJSDoc(284 /* EnumMember */);
24472             node.name = parsePropertyName();
24473             node.initializer = allowInAnd(parseInitializer);
24474             return finishNode(node);
24475         }
24476         function parseEnumDeclaration(node) {
24477             node.kind = 248 /* EnumDeclaration */;
24478             parseExpected(88 /* EnumKeyword */);
24479             node.name = parseIdentifier();
24480             if (parseExpected(18 /* OpenBraceToken */)) {
24481                 node.members = doOutsideOfYieldAndAwaitContext(function () { return parseDelimitedList(6 /* EnumMembers */, parseEnumMember); });
24482                 parseExpected(19 /* CloseBraceToken */);
24483             }
24484             else {
24485                 node.members = createMissingList();
24486             }
24487             return finishNode(node);
24488         }
24489         function parseModuleBlock() {
24490             var node = createNode(250 /* ModuleBlock */);
24491             if (parseExpected(18 /* OpenBraceToken */)) {
24492                 node.statements = parseList(1 /* BlockStatements */, parseStatement);
24493                 parseExpected(19 /* CloseBraceToken */);
24494             }
24495             else {
24496                 node.statements = createMissingList();
24497             }
24498             return finishNode(node);
24499         }
24500         function parseModuleOrNamespaceDeclaration(node, flags) {
24501             node.kind = 249 /* ModuleDeclaration */;
24502             // If we are parsing a dotted namespace name, we want to
24503             // propagate the 'Namespace' flag across the names if set.
24504             var namespaceFlag = flags & 16 /* Namespace */;
24505             node.flags |= flags;
24506             node.name = parseIdentifier();
24507             node.body = parseOptional(24 /* DotToken */)
24508                 ? parseModuleOrNamespaceDeclaration(createNode(0 /* Unknown */), 4 /* NestedNamespace */ | namespaceFlag)
24509                 : parseModuleBlock();
24510             return finishNode(node);
24511         }
24512         function parseAmbientExternalModuleDeclaration(node) {
24513             node.kind = 249 /* ModuleDeclaration */;
24514             if (token() === 150 /* GlobalKeyword */) {
24515                 // parse 'global' as name of global scope augmentation
24516                 node.name = parseIdentifier();
24517                 node.flags |= 1024 /* GlobalAugmentation */;
24518             }
24519             else {
24520                 node.name = parseLiteralNode();
24521                 node.name.text = internIdentifier(node.name.text);
24522             }
24523             if (token() === 18 /* OpenBraceToken */) {
24524                 node.body = parseModuleBlock();
24525             }
24526             else {
24527                 parseSemicolon();
24528             }
24529             return finishNode(node);
24530         }
24531         function parseModuleDeclaration(node) {
24532             var flags = 0;
24533             if (token() === 150 /* GlobalKeyword */) {
24534                 // global augmentation
24535                 return parseAmbientExternalModuleDeclaration(node);
24536             }
24537             else if (parseOptional(136 /* NamespaceKeyword */)) {
24538                 flags |= 16 /* Namespace */;
24539             }
24540             else {
24541                 parseExpected(135 /* ModuleKeyword */);
24542                 if (token() === 10 /* StringLiteral */) {
24543                     return parseAmbientExternalModuleDeclaration(node);
24544                 }
24545             }
24546             return parseModuleOrNamespaceDeclaration(node, flags);
24547         }
24548         function isExternalModuleReference() {
24549             return token() === 139 /* RequireKeyword */ &&
24550                 lookAhead(nextTokenIsOpenParen);
24551         }
24552         function nextTokenIsOpenParen() {
24553             return nextToken() === 20 /* OpenParenToken */;
24554         }
24555         function nextTokenIsSlash() {
24556             return nextToken() === 43 /* SlashToken */;
24557         }
24558         function parseNamespaceExportDeclaration(node) {
24559             node.kind = 252 /* NamespaceExportDeclaration */;
24560             parseExpected(123 /* AsKeyword */);
24561             parseExpected(136 /* NamespaceKeyword */);
24562             node.name = parseIdentifier();
24563             parseSemicolon();
24564             return finishNode(node);
24565         }
24566         function parseImportDeclarationOrImportEqualsDeclaration(node) {
24567             parseExpected(96 /* ImportKeyword */);
24568             var afterImportPos = scanner.getStartPos();
24569             var identifier;
24570             if (isIdentifier()) {
24571                 identifier = parseIdentifier();
24572             }
24573             var isTypeOnly = false;
24574             if (token() !== 149 /* FromKeyword */ &&
24575                 (identifier === null || identifier === void 0 ? void 0 : identifier.escapedText) === "type" &&
24576                 (isIdentifier() || tokenAfterImportDefinitelyProducesImportDeclaration())) {
24577                 isTypeOnly = true;
24578                 identifier = isIdentifier() ? parseIdentifier() : undefined;
24579             }
24580             if (identifier && !tokenAfterImportedIdentifierDefinitelyProducesImportDeclaration()) {
24581                 return parseImportEqualsDeclaration(node, identifier, isTypeOnly);
24582             }
24583             // Import statement
24584             node.kind = 254 /* ImportDeclaration */;
24585             // ImportDeclaration:
24586             //  import ImportClause from ModuleSpecifier ;
24587             //  import ModuleSpecifier;
24588             if (identifier || // import id
24589                 token() === 41 /* AsteriskToken */ || // import *
24590                 token() === 18 /* OpenBraceToken */ // import {
24591             ) {
24592                 node.importClause = parseImportClause(identifier, afterImportPos, isTypeOnly);
24593                 parseExpected(149 /* FromKeyword */);
24594             }
24595             node.moduleSpecifier = parseModuleSpecifier();
24596             parseSemicolon();
24597             return finishNode(node);
24598         }
24599         function tokenAfterImportDefinitelyProducesImportDeclaration() {
24600             return token() === 41 /* AsteriskToken */ || token() === 18 /* OpenBraceToken */;
24601         }
24602         function tokenAfterImportedIdentifierDefinitelyProducesImportDeclaration() {
24603             // In `import id ___`, the current token decides whether to produce
24604             // an ImportDeclaration or ImportEqualsDeclaration.
24605             return token() === 27 /* CommaToken */ || token() === 149 /* FromKeyword */;
24606         }
24607         function parseImportEqualsDeclaration(node, identifier, isTypeOnly) {
24608             node.kind = 253 /* ImportEqualsDeclaration */;
24609             node.name = identifier;
24610             parseExpected(62 /* EqualsToken */);
24611             node.moduleReference = parseModuleReference();
24612             parseSemicolon();
24613             var finished = finishNode(node);
24614             if (isTypeOnly) {
24615                 parseErrorAtRange(finished, ts.Diagnostics.Only_ECMAScript_imports_may_use_import_type);
24616             }
24617             return finished;
24618         }
24619         function parseImportClause(identifier, fullStart, isTypeOnly) {
24620             // ImportClause:
24621             //  ImportedDefaultBinding
24622             //  NameSpaceImport
24623             //  NamedImports
24624             //  ImportedDefaultBinding, NameSpaceImport
24625             //  ImportedDefaultBinding, NamedImports
24626             var importClause = createNode(255 /* ImportClause */, fullStart);
24627             importClause.isTypeOnly = isTypeOnly;
24628             if (identifier) {
24629                 // ImportedDefaultBinding:
24630                 //  ImportedBinding
24631                 importClause.name = identifier;
24632             }
24633             // If there was no default import or if there is comma token after default import
24634             // parse namespace or named imports
24635             if (!importClause.name ||
24636                 parseOptional(27 /* CommaToken */)) {
24637                 importClause.namedBindings = token() === 41 /* AsteriskToken */ ? parseNamespaceImport() : parseNamedImportsOrExports(257 /* NamedImports */);
24638             }
24639             return finishNode(importClause);
24640         }
24641         function parseModuleReference() {
24642             return isExternalModuleReference()
24643                 ? parseExternalModuleReference()
24644                 : parseEntityName(/*allowReservedWords*/ false);
24645         }
24646         function parseExternalModuleReference() {
24647             var node = createNode(265 /* ExternalModuleReference */);
24648             parseExpected(139 /* RequireKeyword */);
24649             parseExpected(20 /* OpenParenToken */);
24650             node.expression = parseModuleSpecifier();
24651             parseExpected(21 /* CloseParenToken */);
24652             return finishNode(node);
24653         }
24654         function parseModuleSpecifier() {
24655             if (token() === 10 /* StringLiteral */) {
24656                 var result = parseLiteralNode();
24657                 result.text = internIdentifier(result.text);
24658                 return result;
24659             }
24660             else {
24661                 // We allow arbitrary expressions here, even though the grammar only allows string
24662                 // literals.  We check to ensure that it is only a string literal later in the grammar
24663                 // check pass.
24664                 return parseExpression();
24665             }
24666         }
24667         function parseNamespaceImport() {
24668             // NameSpaceImport:
24669             //  * as ImportedBinding
24670             var namespaceImport = createNode(256 /* NamespaceImport */);
24671             parseExpected(41 /* AsteriskToken */);
24672             parseExpected(123 /* AsKeyword */);
24673             namespaceImport.name = parseIdentifier();
24674             return finishNode(namespaceImport);
24675         }
24676         function parseNamedImportsOrExports(kind) {
24677             var node = createNode(kind);
24678             // NamedImports:
24679             //  { }
24680             //  { ImportsList }
24681             //  { ImportsList, }
24682             // ImportsList:
24683             //  ImportSpecifier
24684             //  ImportsList, ImportSpecifier
24685             node.elements = parseBracketedList(23 /* ImportOrExportSpecifiers */, kind === 257 /* NamedImports */ ? parseImportSpecifier : parseExportSpecifier, 18 /* OpenBraceToken */, 19 /* CloseBraceToken */);
24686             return finishNode(node);
24687         }
24688         function parseExportSpecifier() {
24689             return parseImportOrExportSpecifier(263 /* ExportSpecifier */);
24690         }
24691         function parseImportSpecifier() {
24692             return parseImportOrExportSpecifier(258 /* ImportSpecifier */);
24693         }
24694         function parseImportOrExportSpecifier(kind) {
24695             var node = createNode(kind);
24696             // ImportSpecifier:
24697             //   BindingIdentifier
24698             //   IdentifierName as BindingIdentifier
24699             // ExportSpecifier:
24700             //   IdentifierName
24701             //   IdentifierName as IdentifierName
24702             var checkIdentifierIsKeyword = ts.isKeyword(token()) && !isIdentifier();
24703             var checkIdentifierStart = scanner.getTokenPos();
24704             var checkIdentifierEnd = scanner.getTextPos();
24705             var identifierName = parseIdentifierName();
24706             if (token() === 123 /* AsKeyword */) {
24707                 node.propertyName = identifierName;
24708                 parseExpected(123 /* AsKeyword */);
24709                 checkIdentifierIsKeyword = ts.isKeyword(token()) && !isIdentifier();
24710                 checkIdentifierStart = scanner.getTokenPos();
24711                 checkIdentifierEnd = scanner.getTextPos();
24712                 node.name = parseIdentifierName();
24713             }
24714             else {
24715                 node.name = identifierName;
24716             }
24717             if (kind === 258 /* ImportSpecifier */ && checkIdentifierIsKeyword) {
24718                 parseErrorAt(checkIdentifierStart, checkIdentifierEnd, ts.Diagnostics.Identifier_expected);
24719             }
24720             return finishNode(node);
24721         }
24722         function parseNamespaceExport(pos) {
24723             var node = createNode(262 /* NamespaceExport */, pos);
24724             node.name = parseIdentifier();
24725             return finishNode(node);
24726         }
24727         function parseExportDeclaration(node) {
24728             node.kind = 260 /* ExportDeclaration */;
24729             node.isTypeOnly = parseOptional(145 /* TypeKeyword */);
24730             var namespaceExportPos = scanner.getStartPos();
24731             if (parseOptional(41 /* AsteriskToken */)) {
24732                 if (parseOptional(123 /* AsKeyword */)) {
24733                     node.exportClause = parseNamespaceExport(namespaceExportPos);
24734                 }
24735                 parseExpected(149 /* FromKeyword */);
24736                 node.moduleSpecifier = parseModuleSpecifier();
24737             }
24738             else {
24739                 node.exportClause = parseNamedImportsOrExports(261 /* NamedExports */);
24740                 // It is not uncommon to accidentally omit the 'from' keyword. Additionally, in editing scenarios,
24741                 // the 'from' keyword can be parsed as a named export when the export clause is unterminated (i.e. `export { from "moduleName";`)
24742                 // If we don't have a 'from' keyword, see if we have a string literal such that ASI won't take effect.
24743                 if (token() === 149 /* FromKeyword */ || (token() === 10 /* StringLiteral */ && !scanner.hasPrecedingLineBreak())) {
24744                     parseExpected(149 /* FromKeyword */);
24745                     node.moduleSpecifier = parseModuleSpecifier();
24746                 }
24747             }
24748             parseSemicolon();
24749             return finishNode(node);
24750         }
24751         function parseExportAssignment(node) {
24752             node.kind = 259 /* ExportAssignment */;
24753             if (parseOptional(62 /* EqualsToken */)) {
24754                 node.isExportEquals = true;
24755             }
24756             else {
24757                 parseExpected(84 /* DefaultKeyword */);
24758             }
24759             node.expression = parseAssignmentExpressionOrHigher();
24760             parseSemicolon();
24761             return finishNode(node);
24762         }
24763         function setExternalModuleIndicator(sourceFile) {
24764             // Try to use the first top-level import/export when available, then
24765             // fall back to looking for an 'import.meta' somewhere in the tree if necessary.
24766             sourceFile.externalModuleIndicator =
24767                 ts.forEach(sourceFile.statements, isAnExternalModuleIndicatorNode) ||
24768                     getImportMetaIfNecessary(sourceFile);
24769         }
24770         function isAnExternalModuleIndicatorNode(node) {
24771             return hasModifierOfKind(node, 89 /* ExportKeyword */)
24772                 || node.kind === 253 /* ImportEqualsDeclaration */ && node.moduleReference.kind === 265 /* ExternalModuleReference */
24773                 || node.kind === 254 /* ImportDeclaration */
24774                 || node.kind === 259 /* ExportAssignment */
24775                 || node.kind === 260 /* ExportDeclaration */ ? node : undefined;
24776         }
24777         function getImportMetaIfNecessary(sourceFile) {
24778             return sourceFile.flags & 2097152 /* PossiblyContainsImportMeta */ ?
24779                 walkTreeForExternalModuleIndicators(sourceFile) :
24780                 undefined;
24781         }
24782         function walkTreeForExternalModuleIndicators(node) {
24783             return isImportMeta(node) ? node : forEachChild(node, walkTreeForExternalModuleIndicators);
24784         }
24785         /** Do not use hasModifier inside the parser; it relies on parent pointers. Use this instead. */
24786         function hasModifierOfKind(node, kind) {
24787             return ts.some(node.modifiers, function (m) { return m.kind === kind; });
24788         }
24789         function isImportMeta(node) {
24790             return ts.isMetaProperty(node) && node.keywordToken === 96 /* ImportKeyword */ && node.name.escapedText === "meta";
24791         }
24792         var ParsingContext;
24793         (function (ParsingContext) {
24794             ParsingContext[ParsingContext["SourceElements"] = 0] = "SourceElements";
24795             ParsingContext[ParsingContext["BlockStatements"] = 1] = "BlockStatements";
24796             ParsingContext[ParsingContext["SwitchClauses"] = 2] = "SwitchClauses";
24797             ParsingContext[ParsingContext["SwitchClauseStatements"] = 3] = "SwitchClauseStatements";
24798             ParsingContext[ParsingContext["TypeMembers"] = 4] = "TypeMembers";
24799             ParsingContext[ParsingContext["ClassMembers"] = 5] = "ClassMembers";
24800             ParsingContext[ParsingContext["EnumMembers"] = 6] = "EnumMembers";
24801             ParsingContext[ParsingContext["HeritageClauseElement"] = 7] = "HeritageClauseElement";
24802             ParsingContext[ParsingContext["VariableDeclarations"] = 8] = "VariableDeclarations";
24803             ParsingContext[ParsingContext["ObjectBindingElements"] = 9] = "ObjectBindingElements";
24804             ParsingContext[ParsingContext["ArrayBindingElements"] = 10] = "ArrayBindingElements";
24805             ParsingContext[ParsingContext["ArgumentExpressions"] = 11] = "ArgumentExpressions";
24806             ParsingContext[ParsingContext["ObjectLiteralMembers"] = 12] = "ObjectLiteralMembers";
24807             ParsingContext[ParsingContext["JsxAttributes"] = 13] = "JsxAttributes";
24808             ParsingContext[ParsingContext["JsxChildren"] = 14] = "JsxChildren";
24809             ParsingContext[ParsingContext["ArrayLiteralMembers"] = 15] = "ArrayLiteralMembers";
24810             ParsingContext[ParsingContext["Parameters"] = 16] = "Parameters";
24811             ParsingContext[ParsingContext["JSDocParameters"] = 17] = "JSDocParameters";
24812             ParsingContext[ParsingContext["RestProperties"] = 18] = "RestProperties";
24813             ParsingContext[ParsingContext["TypeParameters"] = 19] = "TypeParameters";
24814             ParsingContext[ParsingContext["TypeArguments"] = 20] = "TypeArguments";
24815             ParsingContext[ParsingContext["TupleElementTypes"] = 21] = "TupleElementTypes";
24816             ParsingContext[ParsingContext["HeritageClauses"] = 22] = "HeritageClauses";
24817             ParsingContext[ParsingContext["ImportOrExportSpecifiers"] = 23] = "ImportOrExportSpecifiers";
24818             ParsingContext[ParsingContext["Count"] = 24] = "Count"; // Number of parsing contexts
24819         })(ParsingContext || (ParsingContext = {}));
24820         var Tristate;
24821         (function (Tristate) {
24822             Tristate[Tristate["False"] = 0] = "False";
24823             Tristate[Tristate["True"] = 1] = "True";
24824             Tristate[Tristate["Unknown"] = 2] = "Unknown";
24825         })(Tristate || (Tristate = {}));
24826         var JSDocParser;
24827         (function (JSDocParser) {
24828             function parseJSDocTypeExpressionForTests(content, start, length) {
24829                 initializeState(content, 99 /* Latest */, /*_syntaxCursor:*/ undefined, 1 /* JS */);
24830                 sourceFile = createSourceFile("file.js", 99 /* Latest */, 1 /* JS */, /*isDeclarationFile*/ false);
24831                 scanner.setText(content, start, length);
24832                 currentToken = scanner.scan();
24833                 var jsDocTypeExpression = parseJSDocTypeExpression();
24834                 var diagnostics = parseDiagnostics;
24835                 clearState();
24836                 return jsDocTypeExpression ? { jsDocTypeExpression: jsDocTypeExpression, diagnostics: diagnostics } : undefined;
24837             }
24838             JSDocParser.parseJSDocTypeExpressionForTests = parseJSDocTypeExpressionForTests;
24839             // Parses out a JSDoc type expression.
24840             function parseJSDocTypeExpression(mayOmitBraces) {
24841                 var result = createNode(294 /* JSDocTypeExpression */);
24842                 var hasBrace = (mayOmitBraces ? parseOptional : parseExpected)(18 /* OpenBraceToken */);
24843                 result.type = doInsideOfContext(4194304 /* JSDoc */, parseJSDocType);
24844                 if (!mayOmitBraces || hasBrace) {
24845                     parseExpectedJSDoc(19 /* CloseBraceToken */);
24846                 }
24847                 fixupParentReferences(result);
24848                 return finishNode(result);
24849             }
24850             JSDocParser.parseJSDocTypeExpression = parseJSDocTypeExpression;
24851             function parseIsolatedJSDocComment(content, start, length) {
24852                 initializeState(content, 99 /* Latest */, /*_syntaxCursor:*/ undefined, 1 /* JS */);
24853                 sourceFile = { languageVariant: 0 /* Standard */, text: content };
24854                 var jsDoc = doInsideOfContext(4194304 /* JSDoc */, function () { return parseJSDocCommentWorker(start, length); });
24855                 var diagnostics = parseDiagnostics;
24856                 clearState();
24857                 return jsDoc ? { jsDoc: jsDoc, diagnostics: diagnostics } : undefined;
24858             }
24859             JSDocParser.parseIsolatedJSDocComment = parseIsolatedJSDocComment;
24860             function parseJSDocComment(parent, start, length) {
24861                 var _a;
24862                 var saveToken = currentToken;
24863                 var saveParseDiagnosticsLength = parseDiagnostics.length;
24864                 var saveParseErrorBeforeNextFinishedNode = parseErrorBeforeNextFinishedNode;
24865                 var comment = doInsideOfContext(4194304 /* JSDoc */, function () { return parseJSDocCommentWorker(start, length); });
24866                 if (comment) {
24867                     comment.parent = parent;
24868                 }
24869                 if (contextFlags & 131072 /* JavaScriptFile */) {
24870                     if (!sourceFile.jsDocDiagnostics) {
24871                         sourceFile.jsDocDiagnostics = [];
24872                     }
24873                     (_a = sourceFile.jsDocDiagnostics).push.apply(_a, parseDiagnostics);
24874                 }
24875                 currentToken = saveToken;
24876                 parseDiagnostics.length = saveParseDiagnosticsLength;
24877                 parseErrorBeforeNextFinishedNode = saveParseErrorBeforeNextFinishedNode;
24878                 return comment;
24879             }
24880             JSDocParser.parseJSDocComment = parseJSDocComment;
24881             var JSDocState;
24882             (function (JSDocState) {
24883                 JSDocState[JSDocState["BeginningOfLine"] = 0] = "BeginningOfLine";
24884                 JSDocState[JSDocState["SawAsterisk"] = 1] = "SawAsterisk";
24885                 JSDocState[JSDocState["SavingComments"] = 2] = "SavingComments";
24886                 JSDocState[JSDocState["SavingBackticks"] = 3] = "SavingBackticks";
24887             })(JSDocState || (JSDocState = {}));
24888             var PropertyLikeParse;
24889             (function (PropertyLikeParse) {
24890                 PropertyLikeParse[PropertyLikeParse["Property"] = 1] = "Property";
24891                 PropertyLikeParse[PropertyLikeParse["Parameter"] = 2] = "Parameter";
24892                 PropertyLikeParse[PropertyLikeParse["CallbackParameter"] = 4] = "CallbackParameter";
24893             })(PropertyLikeParse || (PropertyLikeParse = {}));
24894             function parseJSDocCommentWorker(start, length) {
24895                 if (start === void 0) { start = 0; }
24896                 var content = sourceText;
24897                 var end = length === undefined ? content.length : start + length;
24898                 length = end - start;
24899                 ts.Debug.assert(start >= 0);
24900                 ts.Debug.assert(start <= end);
24901                 ts.Debug.assert(end <= content.length);
24902                 // Check for /** (JSDoc opening part)
24903                 if (!isJSDocLikeText(content, start)) {
24904                     return undefined;
24905                 }
24906                 var tags;
24907                 var tagsPos;
24908                 var tagsEnd;
24909                 var comments = [];
24910                 // + 3 for leading /**, - 5 in total for /** */
24911                 return scanner.scanRange(start + 3, length - 5, function () {
24912                     // Initially we can parse out a tag.  We also have seen a starting asterisk.
24913                     // This is so that /** * @type */ doesn't parse.
24914                     var state = 1 /* SawAsterisk */;
24915                     var margin;
24916                     // + 4 for leading '/** '
24917                     var indent = start - Math.max(content.lastIndexOf("\n", start), 0) + 4;
24918                     function pushComment(text) {
24919                         if (!margin) {
24920                             margin = indent;
24921                         }
24922                         comments.push(text);
24923                         indent += text.length;
24924                     }
24925                     nextTokenJSDoc();
24926                     while (parseOptionalJsdoc(5 /* WhitespaceTrivia */))
24927                         ;
24928                     if (parseOptionalJsdoc(4 /* NewLineTrivia */)) {
24929                         state = 0 /* BeginningOfLine */;
24930                         indent = 0;
24931                     }
24932                     loop: while (true) {
24933                         switch (token()) {
24934                             case 59 /* AtToken */:
24935                                 if (state === 0 /* BeginningOfLine */ || state === 1 /* SawAsterisk */) {
24936                                     removeTrailingWhitespace(comments);
24937                                     addTag(parseTag(indent));
24938                                     // NOTE: According to usejsdoc.org, a tag goes to end of line, except the last tag.
24939                                     // Real-world comments may break this rule, so "BeginningOfLine" will not be a real line beginning
24940                                     // for malformed examples like `/** @param {string} x @returns {number} the length */`
24941                                     state = 0 /* BeginningOfLine */;
24942                                     margin = undefined;
24943                                 }
24944                                 else {
24945                                     pushComment(scanner.getTokenText());
24946                                 }
24947                                 break;
24948                             case 4 /* NewLineTrivia */:
24949                                 comments.push(scanner.getTokenText());
24950                                 state = 0 /* BeginningOfLine */;
24951                                 indent = 0;
24952                                 break;
24953                             case 41 /* AsteriskToken */:
24954                                 var asterisk = scanner.getTokenText();
24955                                 if (state === 1 /* SawAsterisk */ || state === 2 /* SavingComments */) {
24956                                     // If we've already seen an asterisk, then we can no longer parse a tag on this line
24957                                     state = 2 /* SavingComments */;
24958                                     pushComment(asterisk);
24959                                 }
24960                                 else {
24961                                     // Ignore the first asterisk on a line
24962                                     state = 1 /* SawAsterisk */;
24963                                     indent += asterisk.length;
24964                                 }
24965                                 break;
24966                             case 5 /* WhitespaceTrivia */:
24967                                 // only collect whitespace if we're already saving comments or have just crossed the comment indent margin
24968                                 var whitespace = scanner.getTokenText();
24969                                 if (state === 2 /* SavingComments */) {
24970                                     comments.push(whitespace);
24971                                 }
24972                                 else if (margin !== undefined && indent + whitespace.length > margin) {
24973                                     comments.push(whitespace.slice(margin - indent - 1));
24974                                 }
24975                                 indent += whitespace.length;
24976                                 break;
24977                             case 1 /* EndOfFileToken */:
24978                                 break loop;
24979                             default:
24980                                 // Anything else is doc comment text. We just save it. Because it
24981                                 // wasn't a tag, we can no longer parse a tag on this line until we hit the next
24982                                 // line break.
24983                                 state = 2 /* SavingComments */;
24984                                 pushComment(scanner.getTokenText());
24985                                 break;
24986                         }
24987                         nextTokenJSDoc();
24988                     }
24989                     removeLeadingNewlines(comments);
24990                     removeTrailingWhitespace(comments);
24991                     return createJSDocComment();
24992                 });
24993                 function removeLeadingNewlines(comments) {
24994                     while (comments.length && (comments[0] === "\n" || comments[0] === "\r")) {
24995                         comments.shift();
24996                     }
24997                 }
24998                 function removeTrailingWhitespace(comments) {
24999                     while (comments.length && comments[comments.length - 1].trim() === "") {
25000                         comments.pop();
25001                     }
25002                 }
25003                 function createJSDocComment() {
25004                     var result = createNode(303 /* JSDocComment */, start);
25005                     result.tags = tags && createNodeArray(tags, tagsPos, tagsEnd);
25006                     result.comment = comments.length ? comments.join("") : undefined;
25007                     return finishNode(result, end);
25008                 }
25009                 function isNextNonwhitespaceTokenEndOfFile() {
25010                     // We must use infinite lookahead, as there could be any number of newlines :(
25011                     while (true) {
25012                         nextTokenJSDoc();
25013                         if (token() === 1 /* EndOfFileToken */) {
25014                             return true;
25015                         }
25016                         if (!(token() === 5 /* WhitespaceTrivia */ || token() === 4 /* NewLineTrivia */)) {
25017                             return false;
25018                         }
25019                     }
25020                 }
25021                 function skipWhitespace() {
25022                     if (token() === 5 /* WhitespaceTrivia */ || token() === 4 /* NewLineTrivia */) {
25023                         if (lookAhead(isNextNonwhitespaceTokenEndOfFile)) {
25024                             return; // Don't skip whitespace prior to EoF (or end of comment) - that shouldn't be included in any node's range
25025                         }
25026                     }
25027                     while (token() === 5 /* WhitespaceTrivia */ || token() === 4 /* NewLineTrivia */) {
25028                         nextTokenJSDoc();
25029                     }
25030                 }
25031                 function skipWhitespaceOrAsterisk() {
25032                     if (token() === 5 /* WhitespaceTrivia */ || token() === 4 /* NewLineTrivia */) {
25033                         if (lookAhead(isNextNonwhitespaceTokenEndOfFile)) {
25034                             return ""; // Don't skip whitespace prior to EoF (or end of comment) - that shouldn't be included in any node's range
25035                         }
25036                     }
25037                     var precedingLineBreak = scanner.hasPrecedingLineBreak();
25038                     var seenLineBreak = false;
25039                     var indentText = "";
25040                     while ((precedingLineBreak && token() === 41 /* AsteriskToken */) || token() === 5 /* WhitespaceTrivia */ || token() === 4 /* NewLineTrivia */) {
25041                         indentText += scanner.getTokenText();
25042                         if (token() === 4 /* NewLineTrivia */) {
25043                             precedingLineBreak = true;
25044                             seenLineBreak = true;
25045                             indentText = "";
25046                         }
25047                         else if (token() === 41 /* AsteriskToken */) {
25048                             precedingLineBreak = false;
25049                         }
25050                         nextTokenJSDoc();
25051                     }
25052                     return seenLineBreak ? indentText : "";
25053                 }
25054                 function parseTag(margin) {
25055                     ts.Debug.assert(token() === 59 /* AtToken */);
25056                     var start = scanner.getTokenPos();
25057                     nextTokenJSDoc();
25058                     var tagName = parseJSDocIdentifierName(/*message*/ undefined);
25059                     var indentText = skipWhitespaceOrAsterisk();
25060                     var tag;
25061                     switch (tagName.escapedText) {
25062                         case "author":
25063                             tag = parseAuthorTag(start, tagName, margin);
25064                             break;
25065                         case "implements":
25066                             tag = parseImplementsTag(start, tagName);
25067                             break;
25068                         case "augments":
25069                         case "extends":
25070                             tag = parseAugmentsTag(start, tagName);
25071                             break;
25072                         case "class":
25073                         case "constructor":
25074                             tag = parseSimpleTag(start, 310 /* JSDocClassTag */, tagName);
25075                             break;
25076                         case "public":
25077                             tag = parseSimpleTag(start, 311 /* JSDocPublicTag */, tagName);
25078                             break;
25079                         case "private":
25080                             tag = parseSimpleTag(start, 312 /* JSDocPrivateTag */, tagName);
25081                             break;
25082                         case "protected":
25083                             tag = parseSimpleTag(start, 313 /* JSDocProtectedTag */, tagName);
25084                             break;
25085                         case "readonly":
25086                             tag = parseSimpleTag(start, 314 /* JSDocReadonlyTag */, tagName);
25087                             break;
25088                         case "this":
25089                             tag = parseThisTag(start, tagName);
25090                             break;
25091                         case "enum":
25092                             tag = parseEnumTag(start, tagName);
25093                             break;
25094                         case "arg":
25095                         case "argument":
25096                         case "param":
25097                             return parseParameterOrPropertyTag(start, tagName, 2 /* Parameter */, margin);
25098                         case "return":
25099                         case "returns":
25100                             tag = parseReturnTag(start, tagName);
25101                             break;
25102                         case "template":
25103                             tag = parseTemplateTag(start, tagName);
25104                             break;
25105                         case "type":
25106                             tag = parseTypeTag(start, tagName);
25107                             break;
25108                         case "typedef":
25109                             tag = parseTypedefTag(start, tagName, margin);
25110                             break;
25111                         case "callback":
25112                             tag = parseCallbackTag(start, tagName, margin);
25113                             break;
25114                         default:
25115                             tag = parseUnknownTag(start, tagName);
25116                             break;
25117                     }
25118                     if (!tag.comment) {
25119                         // some tags, like typedef and callback, have already parsed their comments earlier
25120                         if (!indentText) {
25121                             margin += tag.end - tag.pos;
25122                         }
25123                         tag.comment = parseTagComments(margin, indentText.slice(margin));
25124                     }
25125                     return tag;
25126                 }
25127                 function parseTagComments(indent, initialMargin) {
25128                     var comments = [];
25129                     var state = 0 /* BeginningOfLine */;
25130                     var margin;
25131                     function pushComment(text) {
25132                         if (!margin) {
25133                             margin = indent;
25134                         }
25135                         comments.push(text);
25136                         indent += text.length;
25137                     }
25138                     if (initialMargin !== undefined) {
25139                         // jump straight to saving comments if there is some initial indentation
25140                         if (initialMargin !== "") {
25141                             pushComment(initialMargin);
25142                         }
25143                         state = 1 /* SawAsterisk */;
25144                     }
25145                     var tok = token();
25146                     loop: while (true) {
25147                         switch (tok) {
25148                             case 4 /* NewLineTrivia */:
25149                                 if (state >= 1 /* SawAsterisk */) {
25150                                     state = 0 /* BeginningOfLine */;
25151                                     // don't use pushComment here because we want to keep the margin unchanged
25152                                     comments.push(scanner.getTokenText());
25153                                 }
25154                                 indent = 0;
25155                                 break;
25156                             case 59 /* AtToken */:
25157                                 if (state === 3 /* SavingBackticks */) {
25158                                     comments.push(scanner.getTokenText());
25159                                     break;
25160                                 }
25161                                 scanner.setTextPos(scanner.getTextPos() - 1);
25162                             // falls through
25163                             case 1 /* EndOfFileToken */:
25164                                 // Done
25165                                 break loop;
25166                             case 5 /* WhitespaceTrivia */:
25167                                 if (state === 2 /* SavingComments */ || state === 3 /* SavingBackticks */) {
25168                                     pushComment(scanner.getTokenText());
25169                                 }
25170                                 else {
25171                                     var whitespace = scanner.getTokenText();
25172                                     // if the whitespace crosses the margin, take only the whitespace that passes the margin
25173                                     if (margin !== undefined && indent + whitespace.length > margin) {
25174                                         comments.push(whitespace.slice(margin - indent));
25175                                     }
25176                                     indent += whitespace.length;
25177                                 }
25178                                 break;
25179                             case 18 /* OpenBraceToken */:
25180                                 state = 2 /* SavingComments */;
25181                                 if (lookAhead(function () { return nextTokenJSDoc() === 59 /* AtToken */ && ts.tokenIsIdentifierOrKeyword(nextTokenJSDoc()) && scanner.getTokenText() === "link"; })) {
25182                                     pushComment(scanner.getTokenText());
25183                                     nextTokenJSDoc();
25184                                     pushComment(scanner.getTokenText());
25185                                     nextTokenJSDoc();
25186                                 }
25187                                 pushComment(scanner.getTokenText());
25188                                 break;
25189                             case 61 /* BacktickToken */:
25190                                 if (state === 3 /* SavingBackticks */) {
25191                                     state = 2 /* SavingComments */;
25192                                 }
25193                                 else {
25194                                     state = 3 /* SavingBackticks */;
25195                                 }
25196                                 pushComment(scanner.getTokenText());
25197                                 break;
25198                             case 41 /* AsteriskToken */:
25199                                 if (state === 0 /* BeginningOfLine */) {
25200                                     // leading asterisks start recording on the *next* (non-whitespace) token
25201                                     state = 1 /* SawAsterisk */;
25202                                     indent += 1;
25203                                     break;
25204                                 }
25205                             // record the * as a comment
25206                             // falls through
25207                             default:
25208                                 if (state !== 3 /* SavingBackticks */) {
25209                                     state = 2 /* SavingComments */; // leading identifiers start recording as well
25210                                 }
25211                                 pushComment(scanner.getTokenText());
25212                                 break;
25213                         }
25214                         tok = nextTokenJSDoc();
25215                     }
25216                     removeLeadingNewlines(comments);
25217                     removeTrailingWhitespace(comments);
25218                     return comments.length === 0 ? undefined : comments.join("");
25219                 }
25220                 function parseUnknownTag(start, tagName) {
25221                     var result = createNode(306 /* JSDocTag */, start);
25222                     result.tagName = tagName;
25223                     return finishNode(result);
25224                 }
25225                 function addTag(tag) {
25226                     if (!tag) {
25227                         return;
25228                     }
25229                     if (!tags) {
25230                         tags = [tag];
25231                         tagsPos = tag.pos;
25232                     }
25233                     else {
25234                         tags.push(tag);
25235                     }
25236                     tagsEnd = tag.end;
25237                 }
25238                 function tryParseTypeExpression() {
25239                     skipWhitespaceOrAsterisk();
25240                     return token() === 18 /* OpenBraceToken */ ? parseJSDocTypeExpression() : undefined;
25241                 }
25242                 function parseBracketNameInPropertyAndParamTag() {
25243                     // Looking for something like '[foo]', 'foo', '[foo.bar]' or 'foo.bar'
25244                     var isBracketed = parseOptionalJsdoc(22 /* OpenBracketToken */);
25245                     if (isBracketed) {
25246                         skipWhitespace();
25247                     }
25248                     // a markdown-quoted name: `arg` is not legal jsdoc, but occurs in the wild
25249                     var isBackquoted = parseOptionalJsdoc(61 /* BacktickToken */);
25250                     var name = parseJSDocEntityName();
25251                     if (isBackquoted) {
25252                         parseExpectedTokenJSDoc(61 /* BacktickToken */);
25253                     }
25254                     if (isBracketed) {
25255                         skipWhitespace();
25256                         // May have an optional default, e.g. '[foo = 42]'
25257                         if (parseOptionalToken(62 /* EqualsToken */)) {
25258                             parseExpression();
25259                         }
25260                         parseExpected(23 /* CloseBracketToken */);
25261                     }
25262                     return { name: name, isBracketed: isBracketed };
25263                 }
25264                 function isObjectOrObjectArrayTypeReference(node) {
25265                     switch (node.kind) {
25266                         case 141 /* ObjectKeyword */:
25267                             return true;
25268                         case 174 /* ArrayType */:
25269                             return isObjectOrObjectArrayTypeReference(node.elementType);
25270                         default:
25271                             return ts.isTypeReferenceNode(node) && ts.isIdentifier(node.typeName) && node.typeName.escapedText === "Object" && !node.typeArguments;
25272                     }
25273                 }
25274                 function parseParameterOrPropertyTag(start, tagName, target, indent) {
25275                     var typeExpression = tryParseTypeExpression();
25276                     var isNameFirst = !typeExpression;
25277                     skipWhitespaceOrAsterisk();
25278                     var _a = parseBracketNameInPropertyAndParamTag(), name = _a.name, isBracketed = _a.isBracketed;
25279                     skipWhitespace();
25280                     if (isNameFirst) {
25281                         typeExpression = tryParseTypeExpression();
25282                     }
25283                     var result = target === 1 /* Property */ ?
25284                         createNode(323 /* JSDocPropertyTag */, start) :
25285                         createNode(317 /* JSDocParameterTag */, start);
25286                     var comment = parseTagComments(indent + scanner.getStartPos() - start);
25287                     var nestedTypeLiteral = target !== 4 /* CallbackParameter */ && parseNestedTypeLiteral(typeExpression, name, target, indent);
25288                     if (nestedTypeLiteral) {
25289                         typeExpression = nestedTypeLiteral;
25290                         isNameFirst = true;
25291                     }
25292                     result.tagName = tagName;
25293                     result.typeExpression = typeExpression;
25294                     result.name = name;
25295                     result.isNameFirst = isNameFirst;
25296                     result.isBracketed = isBracketed;
25297                     result.comment = comment;
25298                     return finishNode(result);
25299                 }
25300                 function parseNestedTypeLiteral(typeExpression, name, target, indent) {
25301                     if (typeExpression && isObjectOrObjectArrayTypeReference(typeExpression.type)) {
25302                         var typeLiteralExpression = createNode(294 /* JSDocTypeExpression */, scanner.getTokenPos());
25303                         var child = void 0;
25304                         var jsdocTypeLiteral = void 0;
25305                         var start_3 = scanner.getStartPos();
25306                         var children = void 0;
25307                         while (child = tryParse(function () { return parseChildParameterOrPropertyTag(target, indent, name); })) {
25308                             if (child.kind === 317 /* JSDocParameterTag */ || child.kind === 323 /* JSDocPropertyTag */) {
25309                                 children = ts.append(children, child);
25310                             }
25311                         }
25312                         if (children) {
25313                             jsdocTypeLiteral = createNode(304 /* JSDocTypeLiteral */, start_3);
25314                             jsdocTypeLiteral.jsDocPropertyTags = children;
25315                             if (typeExpression.type.kind === 174 /* ArrayType */) {
25316                                 jsdocTypeLiteral.isArrayType = true;
25317                             }
25318                             typeLiteralExpression.type = finishNode(jsdocTypeLiteral);
25319                             return finishNode(typeLiteralExpression);
25320                         }
25321                     }
25322                 }
25323                 function parseReturnTag(start, tagName) {
25324                     if (ts.some(tags, ts.isJSDocReturnTag)) {
25325                         parseErrorAt(tagName.pos, scanner.getTokenPos(), ts.Diagnostics._0_tag_already_specified, tagName.escapedText);
25326                     }
25327                     var result = createNode(318 /* JSDocReturnTag */, start);
25328                     result.tagName = tagName;
25329                     result.typeExpression = tryParseTypeExpression();
25330                     return finishNode(result);
25331                 }
25332                 function parseTypeTag(start, tagName) {
25333                     if (ts.some(tags, ts.isJSDocTypeTag)) {
25334                         parseErrorAt(tagName.pos, scanner.getTokenPos(), ts.Diagnostics._0_tag_already_specified, tagName.escapedText);
25335                     }
25336                     var result = createNode(320 /* JSDocTypeTag */, start);
25337                     result.tagName = tagName;
25338                     result.typeExpression = parseJSDocTypeExpression(/*mayOmitBraces*/ true);
25339                     return finishNode(result);
25340                 }
25341                 function parseAuthorTag(start, tagName, indent) {
25342                     var result = createNode(309 /* JSDocAuthorTag */, start);
25343                     result.tagName = tagName;
25344                     var authorInfoWithEmail = tryParse(function () { return tryParseAuthorNameAndEmail(); });
25345                     if (!authorInfoWithEmail) {
25346                         return finishNode(result);
25347                     }
25348                     result.comment = authorInfoWithEmail;
25349                     if (lookAhead(function () { return nextToken() !== 4 /* NewLineTrivia */; })) {
25350                         var comment = parseTagComments(indent);
25351                         if (comment) {
25352                             result.comment += comment;
25353                         }
25354                     }
25355                     return finishNode(result);
25356                 }
25357                 function tryParseAuthorNameAndEmail() {
25358                     var comments = [];
25359                     var seenLessThan = false;
25360                     var seenGreaterThan = false;
25361                     var token = scanner.getToken();
25362                     loop: while (true) {
25363                         switch (token) {
25364                             case 75 /* Identifier */:
25365                             case 5 /* WhitespaceTrivia */:
25366                             case 24 /* DotToken */:
25367                             case 59 /* AtToken */:
25368                                 comments.push(scanner.getTokenText());
25369                                 break;
25370                             case 29 /* LessThanToken */:
25371                                 if (seenLessThan || seenGreaterThan) {
25372                                     return;
25373                                 }
25374                                 seenLessThan = true;
25375                                 comments.push(scanner.getTokenText());
25376                                 break;
25377                             case 31 /* GreaterThanToken */:
25378                                 if (!seenLessThan || seenGreaterThan) {
25379                                     return;
25380                                 }
25381                                 seenGreaterThan = true;
25382                                 comments.push(scanner.getTokenText());
25383                                 scanner.setTextPos(scanner.getTokenPos() + 1);
25384                                 break loop;
25385                             case 4 /* NewLineTrivia */:
25386                             case 1 /* EndOfFileToken */:
25387                                 break loop;
25388                         }
25389                         token = nextTokenJSDoc();
25390                     }
25391                     if (seenLessThan && seenGreaterThan) {
25392                         return comments.length === 0 ? undefined : comments.join("");
25393                     }
25394                 }
25395                 function parseImplementsTag(start, tagName) {
25396                     var result = createNode(308 /* JSDocImplementsTag */, start);
25397                     result.tagName = tagName;
25398                     result.class = parseExpressionWithTypeArgumentsForAugments();
25399                     return finishNode(result);
25400                 }
25401                 function parseAugmentsTag(start, tagName) {
25402                     var result = createNode(307 /* JSDocAugmentsTag */, start);
25403                     result.tagName = tagName;
25404                     result.class = parseExpressionWithTypeArgumentsForAugments();
25405                     return finishNode(result);
25406                 }
25407                 function parseExpressionWithTypeArgumentsForAugments() {
25408                     var usedBrace = parseOptional(18 /* OpenBraceToken */);
25409                     var node = createNode(216 /* ExpressionWithTypeArguments */);
25410                     node.expression = parsePropertyAccessEntityNameExpression();
25411                     node.typeArguments = tryParseTypeArguments();
25412                     var res = finishNode(node);
25413                     if (usedBrace) {
25414                         parseExpected(19 /* CloseBraceToken */);
25415                     }
25416                     return res;
25417                 }
25418                 function parsePropertyAccessEntityNameExpression() {
25419                     var node = parseJSDocIdentifierName();
25420                     while (parseOptional(24 /* DotToken */)) {
25421                         var prop = createNode(194 /* PropertyAccessExpression */, node.pos);
25422                         prop.expression = node;
25423                         prop.name = parseJSDocIdentifierName();
25424                         node = finishNode(prop);
25425                     }
25426                     return node;
25427                 }
25428                 function parseSimpleTag(start, kind, tagName) {
25429                     var tag = createNode(kind, start);
25430                     tag.tagName = tagName;
25431                     return finishNode(tag);
25432                 }
25433                 function parseThisTag(start, tagName) {
25434                     var tag = createNode(319 /* JSDocThisTag */, start);
25435                     tag.tagName = tagName;
25436                     tag.typeExpression = parseJSDocTypeExpression(/*mayOmitBraces*/ true);
25437                     skipWhitespace();
25438                     return finishNode(tag);
25439                 }
25440                 function parseEnumTag(start, tagName) {
25441                     var tag = createNode(316 /* JSDocEnumTag */, start);
25442                     tag.tagName = tagName;
25443                     tag.typeExpression = parseJSDocTypeExpression(/*mayOmitBraces*/ true);
25444                     skipWhitespace();
25445                     return finishNode(tag);
25446                 }
25447                 function parseTypedefTag(start, tagName, indent) {
25448                     var typeExpression = tryParseTypeExpression();
25449                     skipWhitespaceOrAsterisk();
25450                     var typedefTag = createNode(322 /* JSDocTypedefTag */, start);
25451                     typedefTag.tagName = tagName;
25452                     typedefTag.fullName = parseJSDocTypeNameWithNamespace();
25453                     typedefTag.name = getJSDocTypeAliasName(typedefTag.fullName);
25454                     skipWhitespace();
25455                     typedefTag.comment = parseTagComments(indent);
25456                     typedefTag.typeExpression = typeExpression;
25457                     var end;
25458                     if (!typeExpression || isObjectOrObjectArrayTypeReference(typeExpression.type)) {
25459                         var child = void 0;
25460                         var jsdocTypeLiteral = void 0;
25461                         var childTypeTag = void 0;
25462                         while (child = tryParse(function () { return parseChildPropertyTag(indent); })) {
25463                             if (!jsdocTypeLiteral) {
25464                                 jsdocTypeLiteral = createNode(304 /* JSDocTypeLiteral */, start);
25465                             }
25466                             if (child.kind === 320 /* JSDocTypeTag */) {
25467                                 if (childTypeTag) {
25468                                     break;
25469                                 }
25470                                 else {
25471                                     childTypeTag = child;
25472                                 }
25473                             }
25474                             else {
25475                                 jsdocTypeLiteral.jsDocPropertyTags = ts.append(jsdocTypeLiteral.jsDocPropertyTags, child);
25476                             }
25477                         }
25478                         if (jsdocTypeLiteral) {
25479                             if (typeExpression && typeExpression.type.kind === 174 /* ArrayType */) {
25480                                 jsdocTypeLiteral.isArrayType = true;
25481                             }
25482                             typedefTag.typeExpression = childTypeTag && childTypeTag.typeExpression && !isObjectOrObjectArrayTypeReference(childTypeTag.typeExpression.type) ?
25483                                 childTypeTag.typeExpression :
25484                                 finishNode(jsdocTypeLiteral);
25485                             end = typedefTag.typeExpression.end;
25486                         }
25487                     }
25488                     // Only include the characters between the name end and the next token if a comment was actually parsed out - otherwise it's just whitespace
25489                     return finishNode(typedefTag, end || typedefTag.comment !== undefined ? scanner.getStartPos() : (typedefTag.fullName || typedefTag.typeExpression || typedefTag.tagName).end);
25490                 }
25491                 function parseJSDocTypeNameWithNamespace(nested) {
25492                     var pos = scanner.getTokenPos();
25493                     if (!ts.tokenIsIdentifierOrKeyword(token())) {
25494                         return undefined;
25495                     }
25496                     var typeNameOrNamespaceName = parseJSDocIdentifierName();
25497                     if (parseOptional(24 /* DotToken */)) {
25498                         var jsDocNamespaceNode = createNode(249 /* ModuleDeclaration */, pos);
25499                         if (nested) {
25500                             jsDocNamespaceNode.flags |= 4 /* NestedNamespace */;
25501                         }
25502                         jsDocNamespaceNode.name = typeNameOrNamespaceName;
25503                         jsDocNamespaceNode.body = parseJSDocTypeNameWithNamespace(/*nested*/ true);
25504                         return finishNode(jsDocNamespaceNode);
25505                     }
25506                     if (nested) {
25507                         typeNameOrNamespaceName.isInJSDocNamespace = true;
25508                     }
25509                     return typeNameOrNamespaceName;
25510                 }
25511                 function parseCallbackTag(start, tagName, indent) {
25512                     var callbackTag = createNode(315 /* JSDocCallbackTag */, start);
25513                     callbackTag.tagName = tagName;
25514                     callbackTag.fullName = parseJSDocTypeNameWithNamespace();
25515                     callbackTag.name = getJSDocTypeAliasName(callbackTag.fullName);
25516                     skipWhitespace();
25517                     callbackTag.comment = parseTagComments(indent);
25518                     var child;
25519                     var jsdocSignature = createNode(305 /* JSDocSignature */, start);
25520                     jsdocSignature.parameters = [];
25521                     while (child = tryParse(function () { return parseChildParameterOrPropertyTag(4 /* CallbackParameter */, indent); })) {
25522                         jsdocSignature.parameters = ts.append(jsdocSignature.parameters, child);
25523                     }
25524                     var returnTag = tryParse(function () {
25525                         if (parseOptionalJsdoc(59 /* AtToken */)) {
25526                             var tag = parseTag(indent);
25527                             if (tag && tag.kind === 318 /* JSDocReturnTag */) {
25528                                 return tag;
25529                             }
25530                         }
25531                     });
25532                     if (returnTag) {
25533                         jsdocSignature.type = returnTag;
25534                     }
25535                     callbackTag.typeExpression = finishNode(jsdocSignature);
25536                     return finishNode(callbackTag);
25537                 }
25538                 function getJSDocTypeAliasName(fullName) {
25539                     if (fullName) {
25540                         var rightNode = fullName;
25541                         while (true) {
25542                             if (ts.isIdentifier(rightNode) || !rightNode.body) {
25543                                 return ts.isIdentifier(rightNode) ? rightNode : rightNode.name;
25544                             }
25545                             rightNode = rightNode.body;
25546                         }
25547                     }
25548                 }
25549                 function escapedTextsEqual(a, b) {
25550                     while (!ts.isIdentifier(a) || !ts.isIdentifier(b)) {
25551                         if (!ts.isIdentifier(a) && !ts.isIdentifier(b) && a.right.escapedText === b.right.escapedText) {
25552                             a = a.left;
25553                             b = b.left;
25554                         }
25555                         else {
25556                             return false;
25557                         }
25558                     }
25559                     return a.escapedText === b.escapedText;
25560                 }
25561                 function parseChildPropertyTag(indent) {
25562                     return parseChildParameterOrPropertyTag(1 /* Property */, indent);
25563                 }
25564                 function parseChildParameterOrPropertyTag(target, indent, name) {
25565                     var canParseTag = true;
25566                     var seenAsterisk = false;
25567                     while (true) {
25568                         switch (nextTokenJSDoc()) {
25569                             case 59 /* AtToken */:
25570                                 if (canParseTag) {
25571                                     var child = tryParseChildTag(target, indent);
25572                                     if (child && (child.kind === 317 /* JSDocParameterTag */ || child.kind === 323 /* JSDocPropertyTag */) &&
25573                                         target !== 4 /* CallbackParameter */ &&
25574                                         name && (ts.isIdentifier(child.name) || !escapedTextsEqual(name, child.name.left))) {
25575                                         return false;
25576                                     }
25577                                     return child;
25578                                 }
25579                                 seenAsterisk = false;
25580                                 break;
25581                             case 4 /* NewLineTrivia */:
25582                                 canParseTag = true;
25583                                 seenAsterisk = false;
25584                                 break;
25585                             case 41 /* AsteriskToken */:
25586                                 if (seenAsterisk) {
25587                                     canParseTag = false;
25588                                 }
25589                                 seenAsterisk = true;
25590                                 break;
25591                             case 75 /* Identifier */:
25592                                 canParseTag = false;
25593                                 break;
25594                             case 1 /* EndOfFileToken */:
25595                                 return false;
25596                         }
25597                     }
25598                 }
25599                 function tryParseChildTag(target, indent) {
25600                     ts.Debug.assert(token() === 59 /* AtToken */);
25601                     var start = scanner.getStartPos();
25602                     nextTokenJSDoc();
25603                     var tagName = parseJSDocIdentifierName();
25604                     skipWhitespace();
25605                     var t;
25606                     switch (tagName.escapedText) {
25607                         case "type":
25608                             return target === 1 /* Property */ && parseTypeTag(start, tagName);
25609                         case "prop":
25610                         case "property":
25611                             t = 1 /* Property */;
25612                             break;
25613                         case "arg":
25614                         case "argument":
25615                         case "param":
25616                             t = 2 /* Parameter */ | 4 /* CallbackParameter */;
25617                             break;
25618                         default:
25619                             return false;
25620                     }
25621                     if (!(target & t)) {
25622                         return false;
25623                     }
25624                     return parseParameterOrPropertyTag(start, tagName, target, indent);
25625                 }
25626                 function parseTemplateTag(start, tagName) {
25627                     // the template tag looks like '@template {Constraint} T,U,V'
25628                     var constraint;
25629                     if (token() === 18 /* OpenBraceToken */) {
25630                         constraint = parseJSDocTypeExpression();
25631                     }
25632                     var typeParameters = [];
25633                     var typeParametersPos = getNodePos();
25634                     do {
25635                         skipWhitespace();
25636                         var typeParameter = createNode(155 /* TypeParameter */);
25637                         typeParameter.name = parseJSDocIdentifierName(ts.Diagnostics.Unexpected_token_A_type_parameter_name_was_expected_without_curly_braces);
25638                         finishNode(typeParameter);
25639                         skipWhitespaceOrAsterisk();
25640                         typeParameters.push(typeParameter);
25641                     } while (parseOptionalJsdoc(27 /* CommaToken */));
25642                     var result = createNode(321 /* JSDocTemplateTag */, start);
25643                     result.tagName = tagName;
25644                     result.constraint = constraint;
25645                     result.typeParameters = createNodeArray(typeParameters, typeParametersPos);
25646                     finishNode(result);
25647                     return result;
25648                 }
25649                 function parseOptionalJsdoc(t) {
25650                     if (token() === t) {
25651                         nextTokenJSDoc();
25652                         return true;
25653                     }
25654                     return false;
25655                 }
25656                 function parseJSDocEntityName() {
25657                     var entity = parseJSDocIdentifierName();
25658                     if (parseOptional(22 /* OpenBracketToken */)) {
25659                         parseExpected(23 /* CloseBracketToken */);
25660                         // Note that y[] is accepted as an entity name, but the postfix brackets are not saved for checking.
25661                         // Technically usejsdoc.org requires them for specifying a property of a type equivalent to Array<{ x: ...}>
25662                         // but it's not worth it to enforce that restriction.
25663                     }
25664                     while (parseOptional(24 /* DotToken */)) {
25665                         var name = parseJSDocIdentifierName();
25666                         if (parseOptional(22 /* OpenBracketToken */)) {
25667                             parseExpected(23 /* CloseBracketToken */);
25668                         }
25669                         entity = createQualifiedName(entity, name);
25670                     }
25671                     return entity;
25672                 }
25673                 function parseJSDocIdentifierName(message) {
25674                     if (!ts.tokenIsIdentifierOrKeyword(token())) {
25675                         return createMissingNode(75 /* Identifier */, /*reportAtCurrentPosition*/ !message, message || ts.Diagnostics.Identifier_expected);
25676                     }
25677                     identifierCount++;
25678                     var pos = scanner.getTokenPos();
25679                     var end = scanner.getTextPos();
25680                     var result = createNode(75 /* Identifier */, pos);
25681                     if (token() !== 75 /* Identifier */) {
25682                         result.originalKeywordKind = token();
25683                     }
25684                     result.escapedText = ts.escapeLeadingUnderscores(internIdentifier(scanner.getTokenValue()));
25685                     finishNode(result, end);
25686                     nextTokenJSDoc();
25687                     return result;
25688                 }
25689             }
25690         })(JSDocParser = Parser.JSDocParser || (Parser.JSDocParser = {}));
25691     })(Parser || (Parser = {}));
25692     var IncrementalParser;
25693     (function (IncrementalParser) {
25694         function updateSourceFile(sourceFile, newText, textChangeRange, aggressiveChecks) {
25695             aggressiveChecks = aggressiveChecks || ts.Debug.shouldAssert(2 /* Aggressive */);
25696             checkChangeRange(sourceFile, newText, textChangeRange, aggressiveChecks);
25697             if (ts.textChangeRangeIsUnchanged(textChangeRange)) {
25698                 // if the text didn't change, then we can just return our current source file as-is.
25699                 return sourceFile;
25700             }
25701             if (sourceFile.statements.length === 0) {
25702                 // If we don't have any statements in the current source file, then there's no real
25703                 // way to incrementally parse.  So just do a full parse instead.
25704                 return Parser.parseSourceFile(sourceFile.fileName, newText, sourceFile.languageVersion, /*syntaxCursor*/ undefined, /*setParentNodes*/ true, sourceFile.scriptKind);
25705             }
25706             // Make sure we're not trying to incrementally update a source file more than once.  Once
25707             // we do an update the original source file is considered unusable from that point onwards.
25708             //
25709             // This is because we do incremental parsing in-place.  i.e. we take nodes from the old
25710             // tree and give them new positions and parents.  From that point on, trusting the old
25711             // tree at all is not possible as far too much of it may violate invariants.
25712             var incrementalSourceFile = sourceFile;
25713             ts.Debug.assert(!incrementalSourceFile.hasBeenIncrementallyParsed);
25714             incrementalSourceFile.hasBeenIncrementallyParsed = true;
25715             var oldText = sourceFile.text;
25716             var syntaxCursor = createSyntaxCursor(sourceFile);
25717             // Make the actual change larger so that we know to reparse anything whose lookahead
25718             // might have intersected the change.
25719             var changeRange = extendToAffectedRange(sourceFile, textChangeRange);
25720             checkChangeRange(sourceFile, newText, changeRange, aggressiveChecks);
25721             // Ensure that extending the affected range only moved the start of the change range
25722             // earlier in the file.
25723             ts.Debug.assert(changeRange.span.start <= textChangeRange.span.start);
25724             ts.Debug.assert(ts.textSpanEnd(changeRange.span) === ts.textSpanEnd(textChangeRange.span));
25725             ts.Debug.assert(ts.textSpanEnd(ts.textChangeRangeNewSpan(changeRange)) === ts.textSpanEnd(ts.textChangeRangeNewSpan(textChangeRange)));
25726             // The is the amount the nodes after the edit range need to be adjusted.  It can be
25727             // positive (if the edit added characters), negative (if the edit deleted characters)
25728             // or zero (if this was a pure overwrite with nothing added/removed).
25729             var delta = ts.textChangeRangeNewSpan(changeRange).length - changeRange.span.length;
25730             // If we added or removed characters during the edit, then we need to go and adjust all
25731             // the nodes after the edit.  Those nodes may move forward (if we inserted chars) or they
25732             // may move backward (if we deleted chars).
25733             //
25734             // Doing this helps us out in two ways.  First, it means that any nodes/tokens we want
25735             // to reuse are already at the appropriate position in the new text.  That way when we
25736             // reuse them, we don't have to figure out if they need to be adjusted.  Second, it makes
25737             // it very easy to determine if we can reuse a node.  If the node's position is at where
25738             // we are in the text, then we can reuse it.  Otherwise we can't.  If the node's position
25739             // is ahead of us, then we'll need to rescan tokens.  If the node's position is behind
25740             // us, then we'll need to skip it or crumble it as appropriate
25741             //
25742             // We will also adjust the positions of nodes that intersect the change range as well.
25743             // By doing this, we ensure that all the positions in the old tree are consistent, not
25744             // just the positions of nodes entirely before/after the change range.  By being
25745             // consistent, we can then easily map from positions to nodes in the old tree easily.
25746             //
25747             // Also, mark any syntax elements that intersect the changed span.  We know, up front,
25748             // that we cannot reuse these elements.
25749             updateTokenPositionsAndMarkElements(incrementalSourceFile, changeRange.span.start, ts.textSpanEnd(changeRange.span), ts.textSpanEnd(ts.textChangeRangeNewSpan(changeRange)), delta, oldText, newText, aggressiveChecks);
25750             // Now that we've set up our internal incremental state just proceed and parse the
25751             // source file in the normal fashion.  When possible the parser will retrieve and
25752             // reuse nodes from the old tree.
25753             //
25754             // Note: passing in 'true' for setNodeParents is very important.  When incrementally
25755             // parsing, we will be reusing nodes from the old tree, and placing it into new
25756             // parents.  If we don't set the parents now, we'll end up with an observably
25757             // inconsistent tree.  Setting the parents on the new tree should be very fast.  We
25758             // will immediately bail out of walking any subtrees when we can see that their parents
25759             // are already correct.
25760             var result = Parser.parseSourceFile(sourceFile.fileName, newText, sourceFile.languageVersion, syntaxCursor, /*setParentNodes*/ true, sourceFile.scriptKind);
25761             result.commentDirectives = getNewCommentDirectives(sourceFile.commentDirectives, result.commentDirectives, changeRange.span.start, ts.textSpanEnd(changeRange.span), delta, oldText, newText, aggressiveChecks);
25762             return result;
25763         }
25764         IncrementalParser.updateSourceFile = updateSourceFile;
25765         function getNewCommentDirectives(oldDirectives, newDirectives, changeStart, changeRangeOldEnd, delta, oldText, newText, aggressiveChecks) {
25766             if (!oldDirectives)
25767                 return newDirectives;
25768             var commentDirectives;
25769             var addedNewlyScannedDirectives = false;
25770             for (var _i = 0, oldDirectives_1 = oldDirectives; _i < oldDirectives_1.length; _i++) {
25771                 var directive = oldDirectives_1[_i];
25772                 var range = directive.range, type = directive.type;
25773                 // Range before the change
25774                 if (range.end < changeStart) {
25775                     commentDirectives = ts.append(commentDirectives, directive);
25776                 }
25777                 else if (range.pos > changeRangeOldEnd) {
25778                     addNewlyScannedDirectives();
25779                     // Node is entirely past the change range.  We need to move both its pos and
25780                     // end, forward or backward appropriately.
25781                     var updatedDirective = {
25782                         range: { pos: range.pos + delta, end: range.end + delta },
25783                         type: type
25784                     };
25785                     commentDirectives = ts.append(commentDirectives, updatedDirective);
25786                     if (aggressiveChecks) {
25787                         ts.Debug.assert(oldText.substring(range.pos, range.end) === newText.substring(updatedDirective.range.pos, updatedDirective.range.end));
25788                     }
25789                 }
25790                 // Ignore ranges that fall in change range
25791             }
25792             addNewlyScannedDirectives();
25793             return commentDirectives;
25794             function addNewlyScannedDirectives() {
25795                 if (addedNewlyScannedDirectives)
25796                     return;
25797                 addedNewlyScannedDirectives = true;
25798                 if (!commentDirectives) {
25799                     commentDirectives = newDirectives;
25800                 }
25801                 else if (newDirectives) {
25802                     commentDirectives.push.apply(commentDirectives, newDirectives);
25803                 }
25804             }
25805         }
25806         function moveElementEntirelyPastChangeRange(element, isArray, delta, oldText, newText, aggressiveChecks) {
25807             if (isArray) {
25808                 visitArray(element);
25809             }
25810             else {
25811                 visitNode(element);
25812             }
25813             return;
25814             function visitNode(node) {
25815                 var text = "";
25816                 if (aggressiveChecks && shouldCheckNode(node)) {
25817                     text = oldText.substring(node.pos, node.end);
25818                 }
25819                 // Ditch any existing LS children we may have created.  This way we can avoid
25820                 // moving them forward.
25821                 if (node._children) {
25822                     node._children = undefined;
25823                 }
25824                 node.pos += delta;
25825                 node.end += delta;
25826                 if (aggressiveChecks && shouldCheckNode(node)) {
25827                     ts.Debug.assert(text === newText.substring(node.pos, node.end));
25828                 }
25829                 forEachChild(node, visitNode, visitArray);
25830                 if (ts.hasJSDocNodes(node)) {
25831                     for (var _i = 0, _a = node.jsDoc; _i < _a.length; _i++) {
25832                         var jsDocComment = _a[_i];
25833                         visitNode(jsDocComment);
25834                     }
25835                 }
25836                 checkNodePositions(node, aggressiveChecks);
25837             }
25838             function visitArray(array) {
25839                 array._children = undefined;
25840                 array.pos += delta;
25841                 array.end += delta;
25842                 for (var _i = 0, array_8 = array; _i < array_8.length; _i++) {
25843                     var node = array_8[_i];
25844                     visitNode(node);
25845                 }
25846             }
25847         }
25848         function shouldCheckNode(node) {
25849             switch (node.kind) {
25850                 case 10 /* StringLiteral */:
25851                 case 8 /* NumericLiteral */:
25852                 case 75 /* Identifier */:
25853                     return true;
25854             }
25855             return false;
25856         }
25857         function adjustIntersectingElement(element, changeStart, changeRangeOldEnd, changeRangeNewEnd, delta) {
25858             ts.Debug.assert(element.end >= changeStart, "Adjusting an element that was entirely before the change range");
25859             ts.Debug.assert(element.pos <= changeRangeOldEnd, "Adjusting an element that was entirely after the change range");
25860             ts.Debug.assert(element.pos <= element.end);
25861             // We have an element that intersects the change range in some way.  It may have its
25862             // start, or its end (or both) in the changed range.  We want to adjust any part
25863             // that intersects such that the final tree is in a consistent state.  i.e. all
25864             // children have spans within the span of their parent, and all siblings are ordered
25865             // properly.
25866             // We may need to update both the 'pos' and the 'end' of the element.
25867             // If the 'pos' is before the start of the change, then we don't need to touch it.
25868             // If it isn't, then the 'pos' must be inside the change.  How we update it will
25869             // depend if delta is positive or negative. If delta is positive then we have
25870             // something like:
25871             //
25872             //  -------------------AAA-----------------
25873             //  -------------------BBBCCCCCCC-----------------
25874             //
25875             // In this case, we consider any node that started in the change range to still be
25876             // starting at the same position.
25877             //
25878             // however, if the delta is negative, then we instead have something like this:
25879             //
25880             //  -------------------XXXYYYYYYY-----------------
25881             //  -------------------ZZZ-----------------
25882             //
25883             // In this case, any element that started in the 'X' range will keep its position.
25884             // However any element that started after that will have their pos adjusted to be
25885             // at the end of the new range.  i.e. any node that started in the 'Y' range will
25886             // be adjusted to have their start at the end of the 'Z' range.
25887             //
25888             // The element will keep its position if possible.  Or Move backward to the new-end
25889             // if it's in the 'Y' range.
25890             element.pos = Math.min(element.pos, changeRangeNewEnd);
25891             // If the 'end' is after the change range, then we always adjust it by the delta
25892             // amount.  However, if the end is in the change range, then how we adjust it
25893             // will depend on if delta is positive or negative.  If delta is positive then we
25894             // have something like:
25895             //
25896             //  -------------------AAA-----------------
25897             //  -------------------BBBCCCCCCC-----------------
25898             //
25899             // In this case, we consider any node that ended inside the change range to keep its
25900             // end position.
25901             //
25902             // however, if the delta is negative, then we instead have something like this:
25903             //
25904             //  -------------------XXXYYYYYYY-----------------
25905             //  -------------------ZZZ-----------------
25906             //
25907             // In this case, any element that ended in the 'X' range will keep its position.
25908             // However any element that ended after that will have their pos adjusted to be
25909             // at the end of the new range.  i.e. any node that ended in the 'Y' range will
25910             // be adjusted to have their end at the end of the 'Z' range.
25911             if (element.end >= changeRangeOldEnd) {
25912                 // Element ends after the change range.  Always adjust the end pos.
25913                 element.end += delta;
25914             }
25915             else {
25916                 // Element ends in the change range.  The element will keep its position if
25917                 // possible. Or Move backward to the new-end if it's in the 'Y' range.
25918                 element.end = Math.min(element.end, changeRangeNewEnd);
25919             }
25920             ts.Debug.assert(element.pos <= element.end);
25921             if (element.parent) {
25922                 ts.Debug.assert(element.pos >= element.parent.pos);
25923                 ts.Debug.assert(element.end <= element.parent.end);
25924             }
25925         }
25926         function checkNodePositions(node, aggressiveChecks) {
25927             if (aggressiveChecks) {
25928                 var pos_2 = node.pos;
25929                 var visitNode_1 = function (child) {
25930                     ts.Debug.assert(child.pos >= pos_2);
25931                     pos_2 = child.end;
25932                 };
25933                 if (ts.hasJSDocNodes(node)) {
25934                     for (var _i = 0, _a = node.jsDoc; _i < _a.length; _i++) {
25935                         var jsDocComment = _a[_i];
25936                         visitNode_1(jsDocComment);
25937                     }
25938                 }
25939                 forEachChild(node, visitNode_1);
25940                 ts.Debug.assert(pos_2 <= node.end);
25941             }
25942         }
25943         function updateTokenPositionsAndMarkElements(sourceFile, changeStart, changeRangeOldEnd, changeRangeNewEnd, delta, oldText, newText, aggressiveChecks) {
25944             visitNode(sourceFile);
25945             return;
25946             function visitNode(child) {
25947                 ts.Debug.assert(child.pos <= child.end);
25948                 if (child.pos > changeRangeOldEnd) {
25949                     // Node is entirely past the change range.  We need to move both its pos and
25950                     // end, forward or backward appropriately.
25951                     moveElementEntirelyPastChangeRange(child, /*isArray*/ false, delta, oldText, newText, aggressiveChecks);
25952                     return;
25953                 }
25954                 // Check if the element intersects the change range.  If it does, then it is not
25955                 // reusable.  Also, we'll need to recurse to see what constituent portions we may
25956                 // be able to use.
25957                 var fullEnd = child.end;
25958                 if (fullEnd >= changeStart) {
25959                     child.intersectsChange = true;
25960                     child._children = undefined;
25961                     // Adjust the pos or end (or both) of the intersecting element accordingly.
25962                     adjustIntersectingElement(child, changeStart, changeRangeOldEnd, changeRangeNewEnd, delta);
25963                     forEachChild(child, visitNode, visitArray);
25964                     if (ts.hasJSDocNodes(child)) {
25965                         for (var _i = 0, _a = child.jsDoc; _i < _a.length; _i++) {
25966                             var jsDocComment = _a[_i];
25967                             visitNode(jsDocComment);
25968                         }
25969                     }
25970                     checkNodePositions(child, aggressiveChecks);
25971                     return;
25972                 }
25973                 // Otherwise, the node is entirely before the change range.  No need to do anything with it.
25974                 ts.Debug.assert(fullEnd < changeStart);
25975             }
25976             function visitArray(array) {
25977                 ts.Debug.assert(array.pos <= array.end);
25978                 if (array.pos > changeRangeOldEnd) {
25979                     // Array is entirely after the change range.  We need to move it, and move any of
25980                     // its children.
25981                     moveElementEntirelyPastChangeRange(array, /*isArray*/ true, delta, oldText, newText, aggressiveChecks);
25982                     return;
25983                 }
25984                 // Check if the element intersects the change range.  If it does, then it is not
25985                 // reusable.  Also, we'll need to recurse to see what constituent portions we may
25986                 // be able to use.
25987                 var fullEnd = array.end;
25988                 if (fullEnd >= changeStart) {
25989                     array.intersectsChange = true;
25990                     array._children = undefined;
25991                     // Adjust the pos or end (or both) of the intersecting array accordingly.
25992                     adjustIntersectingElement(array, changeStart, changeRangeOldEnd, changeRangeNewEnd, delta);
25993                     for (var _i = 0, array_9 = array; _i < array_9.length; _i++) {
25994                         var node = array_9[_i];
25995                         visitNode(node);
25996                     }
25997                     return;
25998                 }
25999                 // Otherwise, the array is entirely before the change range.  No need to do anything with it.
26000                 ts.Debug.assert(fullEnd < changeStart);
26001             }
26002         }
26003         function extendToAffectedRange(sourceFile, changeRange) {
26004             // Consider the following code:
26005             //      void foo() { /; }
26006             //
26007             // If the text changes with an insertion of / just before the semicolon then we end up with:
26008             //      void foo() { //; }
26009             //
26010             // If we were to just use the changeRange a is, then we would not rescan the { token
26011             // (as it does not intersect the actual original change range).  Because an edit may
26012             // change the token touching it, we actually need to look back *at least* one token so
26013             // that the prior token sees that change.
26014             var maxLookahead = 1;
26015             var start = changeRange.span.start;
26016             // the first iteration aligns us with the change start. subsequent iteration move us to
26017             // the left by maxLookahead tokens.  We only need to do this as long as we're not at the
26018             // start of the tree.
26019             for (var i = 0; start > 0 && i <= maxLookahead; i++) {
26020                 var nearestNode = findNearestNodeStartingBeforeOrAtPosition(sourceFile, start);
26021                 ts.Debug.assert(nearestNode.pos <= start);
26022                 var position = nearestNode.pos;
26023                 start = Math.max(0, position - 1);
26024             }
26025             var finalSpan = ts.createTextSpanFromBounds(start, ts.textSpanEnd(changeRange.span));
26026             var finalLength = changeRange.newLength + (changeRange.span.start - start);
26027             return ts.createTextChangeRange(finalSpan, finalLength);
26028         }
26029         function findNearestNodeStartingBeforeOrAtPosition(sourceFile, position) {
26030             var bestResult = sourceFile;
26031             var lastNodeEntirelyBeforePosition;
26032             forEachChild(sourceFile, visit);
26033             if (lastNodeEntirelyBeforePosition) {
26034                 var lastChildOfLastEntireNodeBeforePosition = getLastDescendant(lastNodeEntirelyBeforePosition);
26035                 if (lastChildOfLastEntireNodeBeforePosition.pos > bestResult.pos) {
26036                     bestResult = lastChildOfLastEntireNodeBeforePosition;
26037                 }
26038             }
26039             return bestResult;
26040             function getLastDescendant(node) {
26041                 while (true) {
26042                     var lastChild = ts.getLastChild(node);
26043                     if (lastChild) {
26044                         node = lastChild;
26045                     }
26046                     else {
26047                         return node;
26048                     }
26049                 }
26050             }
26051             function visit(child) {
26052                 if (ts.nodeIsMissing(child)) {
26053                     // Missing nodes are effectively invisible to us.  We never even consider them
26054                     // When trying to find the nearest node before us.
26055                     return;
26056                 }
26057                 // If the child intersects this position, then this node is currently the nearest
26058                 // node that starts before the position.
26059                 if (child.pos <= position) {
26060                     if (child.pos >= bestResult.pos) {
26061                         // This node starts before the position, and is closer to the position than
26062                         // the previous best node we found.  It is now the new best node.
26063                         bestResult = child;
26064                     }
26065                     // Now, the node may overlap the position, or it may end entirely before the
26066                     // position.  If it overlaps with the position, then either it, or one of its
26067                     // children must be the nearest node before the position.  So we can just
26068                     // recurse into this child to see if we can find something better.
26069                     if (position < child.end) {
26070                         // The nearest node is either this child, or one of the children inside
26071                         // of it.  We've already marked this child as the best so far.  Recurse
26072                         // in case one of the children is better.
26073                         forEachChild(child, visit);
26074                         // Once we look at the children of this node, then there's no need to
26075                         // continue any further.
26076                         return true;
26077                     }
26078                     else {
26079                         ts.Debug.assert(child.end <= position);
26080                         // The child ends entirely before this position.  Say you have the following
26081                         // (where $ is the position)
26082                         //
26083                         //      <complex expr 1> ? <complex expr 2> $ : <...> <...>
26084                         //
26085                         // We would want to find the nearest preceding node in "complex expr 2".
26086                         // To support that, we keep track of this node, and once we're done searching
26087                         // for a best node, we recurse down this node to see if we can find a good
26088                         // result in it.
26089                         //
26090                         // This approach allows us to quickly skip over nodes that are entirely
26091                         // before the position, while still allowing us to find any nodes in the
26092                         // last one that might be what we want.
26093                         lastNodeEntirelyBeforePosition = child;
26094                     }
26095                 }
26096                 else {
26097                     ts.Debug.assert(child.pos > position);
26098                     // We're now at a node that is entirely past the position we're searching for.
26099                     // This node (and all following nodes) could never contribute to the result,
26100                     // so just skip them by returning 'true' here.
26101                     return true;
26102                 }
26103             }
26104         }
26105         function checkChangeRange(sourceFile, newText, textChangeRange, aggressiveChecks) {
26106             var oldText = sourceFile.text;
26107             if (textChangeRange) {
26108                 ts.Debug.assert((oldText.length - textChangeRange.span.length + textChangeRange.newLength) === newText.length);
26109                 if (aggressiveChecks || ts.Debug.shouldAssert(3 /* VeryAggressive */)) {
26110                     var oldTextPrefix = oldText.substr(0, textChangeRange.span.start);
26111                     var newTextPrefix = newText.substr(0, textChangeRange.span.start);
26112                     ts.Debug.assert(oldTextPrefix === newTextPrefix);
26113                     var oldTextSuffix = oldText.substring(ts.textSpanEnd(textChangeRange.span), oldText.length);
26114                     var newTextSuffix = newText.substring(ts.textSpanEnd(ts.textChangeRangeNewSpan(textChangeRange)), newText.length);
26115                     ts.Debug.assert(oldTextSuffix === newTextSuffix);
26116                 }
26117             }
26118         }
26119         function createSyntaxCursor(sourceFile) {
26120             var currentArray = sourceFile.statements;
26121             var currentArrayIndex = 0;
26122             ts.Debug.assert(currentArrayIndex < currentArray.length);
26123             var current = currentArray[currentArrayIndex];
26124             var lastQueriedPosition = -1 /* Value */;
26125             return {
26126                 currentNode: function (position) {
26127                     // Only compute the current node if the position is different than the last time
26128                     // we were asked.  The parser commonly asks for the node at the same position
26129                     // twice.  Once to know if can read an appropriate list element at a certain point,
26130                     // and then to actually read and consume the node.
26131                     if (position !== lastQueriedPosition) {
26132                         // Much of the time the parser will need the very next node in the array that
26133                         // we just returned a node from.So just simply check for that case and move
26134                         // forward in the array instead of searching for the node again.
26135                         if (current && current.end === position && currentArrayIndex < (currentArray.length - 1)) {
26136                             currentArrayIndex++;
26137                             current = currentArray[currentArrayIndex];
26138                         }
26139                         // If we don't have a node, or the node we have isn't in the right position,
26140                         // then try to find a viable node at the position requested.
26141                         if (!current || current.pos !== position) {
26142                             findHighestListElementThatStartsAtPosition(position);
26143                         }
26144                     }
26145                     // Cache this query so that we don't do any extra work if the parser calls back
26146                     // into us.  Note: this is very common as the parser will make pairs of calls like
26147                     // 'isListElement -> parseListElement'.  If we were unable to find a node when
26148                     // called with 'isListElement', we don't want to redo the work when parseListElement
26149                     // is called immediately after.
26150                     lastQueriedPosition = position;
26151                     // Either we don'd have a node, or we have a node at the position being asked for.
26152                     ts.Debug.assert(!current || current.pos === position);
26153                     return current;
26154                 }
26155             };
26156             // Finds the highest element in the tree we can find that starts at the provided position.
26157             // The element must be a direct child of some node list in the tree.  This way after we
26158             // return it, we can easily return its next sibling in the list.
26159             function findHighestListElementThatStartsAtPosition(position) {
26160                 // Clear out any cached state about the last node we found.
26161                 currentArray = undefined;
26162                 currentArrayIndex = -1 /* Value */;
26163                 current = undefined;
26164                 // Recurse into the source file to find the highest node at this position.
26165                 forEachChild(sourceFile, visitNode, visitArray);
26166                 return;
26167                 function visitNode(node) {
26168                     if (position >= node.pos && position < node.end) {
26169                         // Position was within this node.  Keep searching deeper to find the node.
26170                         forEachChild(node, visitNode, visitArray);
26171                         // don't proceed any further in the search.
26172                         return true;
26173                     }
26174                     // position wasn't in this node, have to keep searching.
26175                     return false;
26176                 }
26177                 function visitArray(array) {
26178                     if (position >= array.pos && position < array.end) {
26179                         // position was in this array.  Search through this array to see if we find a
26180                         // viable element.
26181                         for (var i = 0; i < array.length; i++) {
26182                             var child = array[i];
26183                             if (child) {
26184                                 if (child.pos === position) {
26185                                     // Found the right node.  We're done.
26186                                     currentArray = array;
26187                                     currentArrayIndex = i;
26188                                     current = child;
26189                                     return true;
26190                                 }
26191                                 else {
26192                                     if (child.pos < position && position < child.end) {
26193                                         // Position in somewhere within this child.  Search in it and
26194                                         // stop searching in this array.
26195                                         forEachChild(child, visitNode, visitArray);
26196                                         return true;
26197                                     }
26198                                 }
26199                             }
26200                         }
26201                     }
26202                     // position wasn't in this array, have to keep searching.
26203                     return false;
26204                 }
26205             }
26206         }
26207         var InvalidPosition;
26208         (function (InvalidPosition) {
26209             InvalidPosition[InvalidPosition["Value"] = -1] = "Value";
26210         })(InvalidPosition || (InvalidPosition = {}));
26211     })(IncrementalParser || (IncrementalParser = {}));
26212     /** @internal */
26213     function isDeclarationFileName(fileName) {
26214         return ts.fileExtensionIs(fileName, ".d.ts" /* Dts */);
26215     }
26216     ts.isDeclarationFileName = isDeclarationFileName;
26217     /*@internal*/
26218     function processCommentPragmas(context, sourceText) {
26219         var pragmas = [];
26220         for (var _i = 0, _a = ts.getLeadingCommentRanges(sourceText, 0) || ts.emptyArray; _i < _a.length; _i++) {
26221             var range = _a[_i];
26222             var comment = sourceText.substring(range.pos, range.end);
26223             extractPragmas(pragmas, range, comment);
26224         }
26225         context.pragmas = ts.createMap();
26226         for (var _b = 0, pragmas_1 = pragmas; _b < pragmas_1.length; _b++) {
26227             var pragma = pragmas_1[_b];
26228             if (context.pragmas.has(pragma.name)) {
26229                 var currentValue = context.pragmas.get(pragma.name);
26230                 if (currentValue instanceof Array) {
26231                     currentValue.push(pragma.args);
26232                 }
26233                 else {
26234                     context.pragmas.set(pragma.name, [currentValue, pragma.args]);
26235                 }
26236                 continue;
26237             }
26238             context.pragmas.set(pragma.name, pragma.args);
26239         }
26240     }
26241     ts.processCommentPragmas = processCommentPragmas;
26242     /*@internal*/
26243     function processPragmasIntoFields(context, reportDiagnostic) {
26244         context.checkJsDirective = undefined;
26245         context.referencedFiles = [];
26246         context.typeReferenceDirectives = [];
26247         context.libReferenceDirectives = [];
26248         context.amdDependencies = [];
26249         context.hasNoDefaultLib = false;
26250         context.pragmas.forEach(function (entryOrList, key) {
26251             // TODO: The below should be strongly type-guarded and not need casts/explicit annotations, since entryOrList is related to
26252             // key and key is constrained to a union; but it's not (see GH#21483 for at least partial fix) :(
26253             switch (key) {
26254                 case "reference": {
26255                     var referencedFiles_1 = context.referencedFiles;
26256                     var typeReferenceDirectives_1 = context.typeReferenceDirectives;
26257                     var libReferenceDirectives_1 = context.libReferenceDirectives;
26258                     ts.forEach(ts.toArray(entryOrList), function (arg) {
26259                         var _a = arg.arguments, types = _a.types, lib = _a.lib, path = _a.path;
26260                         if (arg.arguments["no-default-lib"]) {
26261                             context.hasNoDefaultLib = true;
26262                         }
26263                         else if (types) {
26264                             typeReferenceDirectives_1.push({ pos: types.pos, end: types.end, fileName: types.value });
26265                         }
26266                         else if (lib) {
26267                             libReferenceDirectives_1.push({ pos: lib.pos, end: lib.end, fileName: lib.value });
26268                         }
26269                         else if (path) {
26270                             referencedFiles_1.push({ pos: path.pos, end: path.end, fileName: path.value });
26271                         }
26272                         else {
26273                             reportDiagnostic(arg.range.pos, arg.range.end - arg.range.pos, ts.Diagnostics.Invalid_reference_directive_syntax);
26274                         }
26275                     });
26276                     break;
26277                 }
26278                 case "amd-dependency": {
26279                     context.amdDependencies = ts.map(ts.toArray(entryOrList), function (x) { return ({ name: x.arguments.name, path: x.arguments.path }); });
26280                     break;
26281                 }
26282                 case "amd-module": {
26283                     if (entryOrList instanceof Array) {
26284                         for (var _i = 0, entryOrList_1 = entryOrList; _i < entryOrList_1.length; _i++) {
26285                             var entry = entryOrList_1[_i];
26286                             if (context.moduleName) {
26287                                 // TODO: It's probably fine to issue this diagnostic on all instances of the pragma
26288                                 reportDiagnostic(entry.range.pos, entry.range.end - entry.range.pos, ts.Diagnostics.An_AMD_module_cannot_have_multiple_name_assignments);
26289                             }
26290                             context.moduleName = entry.arguments.name;
26291                         }
26292                     }
26293                     else {
26294                         context.moduleName = entryOrList.arguments.name;
26295                     }
26296                     break;
26297                 }
26298                 case "ts-nocheck":
26299                 case "ts-check": {
26300                     // _last_ of either nocheck or check in a file is the "winner"
26301                     ts.forEach(ts.toArray(entryOrList), function (entry) {
26302                         if (!context.checkJsDirective || entry.range.pos > context.checkJsDirective.pos) {
26303                             context.checkJsDirective = {
26304                                 enabled: key === "ts-check",
26305                                 end: entry.range.end,
26306                                 pos: entry.range.pos
26307                             };
26308                         }
26309                     });
26310                     break;
26311                 }
26312                 case "jsx": return; // Accessed directly
26313                 default: ts.Debug.fail("Unhandled pragma kind"); // Can this be made into an assertNever in the future?
26314             }
26315         });
26316     }
26317     ts.processPragmasIntoFields = processPragmasIntoFields;
26318     var namedArgRegExCache = ts.createMap();
26319     function getNamedArgRegEx(name) {
26320         if (namedArgRegExCache.has(name)) {
26321             return namedArgRegExCache.get(name);
26322         }
26323         var result = new RegExp("(\\s" + name + "\\s*=\\s*)('|\")(.+?)\\2", "im");
26324         namedArgRegExCache.set(name, result);
26325         return result;
26326     }
26327     var tripleSlashXMLCommentStartRegEx = /^\/\/\/\s*<(\S+)\s.*?\/>/im;
26328     var singleLinePragmaRegEx = /^\/\/\/?\s*@(\S+)\s*(.*)\s*$/im;
26329     function extractPragmas(pragmas, range, text) {
26330         var tripleSlash = range.kind === 2 /* SingleLineCommentTrivia */ && tripleSlashXMLCommentStartRegEx.exec(text);
26331         if (tripleSlash) {
26332             var name = tripleSlash[1].toLowerCase(); // Technically unsafe cast, but we do it so the below check to make it safe typechecks
26333             var pragma = ts.commentPragmas[name];
26334             if (!pragma || !(pragma.kind & 1 /* TripleSlashXML */)) {
26335                 return;
26336             }
26337             if (pragma.args) {
26338                 var argument = {};
26339                 for (var _i = 0, _a = pragma.args; _i < _a.length; _i++) {
26340                     var arg = _a[_i];
26341                     var matcher = getNamedArgRegEx(arg.name);
26342                     var matchResult = matcher.exec(text);
26343                     if (!matchResult && !arg.optional) {
26344                         return; // Missing required argument, don't parse
26345                     }
26346                     else if (matchResult) {
26347                         if (arg.captureSpan) {
26348                             var startPos = range.pos + matchResult.index + matchResult[1].length + matchResult[2].length;
26349                             argument[arg.name] = {
26350                                 value: matchResult[3],
26351                                 pos: startPos,
26352                                 end: startPos + matchResult[3].length
26353                             };
26354                         }
26355                         else {
26356                             argument[arg.name] = matchResult[3];
26357                         }
26358                     }
26359                 }
26360                 pragmas.push({ name: name, args: { arguments: argument, range: range } });
26361             }
26362             else {
26363                 pragmas.push({ name: name, args: { arguments: {}, range: range } });
26364             }
26365             return;
26366         }
26367         var singleLine = range.kind === 2 /* SingleLineCommentTrivia */ && singleLinePragmaRegEx.exec(text);
26368         if (singleLine) {
26369             return addPragmaForMatch(pragmas, range, 2 /* SingleLine */, singleLine);
26370         }
26371         if (range.kind === 3 /* MultiLineCommentTrivia */) {
26372             var multiLinePragmaRegEx = /\s*@(\S+)\s*(.*)\s*$/gim; // Defined inline since it uses the "g" flag, which keeps a persistent index (for iterating)
26373             var multiLineMatch = void 0;
26374             while (multiLineMatch = multiLinePragmaRegEx.exec(text)) {
26375                 addPragmaForMatch(pragmas, range, 4 /* MultiLine */, multiLineMatch);
26376             }
26377         }
26378     }
26379     function addPragmaForMatch(pragmas, range, kind, match) {
26380         if (!match)
26381             return;
26382         var name = match[1].toLowerCase(); // Technically unsafe cast, but we do it so they below check to make it safe typechecks
26383         var pragma = ts.commentPragmas[name];
26384         if (!pragma || !(pragma.kind & kind)) {
26385             return;
26386         }
26387         var args = match[2]; // Split on spaces and match up positionally with definition
26388         var argument = getNamedPragmaArguments(pragma, args);
26389         if (argument === "fail")
26390             return; // Missing required argument, fail to parse it
26391         pragmas.push({ name: name, args: { arguments: argument, range: range } });
26392         return;
26393     }
26394     function getNamedPragmaArguments(pragma, text) {
26395         if (!text)
26396             return {};
26397         if (!pragma.args)
26398             return {};
26399         var args = text.split(/\s+/);
26400         var argMap = {};
26401         for (var i = 0; i < pragma.args.length; i++) {
26402             var argument = pragma.args[i];
26403             if (!args[i] && !argument.optional) {
26404                 return "fail";
26405             }
26406             if (argument.captureSpan) {
26407                 return ts.Debug.fail("Capture spans not yet implemented for non-xml pragmas");
26408             }
26409             argMap[argument.name] = args[i];
26410         }
26411         return argMap;
26412     }
26413     /** @internal */
26414     function tagNamesAreEquivalent(lhs, rhs) {
26415         if (lhs.kind !== rhs.kind) {
26416             return false;
26417         }
26418         if (lhs.kind === 75 /* Identifier */) {
26419             return lhs.escapedText === rhs.escapedText;
26420         }
26421         if (lhs.kind === 104 /* ThisKeyword */) {
26422             return true;
26423         }
26424         // If we are at this statement then we must have PropertyAccessExpression and because tag name in Jsx element can only
26425         // take forms of JsxTagNameExpression which includes an identifier, "this" expression, or another propertyAccessExpression
26426         // it is safe to case the expression property as such. See parseJsxElementName for how we parse tag name in Jsx element
26427         return lhs.name.escapedText === rhs.name.escapedText &&
26428             tagNamesAreEquivalent(lhs.expression, rhs.expression);
26429     }
26430     ts.tagNamesAreEquivalent = tagNamesAreEquivalent;
26431 })(ts || (ts = {}));
26432 var ts;
26433 (function (ts) {
26434     /* @internal */
26435     ts.compileOnSaveCommandLineOption = { name: "compileOnSave", type: "boolean" };
26436     // NOTE: The order here is important to default lib ordering as entries will have the same
26437     //       order in the generated program (see `getDefaultLibPriority` in program.ts). This
26438     //       order also affects overload resolution when a type declared in one lib is
26439     //       augmented in another lib.
26440     var libEntries = [
26441         // JavaScript only
26442         ["es5", "lib.es5.d.ts"],
26443         ["es6", "lib.es2015.d.ts"],
26444         ["es2015", "lib.es2015.d.ts"],
26445         ["es7", "lib.es2016.d.ts"],
26446         ["es2016", "lib.es2016.d.ts"],
26447         ["es2017", "lib.es2017.d.ts"],
26448         ["es2018", "lib.es2018.d.ts"],
26449         ["es2019", "lib.es2019.d.ts"],
26450         ["es2020", "lib.es2020.d.ts"],
26451         ["esnext", "lib.esnext.d.ts"],
26452         // Host only
26453         ["dom", "lib.dom.d.ts"],
26454         ["dom.iterable", "lib.dom.iterable.d.ts"],
26455         ["webworker", "lib.webworker.d.ts"],
26456         ["webworker.importscripts", "lib.webworker.importscripts.d.ts"],
26457         ["scripthost", "lib.scripthost.d.ts"],
26458         // ES2015 Or ESNext By-feature options
26459         ["es2015.core", "lib.es2015.core.d.ts"],
26460         ["es2015.collection", "lib.es2015.collection.d.ts"],
26461         ["es2015.generator", "lib.es2015.generator.d.ts"],
26462         ["es2015.iterable", "lib.es2015.iterable.d.ts"],
26463         ["es2015.promise", "lib.es2015.promise.d.ts"],
26464         ["es2015.proxy", "lib.es2015.proxy.d.ts"],
26465         ["es2015.reflect", "lib.es2015.reflect.d.ts"],
26466         ["es2015.symbol", "lib.es2015.symbol.d.ts"],
26467         ["es2015.symbol.wellknown", "lib.es2015.symbol.wellknown.d.ts"],
26468         ["es2016.array.include", "lib.es2016.array.include.d.ts"],
26469         ["es2017.object", "lib.es2017.object.d.ts"],
26470         ["es2017.sharedmemory", "lib.es2017.sharedmemory.d.ts"],
26471         ["es2017.string", "lib.es2017.string.d.ts"],
26472         ["es2017.intl", "lib.es2017.intl.d.ts"],
26473         ["es2017.typedarrays", "lib.es2017.typedarrays.d.ts"],
26474         ["es2018.asyncgenerator", "lib.es2018.asyncgenerator.d.ts"],
26475         ["es2018.asynciterable", "lib.es2018.asynciterable.d.ts"],
26476         ["es2018.intl", "lib.es2018.intl.d.ts"],
26477         ["es2018.promise", "lib.es2018.promise.d.ts"],
26478         ["es2018.regexp", "lib.es2018.regexp.d.ts"],
26479         ["es2019.array", "lib.es2019.array.d.ts"],
26480         ["es2019.object", "lib.es2019.object.d.ts"],
26481         ["es2019.string", "lib.es2019.string.d.ts"],
26482         ["es2019.symbol", "lib.es2019.symbol.d.ts"],
26483         ["es2020.bigint", "lib.es2020.bigint.d.ts"],
26484         ["es2020.promise", "lib.es2020.promise.d.ts"],
26485         ["es2020.string", "lib.es2020.string.d.ts"],
26486         ["es2020.symbol.wellknown", "lib.es2020.symbol.wellknown.d.ts"],
26487         ["esnext.array", "lib.es2019.array.d.ts"],
26488         ["esnext.symbol", "lib.es2019.symbol.d.ts"],
26489         ["esnext.asynciterable", "lib.es2018.asynciterable.d.ts"],
26490         ["esnext.intl", "lib.esnext.intl.d.ts"],
26491         ["esnext.bigint", "lib.es2020.bigint.d.ts"],
26492         ["esnext.string", "lib.esnext.string.d.ts"],
26493         ["esnext.promise", "lib.esnext.promise.d.ts"]
26494     ];
26495     /**
26496      * An array of supported "lib" reference file names used to determine the order for inclusion
26497      * when referenced, as well as for spelling suggestions. This ensures the correct ordering for
26498      * overload resolution when a type declared in one lib is extended by another.
26499      */
26500     /* @internal */
26501     ts.libs = libEntries.map(function (entry) { return entry[0]; });
26502     /**
26503      * A map of lib names to lib files. This map is used both for parsing the "lib" command line
26504      * option as well as for resolving lib reference directives.
26505      */
26506     /* @internal */
26507     ts.libMap = ts.createMapFromEntries(libEntries);
26508     // Watch related options
26509     /* @internal */
26510     ts.optionsForWatch = [
26511         {
26512             name: "watchFile",
26513             type: ts.createMapFromTemplate({
26514                 fixedpollinginterval: ts.WatchFileKind.FixedPollingInterval,
26515                 prioritypollinginterval: ts.WatchFileKind.PriorityPollingInterval,
26516                 dynamicprioritypolling: ts.WatchFileKind.DynamicPriorityPolling,
26517                 usefsevents: ts.WatchFileKind.UseFsEvents,
26518                 usefseventsonparentdirectory: ts.WatchFileKind.UseFsEventsOnParentDirectory,
26519             }),
26520             category: ts.Diagnostics.Advanced_Options,
26521             description: ts.Diagnostics.Specify_strategy_for_watching_file_Colon_FixedPollingInterval_default_PriorityPollingInterval_DynamicPriorityPolling_UseFsEvents_UseFsEventsOnParentDirectory,
26522         },
26523         {
26524             name: "watchDirectory",
26525             type: ts.createMapFromTemplate({
26526                 usefsevents: ts.WatchDirectoryKind.UseFsEvents,
26527                 fixedpollinginterval: ts.WatchDirectoryKind.FixedPollingInterval,
26528                 dynamicprioritypolling: ts.WatchDirectoryKind.DynamicPriorityPolling,
26529             }),
26530             category: ts.Diagnostics.Advanced_Options,
26531             description: ts.Diagnostics.Specify_strategy_for_watching_directory_on_platforms_that_don_t_support_recursive_watching_natively_Colon_UseFsEvents_default_FixedPollingInterval_DynamicPriorityPolling,
26532         },
26533         {
26534             name: "fallbackPolling",
26535             type: ts.createMapFromTemplate({
26536                 fixedinterval: ts.PollingWatchKind.FixedInterval,
26537                 priorityinterval: ts.PollingWatchKind.PriorityInterval,
26538                 dynamicpriority: ts.PollingWatchKind.DynamicPriority,
26539             }),
26540             category: ts.Diagnostics.Advanced_Options,
26541             description: ts.Diagnostics.Specify_strategy_for_creating_a_polling_watch_when_it_fails_to_create_using_file_system_events_Colon_FixedInterval_default_PriorityInterval_DynamicPriority,
26542         },
26543         {
26544             name: "synchronousWatchDirectory",
26545             type: "boolean",
26546             category: ts.Diagnostics.Advanced_Options,
26547             description: ts.Diagnostics.Synchronously_call_callbacks_and_update_the_state_of_directory_watchers_on_platforms_that_don_t_support_recursive_watching_natively,
26548         },
26549     ];
26550     /* @internal */
26551     ts.commonOptionsWithBuild = [
26552         {
26553             name: "help",
26554             shortName: "h",
26555             type: "boolean",
26556             showInSimplifiedHelpView: true,
26557             category: ts.Diagnostics.Command_line_Options,
26558             description: ts.Diagnostics.Print_this_message,
26559         },
26560         {
26561             name: "help",
26562             shortName: "?",
26563             type: "boolean"
26564         },
26565         {
26566             name: "watch",
26567             shortName: "w",
26568             type: "boolean",
26569             showInSimplifiedHelpView: true,
26570             category: ts.Diagnostics.Command_line_Options,
26571             description: ts.Diagnostics.Watch_input_files,
26572         },
26573         {
26574             name: "preserveWatchOutput",
26575             type: "boolean",
26576             showInSimplifiedHelpView: false,
26577             category: ts.Diagnostics.Command_line_Options,
26578             description: ts.Diagnostics.Whether_to_keep_outdated_console_output_in_watch_mode_instead_of_clearing_the_screen,
26579         },
26580         {
26581             name: "listFiles",
26582             type: "boolean",
26583             category: ts.Diagnostics.Advanced_Options,
26584             description: ts.Diagnostics.Print_names_of_files_part_of_the_compilation
26585         },
26586         {
26587             name: "listEmittedFiles",
26588             type: "boolean",
26589             category: ts.Diagnostics.Advanced_Options,
26590             description: ts.Diagnostics.Print_names_of_generated_files_part_of_the_compilation
26591         },
26592         {
26593             name: "pretty",
26594             type: "boolean",
26595             showInSimplifiedHelpView: true,
26596             category: ts.Diagnostics.Command_line_Options,
26597             description: ts.Diagnostics.Stylize_errors_and_messages_using_color_and_context_experimental
26598         },
26599         {
26600             name: "traceResolution",
26601             type: "boolean",
26602             category: ts.Diagnostics.Advanced_Options,
26603             description: ts.Diagnostics.Enable_tracing_of_the_name_resolution_process
26604         },
26605         {
26606             name: "diagnostics",
26607             type: "boolean",
26608             category: ts.Diagnostics.Advanced_Options,
26609             description: ts.Diagnostics.Show_diagnostic_information
26610         },
26611         {
26612             name: "extendedDiagnostics",
26613             type: "boolean",
26614             category: ts.Diagnostics.Advanced_Options,
26615             description: ts.Diagnostics.Show_verbose_diagnostic_information
26616         },
26617         {
26618             name: "generateCpuProfile",
26619             type: "string",
26620             isFilePath: true,
26621             paramType: ts.Diagnostics.FILE_OR_DIRECTORY,
26622             category: ts.Diagnostics.Advanced_Options,
26623             description: ts.Diagnostics.Generates_a_CPU_profile
26624         },
26625         {
26626             name: "incremental",
26627             shortName: "i",
26628             type: "boolean",
26629             category: ts.Diagnostics.Basic_Options,
26630             description: ts.Diagnostics.Enable_incremental_compilation,
26631             transpileOptionValue: undefined
26632         },
26633         {
26634             name: "assumeChangesOnlyAffectDirectDependencies",
26635             type: "boolean",
26636             affectsSemanticDiagnostics: true,
26637             affectsEmit: true,
26638             category: ts.Diagnostics.Advanced_Options,
26639             description: ts.Diagnostics.Have_recompiles_in_incremental_and_watch_assume_that_changes_within_a_file_will_only_affect_files_directly_depending_on_it
26640         },
26641         {
26642             name: "locale",
26643             type: "string",
26644             category: ts.Diagnostics.Advanced_Options,
26645             description: ts.Diagnostics.The_locale_used_when_displaying_messages_to_the_user_e_g_en_us
26646         },
26647     ];
26648     /* @internal */
26649     ts.optionDeclarations = __spreadArrays(ts.commonOptionsWithBuild, [
26650         {
26651             name: "all",
26652             type: "boolean",
26653             showInSimplifiedHelpView: true,
26654             category: ts.Diagnostics.Command_line_Options,
26655             description: ts.Diagnostics.Show_all_compiler_options,
26656         },
26657         {
26658             name: "version",
26659             shortName: "v",
26660             type: "boolean",
26661             showInSimplifiedHelpView: true,
26662             category: ts.Diagnostics.Command_line_Options,
26663             description: ts.Diagnostics.Print_the_compiler_s_version,
26664         },
26665         {
26666             name: "init",
26667             type: "boolean",
26668             showInSimplifiedHelpView: true,
26669             category: ts.Diagnostics.Command_line_Options,
26670             description: ts.Diagnostics.Initializes_a_TypeScript_project_and_creates_a_tsconfig_json_file,
26671         },
26672         {
26673             name: "project",
26674             shortName: "p",
26675             type: "string",
26676             isFilePath: true,
26677             showInSimplifiedHelpView: true,
26678             category: ts.Diagnostics.Command_line_Options,
26679             paramType: ts.Diagnostics.FILE_OR_DIRECTORY,
26680             description: ts.Diagnostics.Compile_the_project_given_the_path_to_its_configuration_file_or_to_a_folder_with_a_tsconfig_json,
26681         },
26682         {
26683             name: "build",
26684             type: "boolean",
26685             shortName: "b",
26686             showInSimplifiedHelpView: true,
26687             category: ts.Diagnostics.Command_line_Options,
26688             description: ts.Diagnostics.Build_one_or_more_projects_and_their_dependencies_if_out_of_date
26689         },
26690         {
26691             name: "showConfig",
26692             type: "boolean",
26693             category: ts.Diagnostics.Command_line_Options,
26694             isCommandLineOnly: true,
26695             description: ts.Diagnostics.Print_the_final_configuration_instead_of_building
26696         },
26697         {
26698             name: "listFilesOnly",
26699             type: "boolean",
26700             category: ts.Diagnostics.Command_line_Options,
26701             affectsSemanticDiagnostics: true,
26702             affectsEmit: true,
26703             isCommandLineOnly: true,
26704             description: ts.Diagnostics.Print_names_of_files_that_are_part_of_the_compilation_and_then_stop_processing
26705         },
26706         // Basic
26707         {
26708             name: "target",
26709             shortName: "t",
26710             type: ts.createMapFromTemplate({
26711                 es3: 0 /* ES3 */,
26712                 es5: 1 /* ES5 */,
26713                 es6: 2 /* ES2015 */,
26714                 es2015: 2 /* ES2015 */,
26715                 es2016: 3 /* ES2016 */,
26716                 es2017: 4 /* ES2017 */,
26717                 es2018: 5 /* ES2018 */,
26718                 es2019: 6 /* ES2019 */,
26719                 es2020: 7 /* ES2020 */,
26720                 esnext: 99 /* ESNext */,
26721             }),
26722             affectsSourceFile: true,
26723             affectsModuleResolution: true,
26724             affectsEmit: true,
26725             paramType: ts.Diagnostics.VERSION,
26726             showInSimplifiedHelpView: true,
26727             category: ts.Diagnostics.Basic_Options,
26728             description: ts.Diagnostics.Specify_ECMAScript_target_version_Colon_ES3_default_ES5_ES2015_ES2016_ES2017_ES2018_ES2019_ES2020_or_ESNEXT,
26729         },
26730         {
26731             name: "module",
26732             shortName: "m",
26733             type: ts.createMapFromTemplate({
26734                 none: ts.ModuleKind.None,
26735                 commonjs: ts.ModuleKind.CommonJS,
26736                 amd: ts.ModuleKind.AMD,
26737                 system: ts.ModuleKind.System,
26738                 umd: ts.ModuleKind.UMD,
26739                 es6: ts.ModuleKind.ES2015,
26740                 es2015: ts.ModuleKind.ES2015,
26741                 es2020: ts.ModuleKind.ES2020,
26742                 esnext: ts.ModuleKind.ESNext
26743             }),
26744             affectsModuleResolution: true,
26745             affectsEmit: true,
26746             paramType: ts.Diagnostics.KIND,
26747             showInSimplifiedHelpView: true,
26748             category: ts.Diagnostics.Basic_Options,
26749             description: ts.Diagnostics.Specify_module_code_generation_Colon_none_commonjs_amd_system_umd_es2015_es2020_or_ESNext,
26750         },
26751         {
26752             name: "lib",
26753             type: "list",
26754             element: {
26755                 name: "lib",
26756                 type: ts.libMap
26757             },
26758             affectsModuleResolution: true,
26759             showInSimplifiedHelpView: true,
26760             category: ts.Diagnostics.Basic_Options,
26761             description: ts.Diagnostics.Specify_library_files_to_be_included_in_the_compilation,
26762             transpileOptionValue: undefined
26763         },
26764         {
26765             name: "allowJs",
26766             type: "boolean",
26767             affectsModuleResolution: true,
26768             showInSimplifiedHelpView: true,
26769             category: ts.Diagnostics.Basic_Options,
26770             description: ts.Diagnostics.Allow_javascript_files_to_be_compiled
26771         },
26772         {
26773             name: "checkJs",
26774             type: "boolean",
26775             category: ts.Diagnostics.Basic_Options,
26776             description: ts.Diagnostics.Report_errors_in_js_files
26777         },
26778         {
26779             name: "jsx",
26780             type: ts.createMapFromTemplate({
26781                 "preserve": 1 /* Preserve */,
26782                 "react-native": 3 /* ReactNative */,
26783                 "react": 2 /* React */
26784             }),
26785             affectsSourceFile: true,
26786             paramType: ts.Diagnostics.KIND,
26787             showInSimplifiedHelpView: true,
26788             category: ts.Diagnostics.Basic_Options,
26789             description: ts.Diagnostics.Specify_JSX_code_generation_Colon_preserve_react_native_or_react,
26790         },
26791         {
26792             name: "declaration",
26793             shortName: "d",
26794             type: "boolean",
26795             affectsEmit: true,
26796             showInSimplifiedHelpView: true,
26797             category: ts.Diagnostics.Basic_Options,
26798             description: ts.Diagnostics.Generates_corresponding_d_ts_file,
26799             transpileOptionValue: undefined
26800         },
26801         {
26802             name: "declarationMap",
26803             type: "boolean",
26804             affectsEmit: true,
26805             showInSimplifiedHelpView: true,
26806             category: ts.Diagnostics.Basic_Options,
26807             description: ts.Diagnostics.Generates_a_sourcemap_for_each_corresponding_d_ts_file,
26808             transpileOptionValue: undefined
26809         },
26810         {
26811             name: "emitDeclarationOnly",
26812             type: "boolean",
26813             affectsEmit: true,
26814             category: ts.Diagnostics.Advanced_Options,
26815             description: ts.Diagnostics.Only_emit_d_ts_declaration_files,
26816             transpileOptionValue: undefined
26817         },
26818         {
26819             name: "sourceMap",
26820             type: "boolean",
26821             affectsEmit: true,
26822             showInSimplifiedHelpView: true,
26823             category: ts.Diagnostics.Basic_Options,
26824             description: ts.Diagnostics.Generates_corresponding_map_file,
26825         },
26826         {
26827             name: "outFile",
26828             type: "string",
26829             affectsEmit: true,
26830             isFilePath: true,
26831             paramType: ts.Diagnostics.FILE,
26832             showInSimplifiedHelpView: true,
26833             category: ts.Diagnostics.Basic_Options,
26834             description: ts.Diagnostics.Concatenate_and_emit_output_to_single_file,
26835             transpileOptionValue: undefined
26836         },
26837         {
26838             name: "outDir",
26839             type: "string",
26840             affectsEmit: true,
26841             isFilePath: true,
26842             paramType: ts.Diagnostics.DIRECTORY,
26843             showInSimplifiedHelpView: true,
26844             category: ts.Diagnostics.Basic_Options,
26845             description: ts.Diagnostics.Redirect_output_structure_to_the_directory,
26846         },
26847         {
26848             name: "rootDir",
26849             type: "string",
26850             affectsEmit: true,
26851             isFilePath: true,
26852             paramType: ts.Diagnostics.LOCATION,
26853             category: ts.Diagnostics.Basic_Options,
26854             description: ts.Diagnostics.Specify_the_root_directory_of_input_files_Use_to_control_the_output_directory_structure_with_outDir,
26855         },
26856         {
26857             name: "composite",
26858             type: "boolean",
26859             affectsEmit: true,
26860             isTSConfigOnly: true,
26861             category: ts.Diagnostics.Basic_Options,
26862             description: ts.Diagnostics.Enable_project_compilation,
26863             transpileOptionValue: undefined
26864         },
26865         {
26866             name: "tsBuildInfoFile",
26867             type: "string",
26868             affectsEmit: true,
26869             isFilePath: true,
26870             paramType: ts.Diagnostics.FILE,
26871             category: ts.Diagnostics.Basic_Options,
26872             description: ts.Diagnostics.Specify_file_to_store_incremental_compilation_information,
26873             transpileOptionValue: undefined
26874         },
26875         {
26876             name: "removeComments",
26877             type: "boolean",
26878             affectsEmit: true,
26879             showInSimplifiedHelpView: true,
26880             category: ts.Diagnostics.Basic_Options,
26881             description: ts.Diagnostics.Do_not_emit_comments_to_output,
26882         },
26883         {
26884             name: "noEmit",
26885             type: "boolean",
26886             affectsEmit: true,
26887             showInSimplifiedHelpView: true,
26888             category: ts.Diagnostics.Basic_Options,
26889             description: ts.Diagnostics.Do_not_emit_outputs,
26890             transpileOptionValue: undefined
26891         },
26892         {
26893             name: "importHelpers",
26894             type: "boolean",
26895             affectsEmit: true,
26896             category: ts.Diagnostics.Basic_Options,
26897             description: ts.Diagnostics.Import_emit_helpers_from_tslib
26898         },
26899         {
26900             name: "importsNotUsedAsValues",
26901             type: ts.createMapFromTemplate({
26902                 remove: 0 /* Remove */,
26903                 preserve: 1 /* Preserve */,
26904                 error: 2 /* Error */
26905             }),
26906             affectsEmit: true,
26907             affectsSemanticDiagnostics: true,
26908             category: ts.Diagnostics.Advanced_Options,
26909             description: ts.Diagnostics.Specify_emit_Slashchecking_behavior_for_imports_that_are_only_used_for_types
26910         },
26911         {
26912             name: "downlevelIteration",
26913             type: "boolean",
26914             affectsEmit: true,
26915             category: ts.Diagnostics.Basic_Options,
26916             description: ts.Diagnostics.Provide_full_support_for_iterables_in_for_of_spread_and_destructuring_when_targeting_ES5_or_ES3
26917         },
26918         {
26919             name: "isolatedModules",
26920             type: "boolean",
26921             category: ts.Diagnostics.Basic_Options,
26922             description: ts.Diagnostics.Transpile_each_file_as_a_separate_module_similar_to_ts_transpileModule,
26923             transpileOptionValue: true
26924         },
26925         // Strict Type Checks
26926         {
26927             name: "strict",
26928             type: "boolean",
26929             showInSimplifiedHelpView: true,
26930             category: ts.Diagnostics.Strict_Type_Checking_Options,
26931             description: ts.Diagnostics.Enable_all_strict_type_checking_options
26932         },
26933         {
26934             name: "noImplicitAny",
26935             type: "boolean",
26936             affectsSemanticDiagnostics: true,
26937             strictFlag: true,
26938             showInSimplifiedHelpView: true,
26939             category: ts.Diagnostics.Strict_Type_Checking_Options,
26940             description: ts.Diagnostics.Raise_error_on_expressions_and_declarations_with_an_implied_any_type
26941         },
26942         {
26943             name: "strictNullChecks",
26944             type: "boolean",
26945             affectsSemanticDiagnostics: true,
26946             strictFlag: true,
26947             showInSimplifiedHelpView: true,
26948             category: ts.Diagnostics.Strict_Type_Checking_Options,
26949             description: ts.Diagnostics.Enable_strict_null_checks
26950         },
26951         {
26952             name: "strictFunctionTypes",
26953             type: "boolean",
26954             affectsSemanticDiagnostics: true,
26955             strictFlag: true,
26956             showInSimplifiedHelpView: true,
26957             category: ts.Diagnostics.Strict_Type_Checking_Options,
26958             description: ts.Diagnostics.Enable_strict_checking_of_function_types
26959         },
26960         {
26961             name: "strictBindCallApply",
26962             type: "boolean",
26963             strictFlag: true,
26964             showInSimplifiedHelpView: true,
26965             category: ts.Diagnostics.Strict_Type_Checking_Options,
26966             description: ts.Diagnostics.Enable_strict_bind_call_and_apply_methods_on_functions
26967         },
26968         {
26969             name: "strictPropertyInitialization",
26970             type: "boolean",
26971             affectsSemanticDiagnostics: true,
26972             strictFlag: true,
26973             showInSimplifiedHelpView: true,
26974             category: ts.Diagnostics.Strict_Type_Checking_Options,
26975             description: ts.Diagnostics.Enable_strict_checking_of_property_initialization_in_classes
26976         },
26977         {
26978             name: "noImplicitThis",
26979             type: "boolean",
26980             affectsSemanticDiagnostics: true,
26981             strictFlag: true,
26982             showInSimplifiedHelpView: true,
26983             category: ts.Diagnostics.Strict_Type_Checking_Options,
26984             description: ts.Diagnostics.Raise_error_on_this_expressions_with_an_implied_any_type,
26985         },
26986         {
26987             name: "alwaysStrict",
26988             type: "boolean",
26989             affectsSourceFile: true,
26990             strictFlag: true,
26991             showInSimplifiedHelpView: true,
26992             category: ts.Diagnostics.Strict_Type_Checking_Options,
26993             description: ts.Diagnostics.Parse_in_strict_mode_and_emit_use_strict_for_each_source_file
26994         },
26995         // Additional Checks
26996         {
26997             name: "noUnusedLocals",
26998             type: "boolean",
26999             affectsSemanticDiagnostics: true,
27000             showInSimplifiedHelpView: true,
27001             category: ts.Diagnostics.Additional_Checks,
27002             description: ts.Diagnostics.Report_errors_on_unused_locals,
27003         },
27004         {
27005             name: "noUnusedParameters",
27006             type: "boolean",
27007             affectsSemanticDiagnostics: true,
27008             showInSimplifiedHelpView: true,
27009             category: ts.Diagnostics.Additional_Checks,
27010             description: ts.Diagnostics.Report_errors_on_unused_parameters,
27011         },
27012         {
27013             name: "noImplicitReturns",
27014             type: "boolean",
27015             affectsSemanticDiagnostics: true,
27016             showInSimplifiedHelpView: true,
27017             category: ts.Diagnostics.Additional_Checks,
27018             description: ts.Diagnostics.Report_error_when_not_all_code_paths_in_function_return_a_value
27019         },
27020         {
27021             name: "noFallthroughCasesInSwitch",
27022             type: "boolean",
27023             affectsBindDiagnostics: true,
27024             affectsSemanticDiagnostics: true,
27025             showInSimplifiedHelpView: true,
27026             category: ts.Diagnostics.Additional_Checks,
27027             description: ts.Diagnostics.Report_errors_for_fallthrough_cases_in_switch_statement
27028         },
27029         // Module Resolution
27030         {
27031             name: "moduleResolution",
27032             type: ts.createMapFromTemplate({
27033                 node: ts.ModuleResolutionKind.NodeJs,
27034                 classic: ts.ModuleResolutionKind.Classic,
27035             }),
27036             affectsModuleResolution: true,
27037             paramType: ts.Diagnostics.STRATEGY,
27038             category: ts.Diagnostics.Module_Resolution_Options,
27039             description: ts.Diagnostics.Specify_module_resolution_strategy_Colon_node_Node_js_or_classic_TypeScript_pre_1_6,
27040         },
27041         {
27042             name: "baseUrl",
27043             type: "string",
27044             affectsModuleResolution: true,
27045             isFilePath: true,
27046             category: ts.Diagnostics.Module_Resolution_Options,
27047             description: ts.Diagnostics.Base_directory_to_resolve_non_absolute_module_names
27048         },
27049         {
27050             // this option can only be specified in tsconfig.json
27051             // use type = object to copy the value as-is
27052             name: "paths",
27053             type: "object",
27054             affectsModuleResolution: true,
27055             isTSConfigOnly: true,
27056             category: ts.Diagnostics.Module_Resolution_Options,
27057             description: ts.Diagnostics.A_series_of_entries_which_re_map_imports_to_lookup_locations_relative_to_the_baseUrl,
27058             transpileOptionValue: undefined
27059         },
27060         {
27061             // this option can only be specified in tsconfig.json
27062             // use type = object to copy the value as-is
27063             name: "rootDirs",
27064             type: "list",
27065             isTSConfigOnly: true,
27066             element: {
27067                 name: "rootDirs",
27068                 type: "string",
27069                 isFilePath: true
27070             },
27071             affectsModuleResolution: true,
27072             category: ts.Diagnostics.Module_Resolution_Options,
27073             description: ts.Diagnostics.List_of_root_folders_whose_combined_content_represents_the_structure_of_the_project_at_runtime,
27074             transpileOptionValue: undefined
27075         },
27076         {
27077             name: "typeRoots",
27078             type: "list",
27079             element: {
27080                 name: "typeRoots",
27081                 type: "string",
27082                 isFilePath: true
27083             },
27084             affectsModuleResolution: true,
27085             category: ts.Diagnostics.Module_Resolution_Options,
27086             description: ts.Diagnostics.List_of_folders_to_include_type_definitions_from
27087         },
27088         {
27089             name: "types",
27090             type: "list",
27091             element: {
27092                 name: "types",
27093                 type: "string"
27094             },
27095             affectsModuleResolution: true,
27096             showInSimplifiedHelpView: true,
27097             category: ts.Diagnostics.Module_Resolution_Options,
27098             description: ts.Diagnostics.Type_declaration_files_to_be_included_in_compilation,
27099             transpileOptionValue: undefined
27100         },
27101         {
27102             name: "allowSyntheticDefaultImports",
27103             type: "boolean",
27104             affectsSemanticDiagnostics: true,
27105             category: ts.Diagnostics.Module_Resolution_Options,
27106             description: ts.Diagnostics.Allow_default_imports_from_modules_with_no_default_export_This_does_not_affect_code_emit_just_typechecking
27107         },
27108         {
27109             name: "esModuleInterop",
27110             type: "boolean",
27111             affectsSemanticDiagnostics: true,
27112             affectsEmit: true,
27113             showInSimplifiedHelpView: true,
27114             category: ts.Diagnostics.Module_Resolution_Options,
27115             description: ts.Diagnostics.Enables_emit_interoperability_between_CommonJS_and_ES_Modules_via_creation_of_namespace_objects_for_all_imports_Implies_allowSyntheticDefaultImports
27116         },
27117         {
27118             name: "preserveSymlinks",
27119             type: "boolean",
27120             category: ts.Diagnostics.Module_Resolution_Options,
27121             description: ts.Diagnostics.Do_not_resolve_the_real_path_of_symlinks,
27122         },
27123         {
27124             name: "allowUmdGlobalAccess",
27125             type: "boolean",
27126             affectsSemanticDiagnostics: true,
27127             category: ts.Diagnostics.Module_Resolution_Options,
27128             description: ts.Diagnostics.Allow_accessing_UMD_globals_from_modules,
27129         },
27130         // Source Maps
27131         {
27132             name: "sourceRoot",
27133             type: "string",
27134             affectsEmit: true,
27135             paramType: ts.Diagnostics.LOCATION,
27136             category: ts.Diagnostics.Source_Map_Options,
27137             description: ts.Diagnostics.Specify_the_location_where_debugger_should_locate_TypeScript_files_instead_of_source_locations,
27138         },
27139         {
27140             name: "mapRoot",
27141             type: "string",
27142             affectsEmit: true,
27143             paramType: ts.Diagnostics.LOCATION,
27144             category: ts.Diagnostics.Source_Map_Options,
27145             description: ts.Diagnostics.Specify_the_location_where_debugger_should_locate_map_files_instead_of_generated_locations,
27146         },
27147         {
27148             name: "inlineSourceMap",
27149             type: "boolean",
27150             affectsEmit: true,
27151             category: ts.Diagnostics.Source_Map_Options,
27152             description: ts.Diagnostics.Emit_a_single_file_with_source_maps_instead_of_having_a_separate_file
27153         },
27154         {
27155             name: "inlineSources",
27156             type: "boolean",
27157             affectsEmit: true,
27158             category: ts.Diagnostics.Source_Map_Options,
27159             description: ts.Diagnostics.Emit_the_source_alongside_the_sourcemaps_within_a_single_file_requires_inlineSourceMap_or_sourceMap_to_be_set
27160         },
27161         // Experimental
27162         {
27163             name: "experimentalDecorators",
27164             type: "boolean",
27165             affectsSemanticDiagnostics: true,
27166             category: ts.Diagnostics.Experimental_Options,
27167             description: ts.Diagnostics.Enables_experimental_support_for_ES7_decorators
27168         },
27169         {
27170             name: "emitDecoratorMetadata",
27171             type: "boolean",
27172             affectsSemanticDiagnostics: true,
27173             affectsEmit: true,
27174             category: ts.Diagnostics.Experimental_Options,
27175             description: ts.Diagnostics.Enables_experimental_support_for_emitting_type_metadata_for_decorators
27176         },
27177         // Advanced
27178         {
27179             name: "jsxFactory",
27180             type: "string",
27181             category: ts.Diagnostics.Advanced_Options,
27182             description: ts.Diagnostics.Specify_the_JSX_factory_function_to_use_when_targeting_react_JSX_emit_e_g_React_createElement_or_h
27183         },
27184         {
27185             name: "resolveJsonModule",
27186             type: "boolean",
27187             affectsModuleResolution: true,
27188             category: ts.Diagnostics.Advanced_Options,
27189             description: ts.Diagnostics.Include_modules_imported_with_json_extension
27190         },
27191         {
27192             name: "out",
27193             type: "string",
27194             affectsEmit: true,
27195             isFilePath: false,
27196             // for correct behaviour, please use outFile
27197             category: ts.Diagnostics.Advanced_Options,
27198             paramType: ts.Diagnostics.FILE,
27199             description: ts.Diagnostics.Deprecated_Use_outFile_instead_Concatenate_and_emit_output_to_single_file,
27200             transpileOptionValue: undefined
27201         },
27202         {
27203             name: "reactNamespace",
27204             type: "string",
27205             affectsEmit: true,
27206             category: ts.Diagnostics.Advanced_Options,
27207             description: ts.Diagnostics.Deprecated_Use_jsxFactory_instead_Specify_the_object_invoked_for_createElement_when_targeting_react_JSX_emit
27208         },
27209         {
27210             name: "skipDefaultLibCheck",
27211             type: "boolean",
27212             category: ts.Diagnostics.Advanced_Options,
27213             description: ts.Diagnostics.Deprecated_Use_skipLibCheck_instead_Skip_type_checking_of_default_library_declaration_files
27214         },
27215         {
27216             name: "charset",
27217             type: "string",
27218             category: ts.Diagnostics.Advanced_Options,
27219             description: ts.Diagnostics.The_character_set_of_the_input_files
27220         },
27221         {
27222             name: "emitBOM",
27223             type: "boolean",
27224             affectsEmit: true,
27225             category: ts.Diagnostics.Advanced_Options,
27226             description: ts.Diagnostics.Emit_a_UTF_8_Byte_Order_Mark_BOM_in_the_beginning_of_output_files
27227         },
27228         {
27229             name: "newLine",
27230             type: ts.createMapFromTemplate({
27231                 crlf: 0 /* CarriageReturnLineFeed */,
27232                 lf: 1 /* LineFeed */
27233             }),
27234             affectsEmit: true,
27235             paramType: ts.Diagnostics.NEWLINE,
27236             category: ts.Diagnostics.Advanced_Options,
27237             description: ts.Diagnostics.Specify_the_end_of_line_sequence_to_be_used_when_emitting_files_Colon_CRLF_dos_or_LF_unix,
27238         },
27239         {
27240             name: "noErrorTruncation",
27241             type: "boolean",
27242             affectsSemanticDiagnostics: true,
27243             category: ts.Diagnostics.Advanced_Options,
27244             description: ts.Diagnostics.Do_not_truncate_error_messages
27245         },
27246         {
27247             name: "noLib",
27248             type: "boolean",
27249             affectsModuleResolution: true,
27250             category: ts.Diagnostics.Advanced_Options,
27251             description: ts.Diagnostics.Do_not_include_the_default_library_file_lib_d_ts,
27252             // We are not returning a sourceFile for lib file when asked by the program,
27253             // so pass --noLib to avoid reporting a file not found error.
27254             transpileOptionValue: true
27255         },
27256         {
27257             name: "noResolve",
27258             type: "boolean",
27259             affectsModuleResolution: true,
27260             category: ts.Diagnostics.Advanced_Options,
27261             description: ts.Diagnostics.Do_not_add_triple_slash_references_or_imported_modules_to_the_list_of_compiled_files,
27262             // We are not doing a full typecheck, we are not resolving the whole context,
27263             // so pass --noResolve to avoid reporting missing file errors.
27264             transpileOptionValue: true
27265         },
27266         {
27267             name: "stripInternal",
27268             type: "boolean",
27269             affectsEmit: true,
27270             category: ts.Diagnostics.Advanced_Options,
27271             description: ts.Diagnostics.Do_not_emit_declarations_for_code_that_has_an_internal_annotation,
27272         },
27273         {
27274             name: "disableSizeLimit",
27275             type: "boolean",
27276             affectsSourceFile: true,
27277             category: ts.Diagnostics.Advanced_Options,
27278             description: ts.Diagnostics.Disable_size_limitations_on_JavaScript_projects
27279         },
27280         {
27281             name: "disableSourceOfProjectReferenceRedirect",
27282             type: "boolean",
27283             isTSConfigOnly: true,
27284             category: ts.Diagnostics.Advanced_Options,
27285             description: ts.Diagnostics.Disable_use_of_source_files_instead_of_declaration_files_from_referenced_projects
27286         },
27287         {
27288             name: "disableSolutionSearching",
27289             type: "boolean",
27290             isTSConfigOnly: true,
27291             category: ts.Diagnostics.Advanced_Options,
27292             description: ts.Diagnostics.Disable_solution_searching_for_this_project
27293         },
27294         {
27295             name: "noImplicitUseStrict",
27296             type: "boolean",
27297             affectsSemanticDiagnostics: true,
27298             category: ts.Diagnostics.Advanced_Options,
27299             description: ts.Diagnostics.Do_not_emit_use_strict_directives_in_module_output
27300         },
27301         {
27302             name: "noEmitHelpers",
27303             type: "boolean",
27304             affectsEmit: true,
27305             category: ts.Diagnostics.Advanced_Options,
27306             description: ts.Diagnostics.Do_not_generate_custom_helper_functions_like_extends_in_compiled_output
27307         },
27308         {
27309             name: "noEmitOnError",
27310             type: "boolean",
27311             affectsEmit: true,
27312             category: ts.Diagnostics.Advanced_Options,
27313             description: ts.Diagnostics.Do_not_emit_outputs_if_any_errors_were_reported,
27314             transpileOptionValue: undefined
27315         },
27316         {
27317             name: "preserveConstEnums",
27318             type: "boolean",
27319             affectsEmit: true,
27320             category: ts.Diagnostics.Advanced_Options,
27321             description: ts.Diagnostics.Do_not_erase_const_enum_declarations_in_generated_code
27322         },
27323         {
27324             name: "declarationDir",
27325             type: "string",
27326             affectsEmit: true,
27327             isFilePath: true,
27328             paramType: ts.Diagnostics.DIRECTORY,
27329             category: ts.Diagnostics.Advanced_Options,
27330             description: ts.Diagnostics.Output_directory_for_generated_declaration_files,
27331             transpileOptionValue: undefined
27332         },
27333         {
27334             name: "skipLibCheck",
27335             type: "boolean",
27336             category: ts.Diagnostics.Advanced_Options,
27337             description: ts.Diagnostics.Skip_type_checking_of_declaration_files,
27338         },
27339         {
27340             name: "allowUnusedLabels",
27341             type: "boolean",
27342             affectsBindDiagnostics: true,
27343             affectsSemanticDiagnostics: true,
27344             category: ts.Diagnostics.Advanced_Options,
27345             description: ts.Diagnostics.Do_not_report_errors_on_unused_labels
27346         },
27347         {
27348             name: "allowUnreachableCode",
27349             type: "boolean",
27350             affectsBindDiagnostics: true,
27351             affectsSemanticDiagnostics: true,
27352             category: ts.Diagnostics.Advanced_Options,
27353             description: ts.Diagnostics.Do_not_report_errors_on_unreachable_code
27354         },
27355         {
27356             name: "suppressExcessPropertyErrors",
27357             type: "boolean",
27358             affectsSemanticDiagnostics: true,
27359             category: ts.Diagnostics.Advanced_Options,
27360             description: ts.Diagnostics.Suppress_excess_property_checks_for_object_literals,
27361         },
27362         {
27363             name: "suppressImplicitAnyIndexErrors",
27364             type: "boolean",
27365             affectsSemanticDiagnostics: true,
27366             category: ts.Diagnostics.Advanced_Options,
27367             description: ts.Diagnostics.Suppress_noImplicitAny_errors_for_indexing_objects_lacking_index_signatures,
27368         },
27369         {
27370             name: "forceConsistentCasingInFileNames",
27371             type: "boolean",
27372             affectsModuleResolution: true,
27373             category: ts.Diagnostics.Advanced_Options,
27374             description: ts.Diagnostics.Disallow_inconsistently_cased_references_to_the_same_file
27375         },
27376         {
27377             name: "maxNodeModuleJsDepth",
27378             type: "number",
27379             affectsModuleResolution: true,
27380             category: ts.Diagnostics.Advanced_Options,
27381             description: ts.Diagnostics.The_maximum_dependency_depth_to_search_under_node_modules_and_load_JavaScript_files
27382         },
27383         {
27384             name: "noStrictGenericChecks",
27385             type: "boolean",
27386             affectsSemanticDiagnostics: true,
27387             category: ts.Diagnostics.Advanced_Options,
27388             description: ts.Diagnostics.Disable_strict_checking_of_generic_signatures_in_function_types,
27389         },
27390         {
27391             name: "useDefineForClassFields",
27392             type: "boolean",
27393             affectsSemanticDiagnostics: true,
27394             affectsEmit: true,
27395             category: ts.Diagnostics.Advanced_Options,
27396             description: ts.Diagnostics.Emit_class_fields_with_Define_instead_of_Set,
27397         },
27398         {
27399             name: "keyofStringsOnly",
27400             type: "boolean",
27401             category: ts.Diagnostics.Advanced_Options,
27402             description: ts.Diagnostics.Resolve_keyof_to_string_valued_property_names_only_no_numbers_or_symbols,
27403         },
27404         {
27405             // A list of plugins to load in the language service
27406             name: "plugins",
27407             type: "list",
27408             isTSConfigOnly: true,
27409             element: {
27410                 name: "plugin",
27411                 type: "object"
27412             },
27413             description: ts.Diagnostics.List_of_language_service_plugins
27414         },
27415     ]);
27416     /* @internal */
27417     ts.semanticDiagnosticsOptionDeclarations = ts.optionDeclarations.filter(function (option) { return !!option.affectsSemanticDiagnostics; });
27418     /* @internal */
27419     ts.affectsEmitOptionDeclarations = ts.optionDeclarations.filter(function (option) { return !!option.affectsEmit; });
27420     /* @internal */
27421     ts.moduleResolutionOptionDeclarations = ts.optionDeclarations.filter(function (option) { return !!option.affectsModuleResolution; });
27422     /* @internal */
27423     ts.sourceFileAffectingCompilerOptions = ts.optionDeclarations.filter(function (option) {
27424         return !!option.affectsSourceFile || !!option.affectsModuleResolution || !!option.affectsBindDiagnostics;
27425     });
27426     /* @internal */
27427     ts.transpileOptionValueCompilerOptions = ts.optionDeclarations.filter(function (option) {
27428         return ts.hasProperty(option, "transpileOptionValue");
27429     });
27430     /* @internal */
27431     ts.buildOpts = __spreadArrays(ts.commonOptionsWithBuild, [
27432         {
27433             name: "verbose",
27434             shortName: "v",
27435             category: ts.Diagnostics.Command_line_Options,
27436             description: ts.Diagnostics.Enable_verbose_logging,
27437             type: "boolean"
27438         },
27439         {
27440             name: "dry",
27441             shortName: "d",
27442             category: ts.Diagnostics.Command_line_Options,
27443             description: ts.Diagnostics.Show_what_would_be_built_or_deleted_if_specified_with_clean,
27444             type: "boolean"
27445         },
27446         {
27447             name: "force",
27448             shortName: "f",
27449             category: ts.Diagnostics.Command_line_Options,
27450             description: ts.Diagnostics.Build_all_projects_including_those_that_appear_to_be_up_to_date,
27451             type: "boolean"
27452         },
27453         {
27454             name: "clean",
27455             category: ts.Diagnostics.Command_line_Options,
27456             description: ts.Diagnostics.Delete_the_outputs_of_all_projects,
27457             type: "boolean"
27458         }
27459     ]);
27460     /* @internal */
27461     ts.typeAcquisitionDeclarations = [
27462         {
27463             /* @deprecated typingOptions.enableAutoDiscovery
27464              * Use typeAcquisition.enable instead.
27465              */
27466             name: "enableAutoDiscovery",
27467             type: "boolean",
27468         },
27469         {
27470             name: "enable",
27471             type: "boolean",
27472         },
27473         {
27474             name: "include",
27475             type: "list",
27476             element: {
27477                 name: "include",
27478                 type: "string"
27479             }
27480         },
27481         {
27482             name: "exclude",
27483             type: "list",
27484             element: {
27485                 name: "exclude",
27486                 type: "string"
27487             }
27488         }
27489     ];
27490     /*@internal*/
27491     function createOptionNameMap(optionDeclarations) {
27492         var optionsNameMap = ts.createMap();
27493         var shortOptionNames = ts.createMap();
27494         ts.forEach(optionDeclarations, function (option) {
27495             optionsNameMap.set(option.name.toLowerCase(), option);
27496             if (option.shortName) {
27497                 shortOptionNames.set(option.shortName, option.name);
27498             }
27499         });
27500         return { optionsNameMap: optionsNameMap, shortOptionNames: shortOptionNames };
27501     }
27502     ts.createOptionNameMap = createOptionNameMap;
27503     var optionsNameMapCache;
27504     /* @internal */
27505     function getOptionsNameMap() {
27506         return optionsNameMapCache || (optionsNameMapCache = createOptionNameMap(ts.optionDeclarations));
27507     }
27508     ts.getOptionsNameMap = getOptionsNameMap;
27509     /* @internal */
27510     ts.defaultInitCompilerOptions = {
27511         module: ts.ModuleKind.CommonJS,
27512         target: 1 /* ES5 */,
27513         strict: true,
27514         esModuleInterop: true,
27515         forceConsistentCasingInFileNames: true,
27516         skipLibCheck: true
27517     };
27518     /* @internal */
27519     function convertEnableAutoDiscoveryToEnable(typeAcquisition) {
27520         // Convert deprecated typingOptions.enableAutoDiscovery to typeAcquisition.enable
27521         if (typeAcquisition && typeAcquisition.enableAutoDiscovery !== undefined && typeAcquisition.enable === undefined) {
27522             return {
27523                 enable: typeAcquisition.enableAutoDiscovery,
27524                 include: typeAcquisition.include || [],
27525                 exclude: typeAcquisition.exclude || []
27526             };
27527         }
27528         return typeAcquisition;
27529     }
27530     ts.convertEnableAutoDiscoveryToEnable = convertEnableAutoDiscoveryToEnable;
27531     /* @internal */
27532     function createCompilerDiagnosticForInvalidCustomType(opt) {
27533         return createDiagnosticForInvalidCustomType(opt, ts.createCompilerDiagnostic);
27534     }
27535     ts.createCompilerDiagnosticForInvalidCustomType = createCompilerDiagnosticForInvalidCustomType;
27536     function createDiagnosticForInvalidCustomType(opt, createDiagnostic) {
27537         var namesOfType = ts.arrayFrom(opt.type.keys()).map(function (key) { return "'" + key + "'"; }).join(", ");
27538         return createDiagnostic(ts.Diagnostics.Argument_for_0_option_must_be_Colon_1, "--" + opt.name, namesOfType);
27539     }
27540     /* @internal */
27541     function parseCustomTypeOption(opt, value, errors) {
27542         return convertJsonOptionOfCustomType(opt, trimString(value || ""), errors);
27543     }
27544     ts.parseCustomTypeOption = parseCustomTypeOption;
27545     /* @internal */
27546     function parseListTypeOption(opt, value, errors) {
27547         if (value === void 0) { value = ""; }
27548         value = trimString(value);
27549         if (ts.startsWith(value, "-")) {
27550             return undefined;
27551         }
27552         if (value === "") {
27553             return [];
27554         }
27555         var values = value.split(",");
27556         switch (opt.element.type) {
27557             case "number":
27558                 return ts.map(values, parseInt);
27559             case "string":
27560                 return ts.map(values, function (v) { return v || ""; });
27561             default:
27562                 return ts.mapDefined(values, function (v) { return parseCustomTypeOption(opt.element, v, errors); });
27563         }
27564     }
27565     ts.parseListTypeOption = parseListTypeOption;
27566     function getOptionName(option) {
27567         return option.name;
27568     }
27569     function createUnknownOptionError(unknownOption, diagnostics, createDiagnostics, unknownOptionErrorText) {
27570         var possibleOption = ts.getSpellingSuggestion(unknownOption, diagnostics.optionDeclarations, getOptionName);
27571         return possibleOption ?
27572             createDiagnostics(diagnostics.unknownDidYouMeanDiagnostic, unknownOptionErrorText || unknownOption, possibleOption.name) :
27573             createDiagnostics(diagnostics.unknownOptionDiagnostic, unknownOptionErrorText || unknownOption);
27574     }
27575     /*@internal*/
27576     function parseCommandLineWorker(diagnostics, commandLine, readFile) {
27577         var options = {};
27578         var watchOptions;
27579         var fileNames = [];
27580         var errors = [];
27581         parseStrings(commandLine);
27582         return {
27583             options: options,
27584             watchOptions: watchOptions,
27585             fileNames: fileNames,
27586             errors: errors
27587         };
27588         function parseStrings(args) {
27589             var i = 0;
27590             while (i < args.length) {
27591                 var s = args[i];
27592                 i++;
27593                 if (s.charCodeAt(0) === 64 /* at */) {
27594                     parseResponseFile(s.slice(1));
27595                 }
27596                 else if (s.charCodeAt(0) === 45 /* minus */) {
27597                     var inputOptionName = s.slice(s.charCodeAt(1) === 45 /* minus */ ? 2 : 1);
27598                     var opt = getOptionDeclarationFromName(diagnostics.getOptionsNameMap, inputOptionName, /*allowShort*/ true);
27599                     if (opt) {
27600                         i = parseOptionValue(args, i, diagnostics, opt, options, errors);
27601                     }
27602                     else {
27603                         var watchOpt = getOptionDeclarationFromName(watchOptionsDidYouMeanDiagnostics.getOptionsNameMap, inputOptionName, /*allowShort*/ true);
27604                         if (watchOpt) {
27605                             i = parseOptionValue(args, i, watchOptionsDidYouMeanDiagnostics, watchOpt, watchOptions || (watchOptions = {}), errors);
27606                         }
27607                         else {
27608                             errors.push(createUnknownOptionError(inputOptionName, diagnostics, ts.createCompilerDiagnostic, s));
27609                         }
27610                     }
27611                 }
27612                 else {
27613                     fileNames.push(s);
27614                 }
27615             }
27616         }
27617         function parseResponseFile(fileName) {
27618             var text = tryReadFile(fileName, readFile || (function (fileName) { return ts.sys.readFile(fileName); }));
27619             if (!ts.isString(text)) {
27620                 errors.push(text);
27621                 return;
27622             }
27623             var args = [];
27624             var pos = 0;
27625             while (true) {
27626                 while (pos < text.length && text.charCodeAt(pos) <= 32 /* space */)
27627                     pos++;
27628                 if (pos >= text.length)
27629                     break;
27630                 var start = pos;
27631                 if (text.charCodeAt(start) === 34 /* doubleQuote */) {
27632                     pos++;
27633                     while (pos < text.length && text.charCodeAt(pos) !== 34 /* doubleQuote */)
27634                         pos++;
27635                     if (pos < text.length) {
27636                         args.push(text.substring(start + 1, pos));
27637                         pos++;
27638                     }
27639                     else {
27640                         errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Unterminated_quoted_string_in_response_file_0, fileName));
27641                     }
27642                 }
27643                 else {
27644                     while (text.charCodeAt(pos) > 32 /* space */)
27645                         pos++;
27646                     args.push(text.substring(start, pos));
27647                 }
27648             }
27649             parseStrings(args);
27650         }
27651     }
27652     ts.parseCommandLineWorker = parseCommandLineWorker;
27653     function parseOptionValue(args, i, diagnostics, opt, options, errors) {
27654         if (opt.isTSConfigOnly) {
27655             var optValue = args[i];
27656             if (optValue === "null") {
27657                 options[opt.name] = undefined;
27658                 i++;
27659             }
27660             else if (opt.type === "boolean") {
27661                 if (optValue === "false") {
27662                     options[opt.name] = false;
27663                     i++;
27664                 }
27665                 else {
27666                     if (optValue === "true")
27667                         i++;
27668                     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));
27669                 }
27670             }
27671             else {
27672                 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));
27673                 if (optValue && !ts.startsWith(optValue, "-"))
27674                     i++;
27675             }
27676         }
27677         else {
27678             // Check to see if no argument was provided (e.g. "--locale" is the last command-line argument).
27679             if (!args[i] && opt.type !== "boolean") {
27680                 errors.push(ts.createCompilerDiagnostic(diagnostics.optionTypeMismatchDiagnostic, opt.name, getCompilerOptionValueTypeString(opt)));
27681             }
27682             if (args[i] !== "null") {
27683                 switch (opt.type) {
27684                     case "number":
27685                         options[opt.name] = parseInt(args[i]);
27686                         i++;
27687                         break;
27688                     case "boolean":
27689                         // boolean flag has optional value true, false, others
27690                         var optValue = args[i];
27691                         options[opt.name] = optValue !== "false";
27692                         // consume next argument as boolean flag value
27693                         if (optValue === "false" || optValue === "true") {
27694                             i++;
27695                         }
27696                         break;
27697                     case "string":
27698                         options[opt.name] = args[i] || "";
27699                         i++;
27700                         break;
27701                     case "list":
27702                         var result = parseListTypeOption(opt, args[i], errors);
27703                         options[opt.name] = result || [];
27704                         if (result) {
27705                             i++;
27706                         }
27707                         break;
27708                     // If not a primitive, the possible types are specified in what is effectively a map of options.
27709                     default:
27710                         options[opt.name] = parseCustomTypeOption(opt, args[i], errors);
27711                         i++;
27712                         break;
27713                 }
27714             }
27715             else {
27716                 options[opt.name] = undefined;
27717                 i++;
27718             }
27719         }
27720         return i;
27721     }
27722     /*@internal*/
27723     ts.compilerOptionsDidYouMeanDiagnostics = {
27724         getOptionsNameMap: getOptionsNameMap,
27725         optionDeclarations: ts.optionDeclarations,
27726         unknownOptionDiagnostic: ts.Diagnostics.Unknown_compiler_option_0,
27727         unknownDidYouMeanDiagnostic: ts.Diagnostics.Unknown_compiler_option_0_Did_you_mean_1,
27728         optionTypeMismatchDiagnostic: ts.Diagnostics.Compiler_option_0_expects_an_argument
27729     };
27730     function parseCommandLine(commandLine, readFile) {
27731         return parseCommandLineWorker(ts.compilerOptionsDidYouMeanDiagnostics, commandLine, readFile);
27732     }
27733     ts.parseCommandLine = parseCommandLine;
27734     /** @internal */
27735     function getOptionFromName(optionName, allowShort) {
27736         return getOptionDeclarationFromName(getOptionsNameMap, optionName, allowShort);
27737     }
27738     ts.getOptionFromName = getOptionFromName;
27739     function getOptionDeclarationFromName(getOptionNameMap, optionName, allowShort) {
27740         if (allowShort === void 0) { allowShort = false; }
27741         optionName = optionName.toLowerCase();
27742         var _a = getOptionNameMap(), optionsNameMap = _a.optionsNameMap, shortOptionNames = _a.shortOptionNames;
27743         // Try to translate short option names to their full equivalents.
27744         if (allowShort) {
27745             var short = shortOptionNames.get(optionName);
27746             if (short !== undefined) {
27747                 optionName = short;
27748             }
27749         }
27750         return optionsNameMap.get(optionName);
27751     }
27752     var buildOptionsNameMapCache;
27753     function getBuildOptionsNameMap() {
27754         return buildOptionsNameMapCache || (buildOptionsNameMapCache = createOptionNameMap(ts.buildOpts));
27755     }
27756     var buildOptionsDidYouMeanDiagnostics = {
27757         getOptionsNameMap: getBuildOptionsNameMap,
27758         optionDeclarations: ts.buildOpts,
27759         unknownOptionDiagnostic: ts.Diagnostics.Unknown_build_option_0,
27760         unknownDidYouMeanDiagnostic: ts.Diagnostics.Unknown_build_option_0_Did_you_mean_1,
27761         optionTypeMismatchDiagnostic: ts.Diagnostics.Build_option_0_requires_a_value_of_type_1
27762     };
27763     /*@internal*/
27764     function parseBuildCommand(args) {
27765         var _a = parseCommandLineWorker(buildOptionsDidYouMeanDiagnostics, args), options = _a.options, watchOptions = _a.watchOptions, projects = _a.fileNames, errors = _a.errors;
27766         var buildOptions = options;
27767         if (projects.length === 0) {
27768             // tsc -b invoked with no extra arguments; act as if invoked with "tsc -b ."
27769             projects.push(".");
27770         }
27771         // Nonsensical combinations
27772         if (buildOptions.clean && buildOptions.force) {
27773             errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Options_0_and_1_cannot_be_combined, "clean", "force"));
27774         }
27775         if (buildOptions.clean && buildOptions.verbose) {
27776             errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Options_0_and_1_cannot_be_combined, "clean", "verbose"));
27777         }
27778         if (buildOptions.clean && buildOptions.watch) {
27779             errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Options_0_and_1_cannot_be_combined, "clean", "watch"));
27780         }
27781         if (buildOptions.watch && buildOptions.dry) {
27782             errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Options_0_and_1_cannot_be_combined, "watch", "dry"));
27783         }
27784         return { buildOptions: buildOptions, watchOptions: watchOptions, projects: projects, errors: errors };
27785     }
27786     ts.parseBuildCommand = parseBuildCommand;
27787     /* @internal */
27788     function getDiagnosticText(_message) {
27789         var _args = [];
27790         for (var _i = 1; _i < arguments.length; _i++) {
27791             _args[_i - 1] = arguments[_i];
27792         }
27793         var diagnostic = ts.createCompilerDiagnostic.apply(undefined, arguments);
27794         return diagnostic.messageText;
27795     }
27796     ts.getDiagnosticText = getDiagnosticText;
27797     /**
27798      * Reads the config file, reports errors if any and exits if the config file cannot be found
27799      */
27800     function getParsedCommandLineOfConfigFile(configFileName, optionsToExtend, host, extendedConfigCache, watchOptionsToExtend, extraFileExtensions) {
27801         var configFileText = tryReadFile(configFileName, function (fileName) { return host.readFile(fileName); });
27802         if (!ts.isString(configFileText)) {
27803             host.onUnRecoverableConfigFileDiagnostic(configFileText);
27804             return undefined;
27805         }
27806         var result = ts.parseJsonText(configFileName, configFileText);
27807         var cwd = host.getCurrentDirectory();
27808         result.path = ts.toPath(configFileName, cwd, ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames));
27809         result.resolvedPath = result.path;
27810         result.originalFileName = result.fileName;
27811         return parseJsonSourceFileConfigFileContent(result, host, ts.getNormalizedAbsolutePath(ts.getDirectoryPath(configFileName), cwd), optionsToExtend, ts.getNormalizedAbsolutePath(configFileName, cwd), 
27812         /*resolutionStack*/ undefined, extraFileExtensions, extendedConfigCache, watchOptionsToExtend);
27813     }
27814     ts.getParsedCommandLineOfConfigFile = getParsedCommandLineOfConfigFile;
27815     /**
27816      * Read tsconfig.json file
27817      * @param fileName The path to the config file
27818      */
27819     function readConfigFile(fileName, readFile) {
27820         var textOrDiagnostic = tryReadFile(fileName, readFile);
27821         return ts.isString(textOrDiagnostic) ? parseConfigFileTextToJson(fileName, textOrDiagnostic) : { config: {}, error: textOrDiagnostic };
27822     }
27823     ts.readConfigFile = readConfigFile;
27824     /**
27825      * Parse the text of the tsconfig.json file
27826      * @param fileName The path to the config file
27827      * @param jsonText The text of the config file
27828      */
27829     function parseConfigFileTextToJson(fileName, jsonText) {
27830         var jsonSourceFile = ts.parseJsonText(fileName, jsonText);
27831         return {
27832             config: convertToObject(jsonSourceFile, jsonSourceFile.parseDiagnostics),
27833             error: jsonSourceFile.parseDiagnostics.length ? jsonSourceFile.parseDiagnostics[0] : undefined
27834         };
27835     }
27836     ts.parseConfigFileTextToJson = parseConfigFileTextToJson;
27837     /**
27838      * Read tsconfig.json file
27839      * @param fileName The path to the config file
27840      */
27841     function readJsonConfigFile(fileName, readFile) {
27842         var textOrDiagnostic = tryReadFile(fileName, readFile);
27843         return ts.isString(textOrDiagnostic) ? ts.parseJsonText(fileName, textOrDiagnostic) : { parseDiagnostics: [textOrDiagnostic] };
27844     }
27845     ts.readJsonConfigFile = readJsonConfigFile;
27846     /*@internal*/
27847     function tryReadFile(fileName, readFile) {
27848         var text;
27849         try {
27850             text = readFile(fileName);
27851         }
27852         catch (e) {
27853             return ts.createCompilerDiagnostic(ts.Diagnostics.Cannot_read_file_0_Colon_1, fileName, e.message);
27854         }
27855         return text === undefined ? ts.createCompilerDiagnostic(ts.Diagnostics.Cannot_read_file_0, fileName) : text;
27856     }
27857     ts.tryReadFile = tryReadFile;
27858     function commandLineOptionsToMap(options) {
27859         return ts.arrayToMap(options, getOptionName);
27860     }
27861     var typeAcquisitionDidYouMeanDiagnostics = {
27862         optionDeclarations: ts.typeAcquisitionDeclarations,
27863         unknownOptionDiagnostic: ts.Diagnostics.Unknown_type_acquisition_option_0,
27864         unknownDidYouMeanDiagnostic: ts.Diagnostics.Unknown_type_acquisition_option_0_Did_you_mean_1,
27865     };
27866     var watchOptionsNameMapCache;
27867     function getWatchOptionsNameMap() {
27868         return watchOptionsNameMapCache || (watchOptionsNameMapCache = createOptionNameMap(ts.optionsForWatch));
27869     }
27870     var watchOptionsDidYouMeanDiagnostics = {
27871         getOptionsNameMap: getWatchOptionsNameMap,
27872         optionDeclarations: ts.optionsForWatch,
27873         unknownOptionDiagnostic: ts.Diagnostics.Unknown_watch_option_0,
27874         unknownDidYouMeanDiagnostic: ts.Diagnostics.Unknown_watch_option_0_Did_you_mean_1,
27875         optionTypeMismatchDiagnostic: ts.Diagnostics.Watch_option_0_requires_a_value_of_type_1
27876     };
27877     var commandLineCompilerOptionsMapCache;
27878     function getCommandLineCompilerOptionsMap() {
27879         return commandLineCompilerOptionsMapCache || (commandLineCompilerOptionsMapCache = commandLineOptionsToMap(ts.optionDeclarations));
27880     }
27881     var commandLineWatchOptionsMapCache;
27882     function getCommandLineWatchOptionsMap() {
27883         return commandLineWatchOptionsMapCache || (commandLineWatchOptionsMapCache = commandLineOptionsToMap(ts.optionsForWatch));
27884     }
27885     var commandLineTypeAcquisitionMapCache;
27886     function getCommandLineTypeAcquisitionMap() {
27887         return commandLineTypeAcquisitionMapCache || (commandLineTypeAcquisitionMapCache = commandLineOptionsToMap(ts.typeAcquisitionDeclarations));
27888     }
27889     var _tsconfigRootOptions;
27890     function getTsconfigRootOptionsMap() {
27891         if (_tsconfigRootOptions === undefined) {
27892             _tsconfigRootOptions = {
27893                 name: undefined,
27894                 type: "object",
27895                 elementOptions: commandLineOptionsToMap([
27896                     {
27897                         name: "compilerOptions",
27898                         type: "object",
27899                         elementOptions: getCommandLineCompilerOptionsMap(),
27900                         extraKeyDiagnostics: ts.compilerOptionsDidYouMeanDiagnostics,
27901                     },
27902                     {
27903                         name: "watchOptions",
27904                         type: "object",
27905                         elementOptions: getCommandLineWatchOptionsMap(),
27906                         extraKeyDiagnostics: watchOptionsDidYouMeanDiagnostics,
27907                     },
27908                     {
27909                         name: "typingOptions",
27910                         type: "object",
27911                         elementOptions: getCommandLineTypeAcquisitionMap(),
27912                         extraKeyDiagnostics: typeAcquisitionDidYouMeanDiagnostics,
27913                     },
27914                     {
27915                         name: "typeAcquisition",
27916                         type: "object",
27917                         elementOptions: getCommandLineTypeAcquisitionMap(),
27918                         extraKeyDiagnostics: typeAcquisitionDidYouMeanDiagnostics
27919                     },
27920                     {
27921                         name: "extends",
27922                         type: "string"
27923                     },
27924                     {
27925                         name: "references",
27926                         type: "list",
27927                         element: {
27928                             name: "references",
27929                             type: "object"
27930                         }
27931                     },
27932                     {
27933                         name: "files",
27934                         type: "list",
27935                         element: {
27936                             name: "files",
27937                             type: "string"
27938                         }
27939                     },
27940                     {
27941                         name: "include",
27942                         type: "list",
27943                         element: {
27944                             name: "include",
27945                             type: "string"
27946                         }
27947                     },
27948                     {
27949                         name: "exclude",
27950                         type: "list",
27951                         element: {
27952                             name: "exclude",
27953                             type: "string"
27954                         }
27955                     },
27956                     ts.compileOnSaveCommandLineOption
27957                 ])
27958             };
27959         }
27960         return _tsconfigRootOptions;
27961     }
27962     /**
27963      * Convert the json syntax tree into the json value
27964      */
27965     function convertToObject(sourceFile, errors) {
27966         return convertToObjectWorker(sourceFile, errors, /*returnValue*/ true, /*knownRootOptions*/ undefined, /*jsonConversionNotifier*/ undefined);
27967     }
27968     ts.convertToObject = convertToObject;
27969     /**
27970      * Convert the json syntax tree into the json value and report errors
27971      * This returns the json value (apart from checking errors) only if returnValue provided is true.
27972      * Otherwise it just checks the errors and returns undefined
27973      */
27974     /*@internal*/
27975     function convertToObjectWorker(sourceFile, errors, returnValue, knownRootOptions, jsonConversionNotifier) {
27976         if (!sourceFile.statements.length) {
27977             return returnValue ? {} : undefined;
27978         }
27979         return convertPropertyValueToJson(sourceFile.statements[0].expression, knownRootOptions);
27980         function isRootOptionMap(knownOptions) {
27981             return knownRootOptions && knownRootOptions.elementOptions === knownOptions;
27982         }
27983         function convertObjectLiteralExpressionToJson(node, knownOptions, extraKeyDiagnostics, parentOption) {
27984             var result = returnValue ? {} : undefined;
27985             var _loop_3 = function (element) {
27986                 if (element.kind !== 281 /* PropertyAssignment */) {
27987                     errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, element, ts.Diagnostics.Property_assignment_expected));
27988                     return "continue";
27989                 }
27990                 if (element.questionToken) {
27991                     errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, element.questionToken, ts.Diagnostics.The_0_modifier_can_only_be_used_in_TypeScript_files, "?"));
27992                 }
27993                 if (!isDoubleQuotedString(element.name)) {
27994                     errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, element.name, ts.Diagnostics.String_literal_with_double_quotes_expected));
27995                 }
27996                 var textOfKey = ts.isComputedNonLiteralName(element.name) ? undefined : ts.getTextOfPropertyName(element.name);
27997                 var keyText = textOfKey && ts.unescapeLeadingUnderscores(textOfKey);
27998                 var option = keyText && knownOptions ? knownOptions.get(keyText) : undefined;
27999                 if (keyText && extraKeyDiagnostics && !option) {
28000                     if (knownOptions) {
28001                         errors.push(createUnknownOptionError(keyText, extraKeyDiagnostics, function (message, arg0, arg1) { return ts.createDiagnosticForNodeInSourceFile(sourceFile, element.name, message, arg0, arg1); }));
28002                     }
28003                     else {
28004                         errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, element.name, extraKeyDiagnostics.unknownOptionDiagnostic, keyText));
28005                     }
28006                 }
28007                 var value = convertPropertyValueToJson(element.initializer, option);
28008                 if (typeof keyText !== "undefined") {
28009                     if (returnValue) {
28010                         result[keyText] = value;
28011                     }
28012                     // Notify key value set, if user asked for it
28013                     if (jsonConversionNotifier &&
28014                         // Current callbacks are only on known parent option or if we are setting values in the root
28015                         (parentOption || isRootOptionMap(knownOptions))) {
28016                         var isValidOptionValue = isCompilerOptionsValue(option, value);
28017                         if (parentOption) {
28018                             if (isValidOptionValue) {
28019                                 // Notify option set in the parent if its a valid option value
28020                                 jsonConversionNotifier.onSetValidOptionKeyValueInParent(parentOption, option, value);
28021                             }
28022                         }
28023                         else if (isRootOptionMap(knownOptions)) {
28024                             if (isValidOptionValue) {
28025                                 // Notify about the valid root key value being set
28026                                 jsonConversionNotifier.onSetValidOptionKeyValueInRoot(keyText, element.name, value, element.initializer);
28027                             }
28028                             else if (!option) {
28029                                 // Notify about the unknown root key value being set
28030                                 jsonConversionNotifier.onSetUnknownOptionKeyValueInRoot(keyText, element.name, value, element.initializer);
28031                             }
28032                         }
28033                     }
28034                 }
28035             };
28036             for (var _i = 0, _a = node.properties; _i < _a.length; _i++) {
28037                 var element = _a[_i];
28038                 _loop_3(element);
28039             }
28040             return result;
28041         }
28042         function convertArrayLiteralExpressionToJson(elements, elementOption) {
28043             if (!returnValue) {
28044                 return elements.forEach(function (element) { return convertPropertyValueToJson(element, elementOption); });
28045             }
28046             // Filter out invalid values
28047             return ts.filter(elements.map(function (element) { return convertPropertyValueToJson(element, elementOption); }), function (v) { return v !== undefined; });
28048         }
28049         function convertPropertyValueToJson(valueExpression, option) {
28050             switch (valueExpression.kind) {
28051                 case 106 /* TrueKeyword */:
28052                     reportInvalidOptionValue(option && option.type !== "boolean");
28053                     return true;
28054                 case 91 /* FalseKeyword */:
28055                     reportInvalidOptionValue(option && option.type !== "boolean");
28056                     return false;
28057                 case 100 /* NullKeyword */:
28058                     reportInvalidOptionValue(option && option.name === "extends"); // "extends" is the only option we don't allow null/undefined for
28059                     return null; // eslint-disable-line no-null/no-null
28060                 case 10 /* StringLiteral */:
28061                     if (!isDoubleQuotedString(valueExpression)) {
28062                         errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, valueExpression, ts.Diagnostics.String_literal_with_double_quotes_expected));
28063                     }
28064                     reportInvalidOptionValue(option && (ts.isString(option.type) && option.type !== "string"));
28065                     var text = valueExpression.text;
28066                     if (option && !ts.isString(option.type)) {
28067                         var customOption = option;
28068                         // Validate custom option type
28069                         if (!customOption.type.has(text.toLowerCase())) {
28070                             errors.push(createDiagnosticForInvalidCustomType(customOption, function (message, arg0, arg1) { return ts.createDiagnosticForNodeInSourceFile(sourceFile, valueExpression, message, arg0, arg1); }));
28071                         }
28072                     }
28073                     return text;
28074                 case 8 /* NumericLiteral */:
28075                     reportInvalidOptionValue(option && option.type !== "number");
28076                     return Number(valueExpression.text);
28077                 case 207 /* PrefixUnaryExpression */:
28078                     if (valueExpression.operator !== 40 /* MinusToken */ || valueExpression.operand.kind !== 8 /* NumericLiteral */) {
28079                         break; // not valid JSON syntax
28080                     }
28081                     reportInvalidOptionValue(option && option.type !== "number");
28082                     return -Number(valueExpression.operand.text);
28083                 case 193 /* ObjectLiteralExpression */:
28084                     reportInvalidOptionValue(option && option.type !== "object");
28085                     var objectLiteralExpression = valueExpression;
28086                     // Currently having element option declaration in the tsconfig with type "object"
28087                     // determines if it needs onSetValidOptionKeyValueInParent callback or not
28088                     // At moment there are only "compilerOptions", "typeAcquisition" and "typingOptions"
28089                     // that satifies it and need it to modify options set in them (for normalizing file paths)
28090                     // vs what we set in the json
28091                     // If need arises, we can modify this interface and callbacks as needed
28092                     if (option) {
28093                         var _a = option, elementOptions = _a.elementOptions, extraKeyDiagnostics = _a.extraKeyDiagnostics, optionName = _a.name;
28094                         return convertObjectLiteralExpressionToJson(objectLiteralExpression, elementOptions, extraKeyDiagnostics, optionName);
28095                     }
28096                     else {
28097                         return convertObjectLiteralExpressionToJson(objectLiteralExpression, /* knownOptions*/ undefined, 
28098                         /*extraKeyDiagnosticMessage */ undefined, /*parentOption*/ undefined);
28099                     }
28100                 case 192 /* ArrayLiteralExpression */:
28101                     reportInvalidOptionValue(option && option.type !== "list");
28102                     return convertArrayLiteralExpressionToJson(valueExpression.elements, option && option.element);
28103             }
28104             // Not in expected format
28105             if (option) {
28106                 reportInvalidOptionValue(/*isError*/ true);
28107             }
28108             else {
28109                 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));
28110             }
28111             return undefined;
28112             function reportInvalidOptionValue(isError) {
28113                 if (isError) {
28114                     errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, valueExpression, ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, option.name, getCompilerOptionValueTypeString(option)));
28115                 }
28116             }
28117         }
28118         function isDoubleQuotedString(node) {
28119             return ts.isStringLiteral(node) && ts.isStringDoubleQuoted(node, sourceFile);
28120         }
28121     }
28122     ts.convertToObjectWorker = convertToObjectWorker;
28123     function getCompilerOptionValueTypeString(option) {
28124         return option.type === "list" ?
28125             "Array" :
28126             ts.isString(option.type) ? option.type : "string";
28127     }
28128     function isCompilerOptionsValue(option, value) {
28129         if (option) {
28130             if (isNullOrUndefined(value))
28131                 return true; // All options are undefinable/nullable
28132             if (option.type === "list") {
28133                 return ts.isArray(value);
28134             }
28135             var expectedType = ts.isString(option.type) ? option.type : "string";
28136             return typeof value === expectedType;
28137         }
28138         return false;
28139     }
28140     /**
28141      * Generate an uncommented, complete tsconfig for use with "--showConfig"
28142      * @param configParseResult options to be generated into tsconfig.json
28143      * @param configFileName name of the parsed config file - output paths will be generated relative to this
28144      * @param host provides current directory and case sensitivity services
28145      */
28146     /** @internal */
28147     function convertToTSConfig(configParseResult, configFileName, host) {
28148         var getCanonicalFileName = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames);
28149         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); });
28150         var optionMap = serializeCompilerOptions(configParseResult.options, { configFilePath: ts.getNormalizedAbsolutePath(configFileName, host.getCurrentDirectory()), useCaseSensitiveFileNames: host.useCaseSensitiveFileNames });
28151         var watchOptionMap = configParseResult.watchOptions && serializeWatchOptions(configParseResult.watchOptions);
28152         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 ? {
28153             include: filterSameAsDefaultInclude(configParseResult.configFileSpecs.validatedIncludeSpecs),
28154             exclude: configParseResult.configFileSpecs.validatedExcludeSpecs
28155         } : {})), { compileOnSave: !!configParseResult.compileOnSave ? true : undefined });
28156         return config;
28157     }
28158     ts.convertToTSConfig = convertToTSConfig;
28159     function optionMapToObject(optionMap) {
28160         return __assign({}, ts.arrayFrom(optionMap.entries()).reduce(function (prev, cur) {
28161             var _a;
28162             return (__assign(__assign({}, prev), (_a = {}, _a[cur[0]] = cur[1], _a)));
28163         }, {}));
28164     }
28165     function filterSameAsDefaultInclude(specs) {
28166         if (!ts.length(specs))
28167             return undefined;
28168         if (ts.length(specs) !== 1)
28169             return specs;
28170         if (specs[0] === "**/*")
28171             return undefined;
28172         return specs;
28173     }
28174     function matchesSpecs(path, includeSpecs, excludeSpecs, host) {
28175         if (!includeSpecs)
28176             return function (_) { return true; };
28177         var patterns = ts.getFileMatcherPatterns(path, excludeSpecs, includeSpecs, host.useCaseSensitiveFileNames, host.getCurrentDirectory());
28178         var excludeRe = patterns.excludePattern && ts.getRegexFromPattern(patterns.excludePattern, host.useCaseSensitiveFileNames);
28179         var includeRe = patterns.includeFilePattern && ts.getRegexFromPattern(patterns.includeFilePattern, host.useCaseSensitiveFileNames);
28180         if (includeRe) {
28181             if (excludeRe) {
28182                 return function (path) { return !(includeRe.test(path) && !excludeRe.test(path)); };
28183             }
28184             return function (path) { return !includeRe.test(path); };
28185         }
28186         if (excludeRe) {
28187             return function (path) { return excludeRe.test(path); };
28188         }
28189         return function (_) { return true; };
28190     }
28191     function getCustomTypeMapOfCommandLineOption(optionDefinition) {
28192         if (optionDefinition.type === "string" || optionDefinition.type === "number" || optionDefinition.type === "boolean" || optionDefinition.type === "object") {
28193             // this is of a type CommandLineOptionOfPrimitiveType
28194             return undefined;
28195         }
28196         else if (optionDefinition.type === "list") {
28197             return getCustomTypeMapOfCommandLineOption(optionDefinition.element);
28198         }
28199         else {
28200             return optionDefinition.type;
28201         }
28202     }
28203     function getNameOfCompilerOptionValue(value, customTypeMap) {
28204         // There is a typeMap associated with this command-line option so use it to map value back to its name
28205         return ts.forEachEntry(customTypeMap, function (mapValue, key) {
28206             if (mapValue === value) {
28207                 return key;
28208             }
28209         });
28210     }
28211     function serializeCompilerOptions(options, pathOptions) {
28212         return serializeOptionBaseObject(options, getOptionsNameMap(), pathOptions);
28213     }
28214     function serializeWatchOptions(options) {
28215         return serializeOptionBaseObject(options, getWatchOptionsNameMap());
28216     }
28217     function serializeOptionBaseObject(options, _a, pathOptions) {
28218         var optionsNameMap = _a.optionsNameMap;
28219         var result = ts.createMap();
28220         var getCanonicalFileName = pathOptions && ts.createGetCanonicalFileName(pathOptions.useCaseSensitiveFileNames);
28221         var _loop_4 = function (name) {
28222             if (ts.hasProperty(options, name)) {
28223                 // tsconfig only options cannot be specified via command line,
28224                 // so we can assume that only types that can appear here string | number | boolean
28225                 if (optionsNameMap.has(name) && optionsNameMap.get(name).category === ts.Diagnostics.Command_line_Options) {
28226                     return "continue";
28227                 }
28228                 var value = options[name];
28229                 var optionDefinition = optionsNameMap.get(name.toLowerCase());
28230                 if (optionDefinition) {
28231                     var customTypeMap_1 = getCustomTypeMapOfCommandLineOption(optionDefinition);
28232                     if (!customTypeMap_1) {
28233                         // There is no map associated with this compiler option then use the value as-is
28234                         // This is the case if the value is expect to be string, number, boolean or list of string
28235                         if (pathOptions && optionDefinition.isFilePath) {
28236                             result.set(name, ts.getRelativePathFromFile(pathOptions.configFilePath, ts.getNormalizedAbsolutePath(value, ts.getDirectoryPath(pathOptions.configFilePath)), getCanonicalFileName));
28237                         }
28238                         else {
28239                             result.set(name, value);
28240                         }
28241                     }
28242                     else {
28243                         if (optionDefinition.type === "list") {
28244                             result.set(name, value.map(function (element) { return getNameOfCompilerOptionValue(element, customTypeMap_1); })); // TODO: GH#18217
28245                         }
28246                         else {
28247                             // There is a typeMap associated with this command-line option so use it to map value back to its name
28248                             result.set(name, getNameOfCompilerOptionValue(value, customTypeMap_1));
28249                         }
28250                     }
28251                 }
28252             }
28253         };
28254         for (var name in options) {
28255             _loop_4(name);
28256         }
28257         return result;
28258     }
28259     /**
28260      * Generate tsconfig configuration when running command line "--init"
28261      * @param options commandlineOptions to be generated into tsconfig.json
28262      * @param fileNames array of filenames to be generated into tsconfig.json
28263      */
28264     /* @internal */
28265     function generateTSConfig(options, fileNames, newLine) {
28266         var compilerOptions = ts.extend(options, ts.defaultInitCompilerOptions);
28267         var compilerOptionsMap = serializeCompilerOptions(compilerOptions);
28268         return writeConfigurations();
28269         function getDefaultValueForOption(option) {
28270             switch (option.type) {
28271                 case "number":
28272                     return 1;
28273                 case "boolean":
28274                     return true;
28275                 case "string":
28276                     return option.isFilePath ? "./" : "";
28277                 case "list":
28278                     return [];
28279                 case "object":
28280                     return {};
28281                 default:
28282                     var iterResult = option.type.keys().next();
28283                     if (!iterResult.done)
28284                         return iterResult.value;
28285                     return ts.Debug.fail("Expected 'option.type' to have entries.");
28286             }
28287         }
28288         function makePadding(paddingLength) {
28289             return Array(paddingLength + 1).join(" ");
28290         }
28291         function isAllowedOption(_a) {
28292             var category = _a.category, name = _a.name;
28293             // Skip options which do not have a category or have category `Command_line_Options`
28294             // Exclude all possible `Advanced_Options` in tsconfig.json which were NOT defined in command line
28295             return category !== undefined
28296                 && category !== ts.Diagnostics.Command_line_Options
28297                 && (category !== ts.Diagnostics.Advanced_Options || compilerOptionsMap.has(name));
28298         }
28299         function writeConfigurations() {
28300             // Filter applicable options to place in the file
28301             var categorizedOptions = ts.createMultiMap();
28302             for (var _i = 0, optionDeclarations_1 = ts.optionDeclarations; _i < optionDeclarations_1.length; _i++) {
28303                 var option = optionDeclarations_1[_i];
28304                 var category = option.category;
28305                 if (isAllowedOption(option)) {
28306                     categorizedOptions.add(ts.getLocaleSpecificMessage(category), option);
28307                 }
28308             }
28309             // Serialize all options and their descriptions
28310             var marginLength = 0;
28311             var seenKnownKeys = 0;
28312             var entries = [];
28313             categorizedOptions.forEach(function (options, category) {
28314                 if (entries.length !== 0) {
28315                     entries.push({ value: "" });
28316                 }
28317                 entries.push({ value: "/* " + category + " */" });
28318                 for (var _i = 0, options_1 = options; _i < options_1.length; _i++) {
28319                     var option = options_1[_i];
28320                     var optionName = void 0;
28321                     if (compilerOptionsMap.has(option.name)) {
28322                         optionName = "\"" + option.name + "\": " + JSON.stringify(compilerOptionsMap.get(option.name)) + ((seenKnownKeys += 1) === compilerOptionsMap.size ? "" : ",");
28323                     }
28324                     else {
28325                         optionName = "// \"" + option.name + "\": " + JSON.stringify(getDefaultValueForOption(option)) + ",";
28326                     }
28327                     entries.push({
28328                         value: optionName,
28329                         description: "/* " + (option.description && ts.getLocaleSpecificMessage(option.description) || option.name) + " */"
28330                     });
28331                     marginLength = Math.max(optionName.length, marginLength);
28332                 }
28333             });
28334             // Write the output
28335             var tab = makePadding(2);
28336             var result = [];
28337             result.push("{");
28338             result.push(tab + "\"compilerOptions\": {");
28339             result.push("" + tab + tab + "/* " + ts.getLocaleSpecificMessage(ts.Diagnostics.Visit_https_Colon_Slash_Slashaka_ms_Slashtsconfig_json_to_read_more_about_this_file) + " */");
28340             result.push("");
28341             // Print out each row, aligning all the descriptions on the same column.
28342             for (var _a = 0, entries_3 = entries; _a < entries_3.length; _a++) {
28343                 var entry = entries_3[_a];
28344                 var value = entry.value, _b = entry.description, description = _b === void 0 ? "" : _b;
28345                 result.push(value && "" + tab + tab + value + (description && (makePadding(marginLength - value.length + 2) + description)));
28346             }
28347             if (fileNames.length) {
28348                 result.push(tab + "},");
28349                 result.push(tab + "\"files\": [");
28350                 for (var i = 0; i < fileNames.length; i++) {
28351                     result.push("" + tab + tab + JSON.stringify(fileNames[i]) + (i === fileNames.length - 1 ? "" : ","));
28352                 }
28353                 result.push(tab + "]");
28354             }
28355             else {
28356                 result.push(tab + "}");
28357             }
28358             result.push("}");
28359             return result.join(newLine) + newLine;
28360         }
28361     }
28362     ts.generateTSConfig = generateTSConfig;
28363     /* @internal */
28364     function convertToOptionsWithAbsolutePaths(options, toAbsolutePath) {
28365         var result = {};
28366         var optionsNameMap = getOptionsNameMap().optionsNameMap;
28367         for (var name in options) {
28368             if (ts.hasProperty(options, name)) {
28369                 result[name] = convertToOptionValueWithAbsolutePaths(optionsNameMap.get(name.toLowerCase()), options[name], toAbsolutePath);
28370             }
28371         }
28372         if (result.configFilePath) {
28373             result.configFilePath = toAbsolutePath(result.configFilePath);
28374         }
28375         return result;
28376     }
28377     ts.convertToOptionsWithAbsolutePaths = convertToOptionsWithAbsolutePaths;
28378     function convertToOptionValueWithAbsolutePaths(option, value, toAbsolutePath) {
28379         if (option && !isNullOrUndefined(value)) {
28380             if (option.type === "list") {
28381                 var values = value;
28382                 if (option.element.isFilePath && values.length) {
28383                     return values.map(toAbsolutePath);
28384                 }
28385             }
28386             else if (option.isFilePath) {
28387                 return toAbsolutePath(value);
28388             }
28389         }
28390         return value;
28391     }
28392     /**
28393      * Parse the contents of a config file (tsconfig.json).
28394      * @param json The contents of the config file to parse
28395      * @param host Instance of ParseConfigHost used to enumerate files in folder.
28396      * @param basePath A root directory to resolve relative path entries in the config
28397      *    file to. e.g. outDir
28398      */
28399     function parseJsonConfigFileContent(json, host, basePath, existingOptions, configFileName, resolutionStack, extraFileExtensions, extendedConfigCache, existingWatchOptions) {
28400         return parseJsonConfigFileContentWorker(json, /*sourceFile*/ undefined, host, basePath, existingOptions, existingWatchOptions, configFileName, resolutionStack, extraFileExtensions, extendedConfigCache);
28401     }
28402     ts.parseJsonConfigFileContent = parseJsonConfigFileContent;
28403     /**
28404      * Parse the contents of a config file (tsconfig.json).
28405      * @param jsonNode The contents of the config file to parse
28406      * @param host Instance of ParseConfigHost used to enumerate files in folder.
28407      * @param basePath A root directory to resolve relative path entries in the config
28408      *    file to. e.g. outDir
28409      */
28410     function parseJsonSourceFileConfigFileContent(sourceFile, host, basePath, existingOptions, configFileName, resolutionStack, extraFileExtensions, extendedConfigCache, existingWatchOptions) {
28411         return parseJsonConfigFileContentWorker(/*json*/ undefined, sourceFile, host, basePath, existingOptions, existingWatchOptions, configFileName, resolutionStack, extraFileExtensions, extendedConfigCache);
28412     }
28413     ts.parseJsonSourceFileConfigFileContent = parseJsonSourceFileConfigFileContent;
28414     /*@internal*/
28415     function setConfigFileInOptions(options, configFile) {
28416         if (configFile) {
28417             Object.defineProperty(options, "configFile", { enumerable: false, writable: false, value: configFile });
28418         }
28419     }
28420     ts.setConfigFileInOptions = setConfigFileInOptions;
28421     function isNullOrUndefined(x) {
28422         return x === undefined || x === null; // eslint-disable-line no-null/no-null
28423     }
28424     function directoryOfCombinedPath(fileName, basePath) {
28425         // Use the `getNormalizedAbsolutePath` function to avoid canonicalizing the path, as it must remain noncanonical
28426         // until consistent casing errors are reported
28427         return ts.getDirectoryPath(ts.getNormalizedAbsolutePath(fileName, basePath));
28428     }
28429     /**
28430      * Parse the contents of a config file from json or json source file (tsconfig.json).
28431      * @param json The contents of the config file to parse
28432      * @param sourceFile sourceFile corresponding to the Json
28433      * @param host Instance of ParseConfigHost used to enumerate files in folder.
28434      * @param basePath A root directory to resolve relative path entries in the config
28435      *    file to. e.g. outDir
28436      * @param resolutionStack Only present for backwards-compatibility. Should be empty.
28437      */
28438     function parseJsonConfigFileContentWorker(json, sourceFile, host, basePath, existingOptions, existingWatchOptions, configFileName, resolutionStack, extraFileExtensions, extendedConfigCache) {
28439         if (existingOptions === void 0) { existingOptions = {}; }
28440         if (resolutionStack === void 0) { resolutionStack = []; }
28441         if (extraFileExtensions === void 0) { extraFileExtensions = []; }
28442         ts.Debug.assert((json === undefined && sourceFile !== undefined) || (json !== undefined && sourceFile === undefined));
28443         var errors = [];
28444         var parsedConfig = parseConfig(json, sourceFile, host, basePath, configFileName, resolutionStack, errors, extendedConfigCache);
28445         var raw = parsedConfig.raw;
28446         var options = ts.extend(existingOptions, parsedConfig.options || {});
28447         var watchOptions = existingWatchOptions && parsedConfig.watchOptions ?
28448             ts.extend(existingWatchOptions, parsedConfig.watchOptions) :
28449             parsedConfig.watchOptions || existingWatchOptions;
28450         options.configFilePath = configFileName && ts.normalizeSlashes(configFileName);
28451         setConfigFileInOptions(options, sourceFile);
28452         var projectReferences;
28453         var _a = getFileNames(), fileNames = _a.fileNames, wildcardDirectories = _a.wildcardDirectories, spec = _a.spec;
28454         return {
28455             options: options,
28456             watchOptions: watchOptions,
28457             fileNames: fileNames,
28458             projectReferences: projectReferences,
28459             typeAcquisition: parsedConfig.typeAcquisition || getDefaultTypeAcquisition(),
28460             raw: raw,
28461             errors: errors,
28462             wildcardDirectories: wildcardDirectories,
28463             compileOnSave: !!raw.compileOnSave,
28464             configFileSpecs: spec
28465         };
28466         function getFileNames() {
28467             var filesSpecs;
28468             if (ts.hasProperty(raw, "files") && !isNullOrUndefined(raw.files)) {
28469                 if (ts.isArray(raw.files)) {
28470                     filesSpecs = raw.files;
28471                     var hasReferences = ts.hasProperty(raw, "references") && !isNullOrUndefined(raw.references);
28472                     var hasZeroOrNoReferences = !hasReferences || raw.references.length === 0;
28473                     var hasExtends = ts.hasProperty(raw, "extends");
28474                     if (filesSpecs.length === 0 && hasZeroOrNoReferences && !hasExtends) {
28475                         if (sourceFile) {
28476                             var fileName = configFileName || "tsconfig.json";
28477                             var diagnosticMessage = ts.Diagnostics.The_files_list_in_config_file_0_is_empty;
28478                             var nodeValue = ts.firstDefined(ts.getTsConfigPropArray(sourceFile, "files"), function (property) { return property.initializer; });
28479                             var error = nodeValue
28480                                 ? ts.createDiagnosticForNodeInSourceFile(sourceFile, nodeValue, diagnosticMessage, fileName)
28481                                 : ts.createCompilerDiagnostic(diagnosticMessage, fileName);
28482                             errors.push(error);
28483                         }
28484                         else {
28485                             createCompilerDiagnosticOnlyIfJson(ts.Diagnostics.The_files_list_in_config_file_0_is_empty, configFileName || "tsconfig.json");
28486                         }
28487                     }
28488                 }
28489                 else {
28490                     createCompilerDiagnosticOnlyIfJson(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "files", "Array");
28491                 }
28492             }
28493             var includeSpecs;
28494             if (ts.hasProperty(raw, "include") && !isNullOrUndefined(raw.include)) {
28495                 if (ts.isArray(raw.include)) {
28496                     includeSpecs = raw.include;
28497                 }
28498                 else {
28499                     createCompilerDiagnosticOnlyIfJson(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "include", "Array");
28500                 }
28501             }
28502             var excludeSpecs;
28503             if (ts.hasProperty(raw, "exclude") && !isNullOrUndefined(raw.exclude)) {
28504                 if (ts.isArray(raw.exclude)) {
28505                     excludeSpecs = raw.exclude;
28506                 }
28507                 else {
28508                     createCompilerDiagnosticOnlyIfJson(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "exclude", "Array");
28509                 }
28510             }
28511             else if (raw.compilerOptions) {
28512                 var outDir = raw.compilerOptions.outDir;
28513                 var declarationDir = raw.compilerOptions.declarationDir;
28514                 if (outDir || declarationDir) {
28515                     excludeSpecs = [outDir, declarationDir].filter(function (d) { return !!d; });
28516                 }
28517             }
28518             if (filesSpecs === undefined && includeSpecs === undefined) {
28519                 includeSpecs = ["**/*"];
28520             }
28521             var result = matchFileNames(filesSpecs, includeSpecs, excludeSpecs, configFileName ? directoryOfCombinedPath(configFileName, basePath) : basePath, options, host, errors, extraFileExtensions, sourceFile);
28522             if (shouldReportNoInputFiles(result, canJsonReportNoInutFiles(raw), resolutionStack)) {
28523                 errors.push(getErrorForNoInputFiles(result.spec, configFileName));
28524             }
28525             if (ts.hasProperty(raw, "references") && !isNullOrUndefined(raw.references)) {
28526                 if (ts.isArray(raw.references)) {
28527                     for (var _i = 0, _a = raw.references; _i < _a.length; _i++) {
28528                         var ref = _a[_i];
28529                         if (typeof ref.path !== "string") {
28530                             createCompilerDiagnosticOnlyIfJson(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "reference.path", "string");
28531                         }
28532                         else {
28533                             (projectReferences || (projectReferences = [])).push({
28534                                 path: ts.getNormalizedAbsolutePath(ref.path, basePath),
28535                                 originalPath: ref.path,
28536                                 prepend: ref.prepend,
28537                                 circular: ref.circular
28538                             });
28539                         }
28540                     }
28541                 }
28542                 else {
28543                     createCompilerDiagnosticOnlyIfJson(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "references", "Array");
28544                 }
28545             }
28546             return result;
28547         }
28548         function createCompilerDiagnosticOnlyIfJson(message, arg0, arg1) {
28549             if (!sourceFile) {
28550                 errors.push(ts.createCompilerDiagnostic(message, arg0, arg1));
28551             }
28552         }
28553     }
28554     function isErrorNoInputFiles(error) {
28555         return error.code === ts.Diagnostics.No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2.code;
28556     }
28557     function getErrorForNoInputFiles(_a, configFileName) {
28558         var includeSpecs = _a.includeSpecs, excludeSpecs = _a.excludeSpecs;
28559         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 || []));
28560     }
28561     function shouldReportNoInputFiles(result, canJsonReportNoInutFiles, resolutionStack) {
28562         return result.fileNames.length === 0 && canJsonReportNoInutFiles && (!resolutionStack || resolutionStack.length === 0);
28563     }
28564     /*@internal*/
28565     function canJsonReportNoInutFiles(raw) {
28566         return !ts.hasProperty(raw, "files") && !ts.hasProperty(raw, "references");
28567     }
28568     ts.canJsonReportNoInutFiles = canJsonReportNoInutFiles;
28569     /*@internal*/
28570     function updateErrorForNoInputFiles(result, configFileName, configFileSpecs, configParseDiagnostics, canJsonReportNoInutFiles) {
28571         var existingErrors = configParseDiagnostics.length;
28572         if (shouldReportNoInputFiles(result, canJsonReportNoInutFiles)) {
28573             configParseDiagnostics.push(getErrorForNoInputFiles(configFileSpecs, configFileName));
28574         }
28575         else {
28576             ts.filterMutate(configParseDiagnostics, function (error) { return !isErrorNoInputFiles(error); });
28577         }
28578         return existingErrors !== configParseDiagnostics.length;
28579     }
28580     ts.updateErrorForNoInputFiles = updateErrorForNoInputFiles;
28581     function isSuccessfulParsedTsconfig(value) {
28582         return !!value.options;
28583     }
28584     /**
28585      * This *just* extracts options/include/exclude/files out of a config file.
28586      * It does *not* resolve the included files.
28587      */
28588     function parseConfig(json, sourceFile, host, basePath, configFileName, resolutionStack, errors, extendedConfigCache) {
28589         basePath = ts.normalizeSlashes(basePath);
28590         var resolvedPath = ts.getNormalizedAbsolutePath(configFileName || "", basePath);
28591         if (resolutionStack.indexOf(resolvedPath) >= 0) {
28592             errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Circularity_detected_while_resolving_configuration_Colon_0, __spreadArrays(resolutionStack, [resolvedPath]).join(" -> ")));
28593             return { raw: json || convertToObject(sourceFile, errors) };
28594         }
28595         var ownConfig = json ?
28596             parseOwnConfigOfJson(json, host, basePath, configFileName, errors) :
28597             parseOwnConfigOfJsonSourceFile(sourceFile, host, basePath, configFileName, errors);
28598         if (ownConfig.extendedConfigPath) {
28599             // copy the resolution stack so it is never reused between branches in potential diamond-problem scenarios.
28600             resolutionStack = resolutionStack.concat([resolvedPath]);
28601             var extendedConfig = getExtendedConfig(sourceFile, ownConfig.extendedConfigPath, host, basePath, resolutionStack, errors, extendedConfigCache);
28602             if (extendedConfig && isSuccessfulParsedTsconfig(extendedConfig)) {
28603                 var baseRaw_1 = extendedConfig.raw;
28604                 var raw_1 = ownConfig.raw;
28605                 var setPropertyInRawIfNotUndefined = function (propertyName) {
28606                     var value = raw_1[propertyName] || baseRaw_1[propertyName];
28607                     if (value) {
28608                         raw_1[propertyName] = value;
28609                     }
28610                 };
28611                 setPropertyInRawIfNotUndefined("include");
28612                 setPropertyInRawIfNotUndefined("exclude");
28613                 setPropertyInRawIfNotUndefined("files");
28614                 if (raw_1.compileOnSave === undefined) {
28615                     raw_1.compileOnSave = baseRaw_1.compileOnSave;
28616                 }
28617                 ownConfig.options = ts.assign({}, extendedConfig.options, ownConfig.options);
28618                 ownConfig.watchOptions = ownConfig.watchOptions && extendedConfig.watchOptions ?
28619                     ts.assign({}, extendedConfig.watchOptions, ownConfig.watchOptions) :
28620                     ownConfig.watchOptions || extendedConfig.watchOptions;
28621                 // TODO extend type typeAcquisition
28622             }
28623         }
28624         return ownConfig;
28625     }
28626     function parseOwnConfigOfJson(json, host, basePath, configFileName, errors) {
28627         if (ts.hasProperty(json, "excludes")) {
28628             errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Unknown_option_excludes_Did_you_mean_exclude));
28629         }
28630         var options = convertCompilerOptionsFromJsonWorker(json.compilerOptions, basePath, errors, configFileName);
28631         // typingOptions has been deprecated and is only supported for backward compatibility purposes.
28632         // It should be removed in future releases - use typeAcquisition instead.
28633         var typeAcquisition = convertTypeAcquisitionFromJsonWorker(json.typeAcquisition || json.typingOptions, basePath, errors, configFileName);
28634         var watchOptions = convertWatchOptionsFromJsonWorker(json.watchOptions, basePath, errors);
28635         json.compileOnSave = convertCompileOnSaveOptionFromJson(json, basePath, errors);
28636         var extendedConfigPath;
28637         if (json.extends) {
28638             if (!ts.isString(json.extends)) {
28639                 errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "extends", "string"));
28640             }
28641             else {
28642                 var newBase = configFileName ? directoryOfCombinedPath(configFileName, basePath) : basePath;
28643                 extendedConfigPath = getExtendsConfigPath(json.extends, host, newBase, errors, ts.createCompilerDiagnostic);
28644             }
28645         }
28646         return { raw: json, options: options, watchOptions: watchOptions, typeAcquisition: typeAcquisition, extendedConfigPath: extendedConfigPath };
28647     }
28648     function parseOwnConfigOfJsonSourceFile(sourceFile, host, basePath, configFileName, errors) {
28649         var options = getDefaultCompilerOptions(configFileName);
28650         var typeAcquisition, typingOptionstypeAcquisition;
28651         var watchOptions;
28652         var extendedConfigPath;
28653         var optionsIterator = {
28654             onSetValidOptionKeyValueInParent: function (parentOption, option, value) {
28655                 var currentOption;
28656                 switch (parentOption) {
28657                     case "compilerOptions":
28658                         currentOption = options;
28659                         break;
28660                     case "watchOptions":
28661                         currentOption = (watchOptions || (watchOptions = {}));
28662                         break;
28663                     case "typeAcquisition":
28664                         currentOption = (typeAcquisition || (typeAcquisition = getDefaultTypeAcquisition(configFileName)));
28665                         break;
28666                     case "typingOptions":
28667                         currentOption = (typingOptionstypeAcquisition || (typingOptionstypeAcquisition = getDefaultTypeAcquisition(configFileName)));
28668                         break;
28669                     default:
28670                         ts.Debug.fail("Unknown option");
28671                 }
28672                 currentOption[option.name] = normalizeOptionValue(option, basePath, value);
28673             },
28674             onSetValidOptionKeyValueInRoot: function (key, _keyNode, value, valueNode) {
28675                 switch (key) {
28676                     case "extends":
28677                         var newBase = configFileName ? directoryOfCombinedPath(configFileName, basePath) : basePath;
28678                         extendedConfigPath = getExtendsConfigPath(value, host, newBase, errors, function (message, arg0) {
28679                             return ts.createDiagnosticForNodeInSourceFile(sourceFile, valueNode, message, arg0);
28680                         });
28681                         return;
28682                 }
28683             },
28684             onSetUnknownOptionKeyValueInRoot: function (key, keyNode, _value, _valueNode) {
28685                 if (key === "excludes") {
28686                     errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, keyNode, ts.Diagnostics.Unknown_option_excludes_Did_you_mean_exclude));
28687                 }
28688             }
28689         };
28690         var json = convertToObjectWorker(sourceFile, errors, /*returnValue*/ true, getTsconfigRootOptionsMap(), optionsIterator);
28691         if (!typeAcquisition) {
28692             if (typingOptionstypeAcquisition) {
28693                 typeAcquisition = (typingOptionstypeAcquisition.enableAutoDiscovery !== undefined) ?
28694                     {
28695                         enable: typingOptionstypeAcquisition.enableAutoDiscovery,
28696                         include: typingOptionstypeAcquisition.include,
28697                         exclude: typingOptionstypeAcquisition.exclude
28698                     } :
28699                     typingOptionstypeAcquisition;
28700             }
28701             else {
28702                 typeAcquisition = getDefaultTypeAcquisition(configFileName);
28703             }
28704         }
28705         return { raw: json, options: options, watchOptions: watchOptions, typeAcquisition: typeAcquisition, extendedConfigPath: extendedConfigPath };
28706     }
28707     function getExtendsConfigPath(extendedConfig, host, basePath, errors, createDiagnostic) {
28708         extendedConfig = ts.normalizeSlashes(extendedConfig);
28709         if (ts.isRootedDiskPath(extendedConfig) || ts.startsWith(extendedConfig, "./") || ts.startsWith(extendedConfig, "../")) {
28710             var extendedConfigPath = ts.getNormalizedAbsolutePath(extendedConfig, basePath);
28711             if (!host.fileExists(extendedConfigPath) && !ts.endsWith(extendedConfigPath, ".json" /* Json */)) {
28712                 extendedConfigPath = extendedConfigPath + ".json";
28713                 if (!host.fileExists(extendedConfigPath)) {
28714                     errors.push(createDiagnostic(ts.Diagnostics.File_0_not_found, extendedConfig));
28715                     return undefined;
28716                 }
28717             }
28718             return extendedConfigPath;
28719         }
28720         // If the path isn't a rooted or relative path, resolve like a module
28721         var resolved = ts.nodeModuleNameResolver(extendedConfig, ts.combinePaths(basePath, "tsconfig.json"), { moduleResolution: ts.ModuleResolutionKind.NodeJs }, host, /*cache*/ undefined, /*projectRefs*/ undefined, /*lookupConfig*/ true);
28722         if (resolved.resolvedModule) {
28723             return resolved.resolvedModule.resolvedFileName;
28724         }
28725         errors.push(createDiagnostic(ts.Diagnostics.File_0_not_found, extendedConfig));
28726         return undefined;
28727     }
28728     function getExtendedConfig(sourceFile, extendedConfigPath, host, basePath, resolutionStack, errors, extendedConfigCache) {
28729         var _a;
28730         var path = host.useCaseSensitiveFileNames ? extendedConfigPath : ts.toFileNameLowerCase(extendedConfigPath);
28731         var value;
28732         var extendedResult;
28733         var extendedConfig;
28734         if (extendedConfigCache && (value = extendedConfigCache.get(path))) {
28735             (extendedResult = value.extendedResult, extendedConfig = value.extendedConfig);
28736         }
28737         else {
28738             extendedResult = readJsonConfigFile(extendedConfigPath, function (path) { return host.readFile(path); });
28739             if (!extendedResult.parseDiagnostics.length) {
28740                 var extendedDirname = ts.getDirectoryPath(extendedConfigPath);
28741                 extendedConfig = parseConfig(/*json*/ undefined, extendedResult, host, extendedDirname, ts.getBaseFileName(extendedConfigPath), resolutionStack, errors, extendedConfigCache);
28742                 if (isSuccessfulParsedTsconfig(extendedConfig)) {
28743                     // Update the paths to reflect base path
28744                     var relativeDifference_1 = ts.convertToRelativePath(extendedDirname, basePath, ts.identity);
28745                     var updatePath_1 = function (path) { return ts.isRootedDiskPath(path) ? path : ts.combinePaths(relativeDifference_1, path); };
28746                     var mapPropertiesInRawIfNotUndefined = function (propertyName) {
28747                         if (raw_2[propertyName]) {
28748                             raw_2[propertyName] = ts.map(raw_2[propertyName], updatePath_1);
28749                         }
28750                     };
28751                     var raw_2 = extendedConfig.raw;
28752                     mapPropertiesInRawIfNotUndefined("include");
28753                     mapPropertiesInRawIfNotUndefined("exclude");
28754                     mapPropertiesInRawIfNotUndefined("files");
28755                 }
28756             }
28757             if (extendedConfigCache) {
28758                 extendedConfigCache.set(path, { extendedResult: extendedResult, extendedConfig: extendedConfig });
28759             }
28760         }
28761         if (sourceFile) {
28762             sourceFile.extendedSourceFiles = [extendedResult.fileName];
28763             if (extendedResult.extendedSourceFiles) {
28764                 (_a = sourceFile.extendedSourceFiles).push.apply(_a, extendedResult.extendedSourceFiles);
28765             }
28766         }
28767         if (extendedResult.parseDiagnostics.length) {
28768             errors.push.apply(errors, extendedResult.parseDiagnostics);
28769             return undefined;
28770         }
28771         return extendedConfig;
28772     }
28773     function convertCompileOnSaveOptionFromJson(jsonOption, basePath, errors) {
28774         if (!ts.hasProperty(jsonOption, ts.compileOnSaveCommandLineOption.name)) {
28775             return false;
28776         }
28777         var result = convertJsonOption(ts.compileOnSaveCommandLineOption, jsonOption.compileOnSave, basePath, errors);
28778         return typeof result === "boolean" && result;
28779     }
28780     function convertCompilerOptionsFromJson(jsonOptions, basePath, configFileName) {
28781         var errors = [];
28782         var options = convertCompilerOptionsFromJsonWorker(jsonOptions, basePath, errors, configFileName);
28783         return { options: options, errors: errors };
28784     }
28785     ts.convertCompilerOptionsFromJson = convertCompilerOptionsFromJson;
28786     function convertTypeAcquisitionFromJson(jsonOptions, basePath, configFileName) {
28787         var errors = [];
28788         var options = convertTypeAcquisitionFromJsonWorker(jsonOptions, basePath, errors, configFileName);
28789         return { options: options, errors: errors };
28790     }
28791     ts.convertTypeAcquisitionFromJson = convertTypeAcquisitionFromJson;
28792     function getDefaultCompilerOptions(configFileName) {
28793         var options = configFileName && ts.getBaseFileName(configFileName) === "jsconfig.json"
28794             ? { allowJs: true, maxNodeModuleJsDepth: 2, allowSyntheticDefaultImports: true, skipLibCheck: true, noEmit: true }
28795             : {};
28796         return options;
28797     }
28798     function convertCompilerOptionsFromJsonWorker(jsonOptions, basePath, errors, configFileName) {
28799         var options = getDefaultCompilerOptions(configFileName);
28800         convertOptionsFromJson(getCommandLineCompilerOptionsMap(), jsonOptions, basePath, options, ts.compilerOptionsDidYouMeanDiagnostics, errors);
28801         if (configFileName) {
28802             options.configFilePath = ts.normalizeSlashes(configFileName);
28803         }
28804         return options;
28805     }
28806     function getDefaultTypeAcquisition(configFileName) {
28807         return { enable: !!configFileName && ts.getBaseFileName(configFileName) === "jsconfig.json", include: [], exclude: [] };
28808     }
28809     function convertTypeAcquisitionFromJsonWorker(jsonOptions, basePath, errors, configFileName) {
28810         var options = getDefaultTypeAcquisition(configFileName);
28811         var typeAcquisition = convertEnableAutoDiscoveryToEnable(jsonOptions);
28812         convertOptionsFromJson(getCommandLineTypeAcquisitionMap(), typeAcquisition, basePath, options, typeAcquisitionDidYouMeanDiagnostics, errors);
28813         return options;
28814     }
28815     function convertWatchOptionsFromJsonWorker(jsonOptions, basePath, errors) {
28816         return convertOptionsFromJson(getCommandLineWatchOptionsMap(), jsonOptions, basePath, /*defaultOptions*/ undefined, watchOptionsDidYouMeanDiagnostics, errors);
28817     }
28818     function convertOptionsFromJson(optionsNameMap, jsonOptions, basePath, defaultOptions, diagnostics, errors) {
28819         if (!jsonOptions) {
28820             return;
28821         }
28822         for (var id in jsonOptions) {
28823             var opt = optionsNameMap.get(id);
28824             if (opt) {
28825                 (defaultOptions || (defaultOptions = {}))[opt.name] = convertJsonOption(opt, jsonOptions[id], basePath, errors);
28826             }
28827             else {
28828                 errors.push(createUnknownOptionError(id, diagnostics, ts.createCompilerDiagnostic));
28829             }
28830         }
28831         return defaultOptions;
28832     }
28833     function convertJsonOption(opt, value, basePath, errors) {
28834         if (isCompilerOptionsValue(opt, value)) {
28835             var optType = opt.type;
28836             if (optType === "list" && ts.isArray(value)) {
28837                 return convertJsonOptionOfListType(opt, value, basePath, errors);
28838             }
28839             else if (!ts.isString(optType)) {
28840                 return convertJsonOptionOfCustomType(opt, value, errors);
28841             }
28842             return normalizeNonListOptionValue(opt, basePath, value);
28843         }
28844         else {
28845             errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, opt.name, getCompilerOptionValueTypeString(opt)));
28846         }
28847     }
28848     function normalizeOptionValue(option, basePath, value) {
28849         if (isNullOrUndefined(value))
28850             return undefined;
28851         if (option.type === "list") {
28852             var listOption_1 = option;
28853             if (listOption_1.element.isFilePath || !ts.isString(listOption_1.element.type)) {
28854                 return ts.filter(ts.map(value, function (v) { return normalizeOptionValue(listOption_1.element, basePath, v); }), function (v) { return !!v; });
28855             }
28856             return value;
28857         }
28858         else if (!ts.isString(option.type)) {
28859             return option.type.get(ts.isString(value) ? value.toLowerCase() : value);
28860         }
28861         return normalizeNonListOptionValue(option, basePath, value);
28862     }
28863     function normalizeNonListOptionValue(option, basePath, value) {
28864         if (option.isFilePath) {
28865             value = ts.getNormalizedAbsolutePath(value, basePath);
28866             if (value === "") {
28867                 value = ".";
28868             }
28869         }
28870         return value;
28871     }
28872     function convertJsonOptionOfCustomType(opt, value, errors) {
28873         if (isNullOrUndefined(value))
28874             return undefined;
28875         var key = value.toLowerCase();
28876         var val = opt.type.get(key);
28877         if (val !== undefined) {
28878             return val;
28879         }
28880         else {
28881             errors.push(createCompilerDiagnosticForInvalidCustomType(opt));
28882         }
28883     }
28884     function convertJsonOptionOfListType(option, values, basePath, errors) {
28885         return ts.filter(ts.map(values, function (v) { return convertJsonOption(option.element, v, basePath, errors); }), function (v) { return !!v; });
28886     }
28887     function trimString(s) {
28888         return typeof s.trim === "function" ? s.trim() : s.replace(/^[\s]+|[\s]+$/g, "");
28889     }
28890     /**
28891      * Tests for a path that ends in a recursive directory wildcard.
28892      * Matches **, \**, **\, and \**\, but not a**b.
28893      *
28894      * NOTE: used \ in place of / above to avoid issues with multiline comments.
28895      *
28896      * Breakdown:
28897      *  (^|\/)      # matches either the beginning of the string or a directory separator.
28898      *  \*\*        # matches the recursive directory wildcard "**".
28899      *  \/?$        # matches an optional trailing directory separator at the end of the string.
28900      */
28901     var invalidTrailingRecursionPattern = /(^|\/)\*\*\/?$/;
28902     /**
28903      * Tests for a path where .. appears after a recursive directory wildcard.
28904      * Matches **\..\*, **\a\..\*, and **\.., but not ..\**\*
28905      *
28906      * NOTE: used \ in place of / above to avoid issues with multiline comments.
28907      *
28908      * Breakdown:
28909      *  (^|\/)      # matches either the beginning of the string or a directory separator.
28910      *  \*\*\/      # matches a recursive directory wildcard "**" followed by a directory separator.
28911      *  (.*\/)?     # optionally matches any number of characters followed by a directory separator.
28912      *  \.\.        # matches a parent directory path component ".."
28913      *  ($|\/)      # matches either the end of the string or a directory separator.
28914      */
28915     var invalidDotDotAfterRecursiveWildcardPattern = /(^|\/)\*\*\/(.*\/)?\.\.($|\/)/;
28916     /**
28917      * Tests for a path containing a wildcard character in a directory component of the path.
28918      * Matches \*\, \?\, and \a*b\, but not \a\ or \a\*.
28919      *
28920      * NOTE: used \ in place of / above to avoid issues with multiline comments.
28921      *
28922      * Breakdown:
28923      *  \/          # matches a directory separator.
28924      *  [^/]*?      # matches any number of characters excluding directory separators (non-greedy).
28925      *  [*?]        # matches either a wildcard character (* or ?)
28926      *  [^/]*       # matches any number of characters excluding directory separators (greedy).
28927      *  \/          # matches a directory separator.
28928      */
28929     var watchRecursivePattern = /\/[^/]*?[*?][^/]*\//;
28930     /**
28931      * Matches the portion of a wildcard path that does not contain wildcards.
28932      * Matches \a of \a\*, or \a\b\c of \a\b\c\?\d.
28933      *
28934      * NOTE: used \ in place of / above to avoid issues with multiline comments.
28935      *
28936      * Breakdown:
28937      *  ^                   # matches the beginning of the string
28938      *  [^*?]*              # matches any number of non-wildcard characters
28939      *  (?=\/[^/]*[*?])     # lookahead that matches a directory separator followed by
28940      *                      # a path component that contains at least one wildcard character (* or ?).
28941      */
28942     var wildcardDirectoryPattern = /^[^*?]*(?=\/[^/]*[*?])/;
28943     /**
28944      * Expands an array of file specifications.
28945      *
28946      * @param filesSpecs The literal file names to include.
28947      * @param includeSpecs The wildcard file specifications to include.
28948      * @param excludeSpecs The wildcard file specifications to exclude.
28949      * @param basePath The base path for any relative file specifications.
28950      * @param options Compiler options.
28951      * @param host The host used to resolve files and directories.
28952      * @param errors An array for diagnostic reporting.
28953      */
28954     function matchFileNames(filesSpecs, includeSpecs, excludeSpecs, basePath, options, host, errors, extraFileExtensions, jsonSourceFile) {
28955         basePath = ts.normalizePath(basePath);
28956         var validatedIncludeSpecs, validatedExcludeSpecs;
28957         // The exclude spec list is converted into a regular expression, which allows us to quickly
28958         // test whether a file or directory should be excluded before recursively traversing the
28959         // file system.
28960         if (includeSpecs) {
28961             validatedIncludeSpecs = validateSpecs(includeSpecs, errors, /*allowTrailingRecursion*/ false, jsonSourceFile, "include");
28962         }
28963         if (excludeSpecs) {
28964             validatedExcludeSpecs = validateSpecs(excludeSpecs, errors, /*allowTrailingRecursion*/ true, jsonSourceFile, "exclude");
28965         }
28966         // Wildcard directories (provided as part of a wildcard path) are stored in a
28967         // file map that marks whether it was a regular wildcard match (with a `*` or `?` token),
28968         // or a recursive directory. This information is used by filesystem watchers to monitor for
28969         // new entries in these paths.
28970         var wildcardDirectories = getWildcardDirectories(validatedIncludeSpecs, validatedExcludeSpecs, basePath, host.useCaseSensitiveFileNames);
28971         var spec = { filesSpecs: filesSpecs, includeSpecs: includeSpecs, excludeSpecs: excludeSpecs, validatedIncludeSpecs: validatedIncludeSpecs, validatedExcludeSpecs: validatedExcludeSpecs, wildcardDirectories: wildcardDirectories };
28972         return getFileNamesFromConfigSpecs(spec, basePath, options, host, extraFileExtensions);
28973     }
28974     /**
28975      * Gets the file names from the provided config file specs that contain, files, include, exclude and
28976      * other properties needed to resolve the file names
28977      * @param spec The config file specs extracted with file names to include, wildcards to include/exclude and other details
28978      * @param basePath The base path for any relative file specifications.
28979      * @param options Compiler options.
28980      * @param host The host used to resolve files and directories.
28981      * @param extraFileExtensions optionaly file extra file extension information from host
28982      */
28983     /* @internal */
28984     function getFileNamesFromConfigSpecs(spec, basePath, options, host, extraFileExtensions) {
28985         if (extraFileExtensions === void 0) { extraFileExtensions = []; }
28986         basePath = ts.normalizePath(basePath);
28987         var keyMapper = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames);
28988         // Literal file names (provided via the "files" array in tsconfig.json) are stored in a
28989         // file map with a possibly case insensitive key. We use this map later when when including
28990         // wildcard paths.
28991         var literalFileMap = ts.createMap();
28992         // Wildcard paths (provided via the "includes" array in tsconfig.json) are stored in a
28993         // file map with a possibly case insensitive key. We use this map to store paths matched
28994         // via wildcard, and to handle extension priority.
28995         var wildcardFileMap = ts.createMap();
28996         // Wildcard paths of json files (provided via the "includes" array in tsconfig.json) are stored in a
28997         // file map with a possibly case insensitive key. We use this map to store paths matched
28998         // via wildcard of *.json kind
28999         var wildCardJsonFileMap = ts.createMap();
29000         var filesSpecs = spec.filesSpecs, validatedIncludeSpecs = spec.validatedIncludeSpecs, validatedExcludeSpecs = spec.validatedExcludeSpecs, wildcardDirectories = spec.wildcardDirectories;
29001         // Rather than requery this for each file and filespec, we query the supported extensions
29002         // once and store it on the expansion context.
29003         var supportedExtensions = ts.getSupportedExtensions(options, extraFileExtensions);
29004         var supportedExtensionsWithJsonIfResolveJsonModule = ts.getSuppoertedExtensionsWithJsonIfResolveJsonModule(options, supportedExtensions);
29005         // Literal files are always included verbatim. An "include" or "exclude" specification cannot
29006         // remove a literal file.
29007         if (filesSpecs) {
29008             for (var _i = 0, filesSpecs_1 = filesSpecs; _i < filesSpecs_1.length; _i++) {
29009                 var fileName = filesSpecs_1[_i];
29010                 var file = ts.getNormalizedAbsolutePath(fileName, basePath);
29011                 literalFileMap.set(keyMapper(file), file);
29012             }
29013         }
29014         var jsonOnlyIncludeRegexes;
29015         if (validatedIncludeSpecs && validatedIncludeSpecs.length > 0) {
29016             var _loop_5 = function (file) {
29017                 if (ts.fileExtensionIs(file, ".json" /* Json */)) {
29018                     // Valid only if *.json specified
29019                     if (!jsonOnlyIncludeRegexes) {
29020                         var includes = validatedIncludeSpecs.filter(function (s) { return ts.endsWith(s, ".json" /* Json */); });
29021                         var includeFilePatterns = ts.map(ts.getRegularExpressionsForWildcards(includes, basePath, "files"), function (pattern) { return "^" + pattern + "$"; });
29022                         jsonOnlyIncludeRegexes = includeFilePatterns ? includeFilePatterns.map(function (pattern) { return ts.getRegexFromPattern(pattern, host.useCaseSensitiveFileNames); }) : ts.emptyArray;
29023                     }
29024                     var includeIndex = ts.findIndex(jsonOnlyIncludeRegexes, function (re) { return re.test(file); });
29025                     if (includeIndex !== -1) {
29026                         var key_1 = keyMapper(file);
29027                         if (!literalFileMap.has(key_1) && !wildCardJsonFileMap.has(key_1)) {
29028                             wildCardJsonFileMap.set(key_1, file);
29029                         }
29030                     }
29031                     return "continue";
29032                 }
29033                 // If we have already included a literal or wildcard path with a
29034                 // higher priority extension, we should skip this file.
29035                 //
29036                 // This handles cases where we may encounter both <file>.ts and
29037                 // <file>.d.ts (or <file>.js if "allowJs" is enabled) in the same
29038                 // directory when they are compilation outputs.
29039                 if (hasFileWithHigherPriorityExtension(file, literalFileMap, wildcardFileMap, supportedExtensions, keyMapper)) {
29040                     return "continue";
29041                 }
29042                 // We may have included a wildcard path with a lower priority
29043                 // extension due to the user-defined order of entries in the
29044                 // "include" array. If there is a lower priority extension in the
29045                 // same directory, we should remove it.
29046                 removeWildcardFilesWithLowerPriorityExtension(file, wildcardFileMap, supportedExtensions, keyMapper);
29047                 var key = keyMapper(file);
29048                 if (!literalFileMap.has(key) && !wildcardFileMap.has(key)) {
29049                     wildcardFileMap.set(key, file);
29050                 }
29051             };
29052             for (var _a = 0, _b = host.readDirectory(basePath, supportedExtensionsWithJsonIfResolveJsonModule, validatedExcludeSpecs, validatedIncludeSpecs, /*depth*/ undefined); _a < _b.length; _a++) {
29053                 var file = _b[_a];
29054                 _loop_5(file);
29055             }
29056         }
29057         var literalFiles = ts.arrayFrom(literalFileMap.values());
29058         var wildcardFiles = ts.arrayFrom(wildcardFileMap.values());
29059         return {
29060             fileNames: literalFiles.concat(wildcardFiles, ts.arrayFrom(wildCardJsonFileMap.values())),
29061             wildcardDirectories: wildcardDirectories,
29062             spec: spec
29063         };
29064     }
29065     ts.getFileNamesFromConfigSpecs = getFileNamesFromConfigSpecs;
29066     function validateSpecs(specs, errors, allowTrailingRecursion, jsonSourceFile, specKey) {
29067         return specs.filter(function (spec) {
29068             var diag = specToDiagnostic(spec, allowTrailingRecursion);
29069             if (diag !== undefined) {
29070                 errors.push(createDiagnostic(diag, spec));
29071             }
29072             return diag === undefined;
29073         });
29074         function createDiagnostic(message, spec) {
29075             var element = ts.getTsConfigPropArrayElementValue(jsonSourceFile, specKey, spec);
29076             return element ?
29077                 ts.createDiagnosticForNodeInSourceFile(jsonSourceFile, element, message, spec) :
29078                 ts.createCompilerDiagnostic(message, spec);
29079         }
29080     }
29081     function specToDiagnostic(spec, allowTrailingRecursion) {
29082         if (!allowTrailingRecursion && invalidTrailingRecursionPattern.test(spec)) {
29083             return ts.Diagnostics.File_specification_cannot_end_in_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0;
29084         }
29085         else if (invalidDotDotAfterRecursiveWildcardPattern.test(spec)) {
29086             return ts.Diagnostics.File_specification_cannot_contain_a_parent_directory_that_appears_after_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0;
29087         }
29088     }
29089     /**
29090      * Gets directories in a set of include patterns that should be watched for changes.
29091      */
29092     function getWildcardDirectories(include, exclude, path, useCaseSensitiveFileNames) {
29093         // We watch a directory recursively if it contains a wildcard anywhere in a directory segment
29094         // of the pattern:
29095         //
29096         //  /a/b/**/d   - Watch /a/b recursively to catch changes to any d in any subfolder recursively
29097         //  /a/b/*/d    - Watch /a/b recursively to catch any d in any immediate subfolder, even if a new subfolder is added
29098         //  /a/b        - Watch /a/b recursively to catch changes to anything in any recursive subfoler
29099         //
29100         // We watch a directory without recursion if it contains a wildcard in the file segment of
29101         // the pattern:
29102         //
29103         //  /a/b/*      - Watch /a/b directly to catch any new file
29104         //  /a/b/a?z    - Watch /a/b directly to catch any new file matching a?z
29105         var rawExcludeRegex = ts.getRegularExpressionForWildcard(exclude, path, "exclude");
29106         var excludeRegex = rawExcludeRegex && new RegExp(rawExcludeRegex, useCaseSensitiveFileNames ? "" : "i");
29107         var wildcardDirectories = {};
29108         if (include !== undefined) {
29109             var recursiveKeys = [];
29110             for (var _i = 0, include_1 = include; _i < include_1.length; _i++) {
29111                 var file = include_1[_i];
29112                 var spec = ts.normalizePath(ts.combinePaths(path, file));
29113                 if (excludeRegex && excludeRegex.test(spec)) {
29114                     continue;
29115                 }
29116                 var match = getWildcardDirectoryFromSpec(spec, useCaseSensitiveFileNames);
29117                 if (match) {
29118                     var key = match.key, flags = match.flags;
29119                     var existingFlags = wildcardDirectories[key];
29120                     if (existingFlags === undefined || existingFlags < flags) {
29121                         wildcardDirectories[key] = flags;
29122                         if (flags === 1 /* Recursive */) {
29123                             recursiveKeys.push(key);
29124                         }
29125                     }
29126                 }
29127             }
29128             // Remove any subpaths under an existing recursively watched directory.
29129             for (var key in wildcardDirectories) {
29130                 if (ts.hasProperty(wildcardDirectories, key)) {
29131                     for (var _a = 0, recursiveKeys_1 = recursiveKeys; _a < recursiveKeys_1.length; _a++) {
29132                         var recursiveKey = recursiveKeys_1[_a];
29133                         if (key !== recursiveKey && ts.containsPath(recursiveKey, key, path, !useCaseSensitiveFileNames)) {
29134                             delete wildcardDirectories[key];
29135                         }
29136                     }
29137                 }
29138             }
29139         }
29140         return wildcardDirectories;
29141     }
29142     function getWildcardDirectoryFromSpec(spec, useCaseSensitiveFileNames) {
29143         var match = wildcardDirectoryPattern.exec(spec);
29144         if (match) {
29145             return {
29146                 key: useCaseSensitiveFileNames ? match[0] : ts.toFileNameLowerCase(match[0]),
29147                 flags: watchRecursivePattern.test(spec) ? 1 /* Recursive */ : 0 /* None */
29148             };
29149         }
29150         if (ts.isImplicitGlob(spec)) {
29151             return { key: spec, flags: 1 /* Recursive */ };
29152         }
29153         return undefined;
29154     }
29155     /**
29156      * Determines whether a literal or wildcard file has already been included that has a higher
29157      * extension priority.
29158      *
29159      * @param file The path to the file.
29160      * @param extensionPriority The priority of the extension.
29161      * @param context The expansion context.
29162      */
29163     function hasFileWithHigherPriorityExtension(file, literalFiles, wildcardFiles, extensions, keyMapper) {
29164         var extensionPriority = ts.getExtensionPriority(file, extensions);
29165         var adjustedExtensionPriority = ts.adjustExtensionPriority(extensionPriority, extensions);
29166         for (var i = 0 /* Highest */; i < adjustedExtensionPriority; i++) {
29167             var higherPriorityExtension = extensions[i];
29168             var higherPriorityPath = keyMapper(ts.changeExtension(file, higherPriorityExtension));
29169             if (literalFiles.has(higherPriorityPath) || wildcardFiles.has(higherPriorityPath)) {
29170                 return true;
29171             }
29172         }
29173         return false;
29174     }
29175     /**
29176      * Removes files included via wildcard expansion with a lower extension priority that have
29177      * already been included.
29178      *
29179      * @param file The path to the file.
29180      * @param extensionPriority The priority of the extension.
29181      * @param context The expansion context.
29182      */
29183     function removeWildcardFilesWithLowerPriorityExtension(file, wildcardFiles, extensions, keyMapper) {
29184         var extensionPriority = ts.getExtensionPriority(file, extensions);
29185         var nextExtensionPriority = ts.getNextLowestExtensionPriority(extensionPriority, extensions);
29186         for (var i = nextExtensionPriority; i < extensions.length; i++) {
29187             var lowerPriorityExtension = extensions[i];
29188             var lowerPriorityPath = keyMapper(ts.changeExtension(file, lowerPriorityExtension));
29189             wildcardFiles.delete(lowerPriorityPath);
29190         }
29191     }
29192     /**
29193      * Produces a cleaned version of compiler options with personally identifying info (aka, paths) removed.
29194      * Also converts enum values back to strings.
29195      */
29196     /* @internal */
29197     function convertCompilerOptionsForTelemetry(opts) {
29198         var out = {};
29199         for (var key in opts) {
29200             if (opts.hasOwnProperty(key)) {
29201                 var type = getOptionFromName(key);
29202                 if (type !== undefined) { // Ignore unknown options
29203                     out[key] = getOptionValueWithEmptyStrings(opts[key], type);
29204                 }
29205             }
29206         }
29207         return out;
29208     }
29209     ts.convertCompilerOptionsForTelemetry = convertCompilerOptionsForTelemetry;
29210     function getOptionValueWithEmptyStrings(value, option) {
29211         switch (option.type) {
29212             case "object": // "paths". Can't get any useful information from the value since we blank out strings, so just return "".
29213                 return "";
29214             case "string": // Could be any arbitrary string -- use empty string instead.
29215                 return "";
29216             case "number": // Allow numbers, but be sure to check it's actually a number.
29217                 return typeof value === "number" ? value : "";
29218             case "boolean":
29219                 return typeof value === "boolean" ? value : "";
29220             case "list":
29221                 var elementType_1 = option.element;
29222                 return ts.isArray(value) ? value.map(function (v) { return getOptionValueWithEmptyStrings(v, elementType_1); }) : "";
29223             default:
29224                 return ts.forEachEntry(option.type, function (optionEnumValue, optionStringValue) {
29225                     if (optionEnumValue === value) {
29226                         return optionStringValue;
29227                     }
29228                 }); // TODO: GH#18217
29229         }
29230     }
29231 })(ts || (ts = {}));
29232 var ts;
29233 (function (ts) {
29234     function trace(host) {
29235         host.trace(ts.formatMessage.apply(undefined, arguments));
29236     }
29237     ts.trace = trace;
29238     /* @internal */
29239     function isTraceEnabled(compilerOptions, host) {
29240         return !!compilerOptions.traceResolution && host.trace !== undefined;
29241     }
29242     ts.isTraceEnabled = isTraceEnabled;
29243     function withPackageId(packageInfo, r) {
29244         var packageId;
29245         if (r && packageInfo) {
29246             var packageJsonContent = packageInfo.packageJsonContent;
29247             if (typeof packageJsonContent.name === "string" && typeof packageJsonContent.version === "string") {
29248                 packageId = {
29249                     name: packageJsonContent.name,
29250                     subModuleName: r.path.slice(packageInfo.packageDirectory.length + ts.directorySeparator.length),
29251                     version: packageJsonContent.version
29252                 };
29253             }
29254         }
29255         return r && { path: r.path, extension: r.ext, packageId: packageId };
29256     }
29257     function noPackageId(r) {
29258         return withPackageId(/*packageInfo*/ undefined, r);
29259     }
29260     function removeIgnoredPackageId(r) {
29261         if (r) {
29262             ts.Debug.assert(r.packageId === undefined);
29263             return { path: r.path, ext: r.extension };
29264         }
29265     }
29266     /**
29267      * Kinds of file that we are currently looking for.
29268      * Typically there is one pass with Extensions.TypeScript, then a second pass with Extensions.JavaScript.
29269      */
29270     var Extensions;
29271     (function (Extensions) {
29272         Extensions[Extensions["TypeScript"] = 0] = "TypeScript";
29273         Extensions[Extensions["JavaScript"] = 1] = "JavaScript";
29274         Extensions[Extensions["Json"] = 2] = "Json";
29275         Extensions[Extensions["TSConfig"] = 3] = "TSConfig";
29276         Extensions[Extensions["DtsOnly"] = 4] = "DtsOnly"; /** Only '.d.ts' */
29277     })(Extensions || (Extensions = {}));
29278     /** Used with `Extensions.DtsOnly` to extract the path from TypeScript results. */
29279     function resolvedTypeScriptOnly(resolved) {
29280         if (!resolved) {
29281             return undefined;
29282         }
29283         ts.Debug.assert(ts.extensionIsTS(resolved.extension));
29284         return { fileName: resolved.path, packageId: resolved.packageId };
29285     }
29286     function createResolvedModuleWithFailedLookupLocations(resolved, isExternalLibraryImport, failedLookupLocations, resultFromCache) {
29287         var _a;
29288         if (resultFromCache) {
29289             (_a = resultFromCache.failedLookupLocations).push.apply(_a, failedLookupLocations);
29290             return resultFromCache;
29291         }
29292         return {
29293             resolvedModule: resolved && { resolvedFileName: resolved.path, originalPath: resolved.originalPath === true ? undefined : resolved.originalPath, extension: resolved.extension, isExternalLibraryImport: isExternalLibraryImport, packageId: resolved.packageId },
29294             failedLookupLocations: failedLookupLocations
29295         };
29296     }
29297     function readPackageJsonField(jsonContent, fieldName, typeOfTag, state) {
29298         if (!ts.hasProperty(jsonContent, fieldName)) {
29299             if (state.traceEnabled) {
29300                 trace(state.host, ts.Diagnostics.package_json_does_not_have_a_0_field, fieldName);
29301             }
29302             return;
29303         }
29304         var value = jsonContent[fieldName];
29305         if (typeof value !== typeOfTag || value === null) { // eslint-disable-line no-null/no-null
29306             if (state.traceEnabled) {
29307                 // eslint-disable-next-line no-null/no-null
29308                 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);
29309             }
29310             return;
29311         }
29312         return value;
29313     }
29314     function readPackageJsonPathField(jsonContent, fieldName, baseDirectory, state) {
29315         var fileName = readPackageJsonField(jsonContent, fieldName, "string", state);
29316         if (fileName === undefined) {
29317             return;
29318         }
29319         if (!fileName) {
29320             if (state.traceEnabled) {
29321                 trace(state.host, ts.Diagnostics.package_json_had_a_falsy_0_field, fieldName);
29322             }
29323             return;
29324         }
29325         var path = ts.normalizePath(ts.combinePaths(baseDirectory, fileName));
29326         if (state.traceEnabled) {
29327             trace(state.host, ts.Diagnostics.package_json_has_0_field_1_that_references_2, fieldName, fileName, path);
29328         }
29329         return path;
29330     }
29331     function readPackageJsonTypesFields(jsonContent, baseDirectory, state) {
29332         return readPackageJsonPathField(jsonContent, "typings", baseDirectory, state)
29333             || readPackageJsonPathField(jsonContent, "types", baseDirectory, state);
29334     }
29335     function readPackageJsonTSConfigField(jsonContent, baseDirectory, state) {
29336         return readPackageJsonPathField(jsonContent, "tsconfig", baseDirectory, state);
29337     }
29338     function readPackageJsonMainField(jsonContent, baseDirectory, state) {
29339         return readPackageJsonPathField(jsonContent, "main", baseDirectory, state);
29340     }
29341     function readPackageJsonTypesVersionsField(jsonContent, state) {
29342         var typesVersions = readPackageJsonField(jsonContent, "typesVersions", "object", state);
29343         if (typesVersions === undefined)
29344             return;
29345         if (state.traceEnabled) {
29346             trace(state.host, ts.Diagnostics.package_json_has_a_typesVersions_field_with_version_specific_path_mappings);
29347         }
29348         return typesVersions;
29349     }
29350     function readPackageJsonTypesVersionPaths(jsonContent, state) {
29351         var typesVersions = readPackageJsonTypesVersionsField(jsonContent, state);
29352         if (typesVersions === undefined)
29353             return;
29354         if (state.traceEnabled) {
29355             for (var key in typesVersions) {
29356                 if (ts.hasProperty(typesVersions, key) && !ts.VersionRange.tryParse(key)) {
29357                     trace(state.host, ts.Diagnostics.package_json_has_a_typesVersions_entry_0_that_is_not_a_valid_semver_range, key);
29358                 }
29359             }
29360         }
29361         var result = getPackageJsonTypesVersionsPaths(typesVersions);
29362         if (!result) {
29363             if (state.traceEnabled) {
29364                 trace(state.host, ts.Diagnostics.package_json_does_not_have_a_typesVersions_entry_that_matches_version_0, ts.versionMajorMinor);
29365             }
29366             return;
29367         }
29368         var bestVersionKey = result.version, bestVersionPaths = result.paths;
29369         if (typeof bestVersionPaths !== "object") {
29370             if (state.traceEnabled) {
29371                 trace(state.host, ts.Diagnostics.Expected_type_of_0_field_in_package_json_to_be_1_got_2, "typesVersions['" + bestVersionKey + "']", "object", typeof bestVersionPaths);
29372             }
29373             return;
29374         }
29375         return result;
29376     }
29377     var typeScriptVersion;
29378     /* @internal */
29379     function getPackageJsonTypesVersionsPaths(typesVersions) {
29380         if (!typeScriptVersion)
29381             typeScriptVersion = new ts.Version(ts.version);
29382         for (var key in typesVersions) {
29383             if (!ts.hasProperty(typesVersions, key))
29384                 continue;
29385             var keyRange = ts.VersionRange.tryParse(key);
29386             if (keyRange === undefined) {
29387                 continue;
29388             }
29389             // return the first entry whose range matches the current compiler version.
29390             if (keyRange.test(typeScriptVersion)) {
29391                 return { version: key, paths: typesVersions[key] };
29392             }
29393         }
29394     }
29395     ts.getPackageJsonTypesVersionsPaths = getPackageJsonTypesVersionsPaths;
29396     function getEffectiveTypeRoots(options, host) {
29397         if (options.typeRoots) {
29398             return options.typeRoots;
29399         }
29400         var currentDirectory;
29401         if (options.configFilePath) {
29402             currentDirectory = ts.getDirectoryPath(options.configFilePath);
29403         }
29404         else if (host.getCurrentDirectory) {
29405             currentDirectory = host.getCurrentDirectory();
29406         }
29407         if (currentDirectory !== undefined) {
29408             return getDefaultTypeRoots(currentDirectory, host);
29409         }
29410     }
29411     ts.getEffectiveTypeRoots = getEffectiveTypeRoots;
29412     /**
29413      * Returns the path to every node_modules/@types directory from some ancestor directory.
29414      * Returns undefined if there are none.
29415      */
29416     function getDefaultTypeRoots(currentDirectory, host) {
29417         if (!host.directoryExists) {
29418             return [ts.combinePaths(currentDirectory, nodeModulesAtTypes)];
29419             // And if it doesn't exist, tough.
29420         }
29421         var typeRoots;
29422         ts.forEachAncestorDirectory(ts.normalizePath(currentDirectory), function (directory) {
29423             var atTypes = ts.combinePaths(directory, nodeModulesAtTypes);
29424             if (host.directoryExists(atTypes)) {
29425                 (typeRoots || (typeRoots = [])).push(atTypes);
29426             }
29427             return undefined;
29428         });
29429         return typeRoots;
29430     }
29431     var nodeModulesAtTypes = ts.combinePaths("node_modules", "@types");
29432     /**
29433      * @param {string | undefined} containingFile - file that contains type reference directive, can be undefined if containing file is unknown.
29434      * This is possible in case if resolution is performed for directives specified via 'types' parameter. In this case initial path for secondary lookups
29435      * is assumed to be the same as root directory of the project.
29436      */
29437     function resolveTypeReferenceDirective(typeReferenceDirectiveName, containingFile, options, host, redirectedReference) {
29438         var traceEnabled = isTraceEnabled(options, host);
29439         if (redirectedReference) {
29440             options = redirectedReference.commandLine.options;
29441         }
29442         var failedLookupLocations = [];
29443         var moduleResolutionState = { compilerOptions: options, host: host, traceEnabled: traceEnabled, failedLookupLocations: failedLookupLocations };
29444         var typeRoots = getEffectiveTypeRoots(options, host);
29445         if (traceEnabled) {
29446             if (containingFile === undefined) {
29447                 if (typeRoots === undefined) {
29448                     trace(host, ts.Diagnostics.Resolving_type_reference_directive_0_containing_file_not_set_root_directory_not_set, typeReferenceDirectiveName);
29449                 }
29450                 else {
29451                     trace(host, ts.Diagnostics.Resolving_type_reference_directive_0_containing_file_not_set_root_directory_1, typeReferenceDirectiveName, typeRoots);
29452                 }
29453             }
29454             else {
29455                 if (typeRoots === undefined) {
29456                     trace(host, ts.Diagnostics.Resolving_type_reference_directive_0_containing_file_1_root_directory_not_set, typeReferenceDirectiveName, containingFile);
29457                 }
29458                 else {
29459                     trace(host, ts.Diagnostics.Resolving_type_reference_directive_0_containing_file_1_root_directory_2, typeReferenceDirectiveName, containingFile, typeRoots);
29460                 }
29461             }
29462             if (redirectedReference) {
29463                 trace(host, ts.Diagnostics.Using_compiler_options_of_project_reference_redirect_0, redirectedReference.sourceFile.fileName);
29464             }
29465         }
29466         var resolved = primaryLookup();
29467         var primary = true;
29468         if (!resolved) {
29469             resolved = secondaryLookup();
29470             primary = false;
29471         }
29472         var resolvedTypeReferenceDirective;
29473         if (resolved) {
29474             var fileName = resolved.fileName, packageId = resolved.packageId;
29475             var resolvedFileName = options.preserveSymlinks ? fileName : realPath(fileName, host, traceEnabled);
29476             if (traceEnabled) {
29477                 if (packageId) {
29478                     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);
29479                 }
29480                 else {
29481                     trace(host, ts.Diagnostics.Type_reference_directive_0_was_successfully_resolved_to_1_primary_Colon_2, typeReferenceDirectiveName, resolvedFileName, primary);
29482                 }
29483             }
29484             resolvedTypeReferenceDirective = { primary: primary, resolvedFileName: resolvedFileName, packageId: packageId, isExternalLibraryImport: pathContainsNodeModules(fileName) };
29485         }
29486         return { resolvedTypeReferenceDirective: resolvedTypeReferenceDirective, failedLookupLocations: failedLookupLocations };
29487         function primaryLookup() {
29488             // Check primary library paths
29489             if (typeRoots && typeRoots.length) {
29490                 if (traceEnabled) {
29491                     trace(host, ts.Diagnostics.Resolving_with_primary_search_path_0, typeRoots.join(", "));
29492                 }
29493                 return ts.firstDefined(typeRoots, function (typeRoot) {
29494                     var candidate = ts.combinePaths(typeRoot, typeReferenceDirectiveName);
29495                     var candidateDirectory = ts.getDirectoryPath(candidate);
29496                     var directoryExists = ts.directoryProbablyExists(candidateDirectory, host);
29497                     if (!directoryExists && traceEnabled) {
29498                         trace(host, ts.Diagnostics.Directory_0_does_not_exist_skipping_all_lookups_in_it, candidateDirectory);
29499                     }
29500                     return resolvedTypeScriptOnly(loadNodeModuleFromDirectory(Extensions.DtsOnly, candidate, !directoryExists, moduleResolutionState));
29501                 });
29502             }
29503             else {
29504                 if (traceEnabled) {
29505                     trace(host, ts.Diagnostics.Root_directory_cannot_be_determined_skipping_primary_search_paths);
29506                 }
29507             }
29508         }
29509         function secondaryLookup() {
29510             var initialLocationForSecondaryLookup = containingFile && ts.getDirectoryPath(containingFile);
29511             if (initialLocationForSecondaryLookup !== undefined) {
29512                 // check secondary locations
29513                 if (traceEnabled) {
29514                     trace(host, ts.Diagnostics.Looking_up_in_node_modules_folder_initial_location_0, initialLocationForSecondaryLookup);
29515                 }
29516                 var result = void 0;
29517                 if (!ts.isExternalModuleNameRelative(typeReferenceDirectiveName)) {
29518                     var searchResult = loadModuleFromNearestNodeModulesDirectory(Extensions.DtsOnly, typeReferenceDirectiveName, initialLocationForSecondaryLookup, moduleResolutionState, /*cache*/ undefined, /*redirectedReference*/ undefined);
29519                     result = searchResult && searchResult.value;
29520                 }
29521                 else {
29522                     var candidate = ts.normalizePathAndParts(ts.combinePaths(initialLocationForSecondaryLookup, typeReferenceDirectiveName)).path;
29523                     result = nodeLoadModuleByRelativeName(Extensions.DtsOnly, candidate, /*onlyRecordFailures*/ false, moduleResolutionState, /*considerPackageJson*/ true);
29524                 }
29525                 var resolvedFile = resolvedTypeScriptOnly(result);
29526                 if (!resolvedFile && traceEnabled) {
29527                     trace(host, ts.Diagnostics.Type_reference_directive_0_was_not_resolved, typeReferenceDirectiveName);
29528                 }
29529                 return resolvedFile;
29530             }
29531             else {
29532                 if (traceEnabled) {
29533                     trace(host, ts.Diagnostics.Containing_file_is_not_specified_and_root_directory_cannot_be_determined_skipping_lookup_in_node_modules_folder);
29534                 }
29535             }
29536         }
29537     }
29538     ts.resolveTypeReferenceDirective = resolveTypeReferenceDirective;
29539     /**
29540      * Given a set of options, returns the set of type directive names
29541      *   that should be included for this program automatically.
29542      * This list could either come from the config file,
29543      *   or from enumerating the types root + initial secondary types lookup location.
29544      * More type directives might appear in the program later as a result of loading actual source files;
29545      *   this list is only the set of defaults that are implicitly included.
29546      */
29547     function getAutomaticTypeDirectiveNames(options, host) {
29548         // Use explicit type list from tsconfig.json
29549         if (options.types) {
29550             return options.types;
29551         }
29552         // Walk the primary type lookup locations
29553         var result = [];
29554         if (host.directoryExists && host.getDirectories) {
29555             var typeRoots = getEffectiveTypeRoots(options, host);
29556             if (typeRoots) {
29557                 for (var _i = 0, typeRoots_1 = typeRoots; _i < typeRoots_1.length; _i++) {
29558                     var root = typeRoots_1[_i];
29559                     if (host.directoryExists(root)) {
29560                         for (var _a = 0, _b = host.getDirectories(root); _a < _b.length; _a++) {
29561                             var typeDirectivePath = _b[_a];
29562                             var normalized = ts.normalizePath(typeDirectivePath);
29563                             var packageJsonPath = ts.combinePaths(root, normalized, "package.json");
29564                             // `types-publisher` sometimes creates packages with `"typings": null` for packages that don't provide their own types.
29565                             // See `createNotNeededPackageJSON` in the types-publisher` repo.
29566                             // eslint-disable-next-line no-null/no-null
29567                             var isNotNeededPackage = host.fileExists(packageJsonPath) && ts.readJson(packageJsonPath, host).typings === null;
29568                             if (!isNotNeededPackage) {
29569                                 var baseFileName = ts.getBaseFileName(normalized);
29570                                 // At this stage, skip results with leading dot.
29571                                 if (baseFileName.charCodeAt(0) !== 46 /* dot */) {
29572                                     // Return just the type directive names
29573                                     result.push(baseFileName);
29574                                 }
29575                             }
29576                         }
29577                     }
29578                 }
29579             }
29580         }
29581         return result;
29582     }
29583     ts.getAutomaticTypeDirectiveNames = getAutomaticTypeDirectiveNames;
29584     function createModuleResolutionCache(currentDirectory, getCanonicalFileName, options) {
29585         return createModuleResolutionCacheWithMaps(createCacheWithRedirects(options), createCacheWithRedirects(options), currentDirectory, getCanonicalFileName);
29586     }
29587     ts.createModuleResolutionCache = createModuleResolutionCache;
29588     /*@internal*/
29589     function createCacheWithRedirects(options) {
29590         var ownMap = ts.createMap();
29591         var redirectsMap = ts.createMap();
29592         return {
29593             ownMap: ownMap,
29594             redirectsMap: redirectsMap,
29595             getOrCreateMapOfCacheRedirects: getOrCreateMapOfCacheRedirects,
29596             clear: clear,
29597             setOwnOptions: setOwnOptions,
29598             setOwnMap: setOwnMap
29599         };
29600         function setOwnOptions(newOptions) {
29601             options = newOptions;
29602         }
29603         function setOwnMap(newOwnMap) {
29604             ownMap = newOwnMap;
29605         }
29606         function getOrCreateMapOfCacheRedirects(redirectedReference) {
29607             if (!redirectedReference) {
29608                 return ownMap;
29609             }
29610             var path = redirectedReference.sourceFile.path;
29611             var redirects = redirectsMap.get(path);
29612             if (!redirects) {
29613                 // Reuse map if redirected reference map uses same resolution
29614                 redirects = !options || ts.optionsHaveModuleResolutionChanges(options, redirectedReference.commandLine.options) ? ts.createMap() : ownMap;
29615                 redirectsMap.set(path, redirects);
29616             }
29617             return redirects;
29618         }
29619         function clear() {
29620             ownMap.clear();
29621             redirectsMap.clear();
29622         }
29623     }
29624     ts.createCacheWithRedirects = createCacheWithRedirects;
29625     /*@internal*/
29626     function createModuleResolutionCacheWithMaps(directoryToModuleNameMap, moduleNameToDirectoryMap, currentDirectory, getCanonicalFileName) {
29627         return { getOrCreateCacheForDirectory: getOrCreateCacheForDirectory, getOrCreateCacheForModuleName: getOrCreateCacheForModuleName, directoryToModuleNameMap: directoryToModuleNameMap, moduleNameToDirectoryMap: moduleNameToDirectoryMap };
29628         function getOrCreateCacheForDirectory(directoryName, redirectedReference) {
29629             var path = ts.toPath(directoryName, currentDirectory, getCanonicalFileName);
29630             return getOrCreateCache(directoryToModuleNameMap, redirectedReference, path, ts.createMap);
29631         }
29632         function getOrCreateCacheForModuleName(nonRelativeModuleName, redirectedReference) {
29633             ts.Debug.assert(!ts.isExternalModuleNameRelative(nonRelativeModuleName));
29634             return getOrCreateCache(moduleNameToDirectoryMap, redirectedReference, nonRelativeModuleName, createPerModuleNameCache);
29635         }
29636         function getOrCreateCache(cacheWithRedirects, redirectedReference, key, create) {
29637             var cache = cacheWithRedirects.getOrCreateMapOfCacheRedirects(redirectedReference);
29638             var result = cache.get(key);
29639             if (!result) {
29640                 result = create();
29641                 cache.set(key, result);
29642             }
29643             return result;
29644         }
29645         function createPerModuleNameCache() {
29646             var directoryPathMap = ts.createMap();
29647             return { get: get, set: set };
29648             function get(directory) {
29649                 return directoryPathMap.get(ts.toPath(directory, currentDirectory, getCanonicalFileName));
29650             }
29651             /**
29652              * At first this function add entry directory -> module resolution result to the table.
29653              * Then it computes the set of parent folders for 'directory' that should have the same module resolution result
29654              * and for every parent folder in set it adds entry: parent -> module resolution. .
29655              * Lets say we first directory name: /a/b/c/d/e and resolution result is: /a/b/bar.ts.
29656              * Set of parent folders that should have the same result will be:
29657              * [
29658              *     /a/b/c/d, /a/b/c, /a/b
29659              * ]
29660              * this means that request for module resolution from file in any of these folder will be immediately found in cache.
29661              */
29662             function set(directory, result) {
29663                 var path = ts.toPath(directory, currentDirectory, getCanonicalFileName);
29664                 // if entry is already in cache do nothing
29665                 if (directoryPathMap.has(path)) {
29666                     return;
29667                 }
29668                 directoryPathMap.set(path, result);
29669                 var resolvedFileName = result.resolvedModule &&
29670                     (result.resolvedModule.originalPath || result.resolvedModule.resolvedFileName);
29671                 // find common prefix between directory and resolved file name
29672                 // this common prefix should be the shortest path that has the same resolution
29673                 // directory: /a/b/c/d/e
29674                 // resolvedFileName: /a/b/foo.d.ts
29675                 // commonPrefix: /a/b
29676                 // for failed lookups cache the result for every directory up to root
29677                 var commonPrefix = resolvedFileName && getCommonPrefix(path, resolvedFileName);
29678                 var current = path;
29679                 while (current !== commonPrefix) {
29680                     var parent = ts.getDirectoryPath(current);
29681                     if (parent === current || directoryPathMap.has(parent)) {
29682                         break;
29683                     }
29684                     directoryPathMap.set(parent, result);
29685                     current = parent;
29686                 }
29687             }
29688             function getCommonPrefix(directory, resolution) {
29689                 var resolutionDirectory = ts.toPath(ts.getDirectoryPath(resolution), currentDirectory, getCanonicalFileName);
29690                 // find first position where directory and resolution differs
29691                 var i = 0;
29692                 var limit = Math.min(directory.length, resolutionDirectory.length);
29693                 while (i < limit && directory.charCodeAt(i) === resolutionDirectory.charCodeAt(i)) {
29694                     i++;
29695                 }
29696                 if (i === directory.length && (resolutionDirectory.length === i || resolutionDirectory[i] === ts.directorySeparator)) {
29697                     return directory;
29698                 }
29699                 var rootLength = ts.getRootLength(directory);
29700                 if (i < rootLength) {
29701                     return undefined;
29702                 }
29703                 var sep = directory.lastIndexOf(ts.directorySeparator, i - 1);
29704                 if (sep === -1) {
29705                     return undefined;
29706                 }
29707                 return directory.substr(0, Math.max(sep, rootLength));
29708             }
29709         }
29710     }
29711     ts.createModuleResolutionCacheWithMaps = createModuleResolutionCacheWithMaps;
29712     function resolveModuleNameFromCache(moduleName, containingFile, cache) {
29713         var containingDirectory = ts.getDirectoryPath(containingFile);
29714         var perFolderCache = cache && cache.getOrCreateCacheForDirectory(containingDirectory);
29715         return perFolderCache && perFolderCache.get(moduleName);
29716     }
29717     ts.resolveModuleNameFromCache = resolveModuleNameFromCache;
29718     function resolveModuleName(moduleName, containingFile, compilerOptions, host, cache, redirectedReference) {
29719         var traceEnabled = isTraceEnabled(compilerOptions, host);
29720         if (redirectedReference) {
29721             compilerOptions = redirectedReference.commandLine.options;
29722         }
29723         if (traceEnabled) {
29724             trace(host, ts.Diagnostics.Resolving_module_0_from_1, moduleName, containingFile);
29725             if (redirectedReference) {
29726                 trace(host, ts.Diagnostics.Using_compiler_options_of_project_reference_redirect_0, redirectedReference.sourceFile.fileName);
29727             }
29728         }
29729         var containingDirectory = ts.getDirectoryPath(containingFile);
29730         var perFolderCache = cache && cache.getOrCreateCacheForDirectory(containingDirectory, redirectedReference);
29731         var result = perFolderCache && perFolderCache.get(moduleName);
29732         if (result) {
29733             if (traceEnabled) {
29734                 trace(host, ts.Diagnostics.Resolution_for_module_0_was_found_in_cache_from_location_1, moduleName, containingDirectory);
29735             }
29736         }
29737         else {
29738             var moduleResolution = compilerOptions.moduleResolution;
29739             if (moduleResolution === undefined) {
29740                 moduleResolution = ts.getEmitModuleKind(compilerOptions) === ts.ModuleKind.CommonJS ? ts.ModuleResolutionKind.NodeJs : ts.ModuleResolutionKind.Classic;
29741                 if (traceEnabled) {
29742                     trace(host, ts.Diagnostics.Module_resolution_kind_is_not_specified_using_0, ts.ModuleResolutionKind[moduleResolution]);
29743                 }
29744             }
29745             else {
29746                 if (traceEnabled) {
29747                     trace(host, ts.Diagnostics.Explicitly_specified_module_resolution_kind_Colon_0, ts.ModuleResolutionKind[moduleResolution]);
29748                 }
29749             }
29750             ts.perfLogger.logStartResolveModule(moduleName /* , containingFile, ModuleResolutionKind[moduleResolution]*/);
29751             switch (moduleResolution) {
29752                 case ts.ModuleResolutionKind.NodeJs:
29753                     result = nodeModuleNameResolver(moduleName, containingFile, compilerOptions, host, cache, redirectedReference);
29754                     break;
29755                 case ts.ModuleResolutionKind.Classic:
29756                     result = classicNameResolver(moduleName, containingFile, compilerOptions, host, cache, redirectedReference);
29757                     break;
29758                 default:
29759                     return ts.Debug.fail("Unexpected moduleResolution: " + moduleResolution);
29760             }
29761             if (result && result.resolvedModule)
29762                 ts.perfLogger.logInfoEvent("Module \"" + moduleName + "\" resolved to \"" + result.resolvedModule.resolvedFileName + "\"");
29763             ts.perfLogger.logStopResolveModule((result && result.resolvedModule) ? "" + result.resolvedModule.resolvedFileName : "null");
29764             if (perFolderCache) {
29765                 perFolderCache.set(moduleName, result);
29766                 if (!ts.isExternalModuleNameRelative(moduleName)) {
29767                     // put result in per-module name cache
29768                     cache.getOrCreateCacheForModuleName(moduleName, redirectedReference).set(containingDirectory, result);
29769                 }
29770             }
29771         }
29772         if (traceEnabled) {
29773             if (result.resolvedModule) {
29774                 if (result.resolvedModule.packageId) {
29775                     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));
29776                 }
29777                 else {
29778                     trace(host, ts.Diagnostics.Module_name_0_was_successfully_resolved_to_1, moduleName, result.resolvedModule.resolvedFileName);
29779                 }
29780             }
29781             else {
29782                 trace(host, ts.Diagnostics.Module_name_0_was_not_resolved, moduleName);
29783             }
29784         }
29785         return result;
29786     }
29787     ts.resolveModuleName = resolveModuleName;
29788     /**
29789      * Any module resolution kind can be augmented with optional settings: 'baseUrl', 'paths' and 'rootDirs' - they are used to
29790      * mitigate differences between design time structure of the project and its runtime counterpart so the same import name
29791      * can be resolved successfully by TypeScript compiler and runtime module loader.
29792      * If these settings are set then loading procedure will try to use them to resolve module name and it can of failure it will
29793      * fallback to standard resolution routine.
29794      *
29795      * - baseUrl - this setting controls how non-relative module names are resolved. If this setting is specified then non-relative
29796      * names will be resolved relative to baseUrl: i.e. if baseUrl is '/a/b' then candidate location to resolve module name 'c/d' will
29797      * be '/a/b/c/d'
29798      * - paths - this setting can only be used when baseUrl is specified. allows to tune how non-relative module names
29799      * will be resolved based on the content of the module name.
29800      * Structure of 'paths' compiler options
29801      * 'paths': {
29802      *    pattern-1: [...substitutions],
29803      *    pattern-2: [...substitutions],
29804      *    ...
29805      *    pattern-n: [...substitutions]
29806      * }
29807      * Pattern here is a string that can contain zero or one '*' character. During module resolution module name will be matched against
29808      * all patterns in the list. Matching for patterns that don't contain '*' means that module name must be equal to pattern respecting the case.
29809      * If pattern contains '*' then to match pattern "<prefix>*<suffix>" module name must start with the <prefix> and end with <suffix>.
29810      * <MatchedStar> denotes part of the module name between <prefix> and <suffix>.
29811      * If module name can be matches with multiple patterns then pattern with the longest prefix will be picked.
29812      * After selecting pattern we'll use list of substitutions to get candidate locations of the module and the try to load module
29813      * from the candidate location.
29814      * Substitution is a string that can contain zero or one '*'. To get candidate location from substitution we'll pick every
29815      * substitution in the list and replace '*' with <MatchedStar> string. If candidate location is not rooted it
29816      * will be converted to absolute using baseUrl.
29817      * For example:
29818      * baseUrl: /a/b/c
29819      * "paths": {
29820      *     // match all module names
29821      *     "*": [
29822      *         "*",        // use matched name as is,
29823      *                     // <matched name> will be looked as /a/b/c/<matched name>
29824      *
29825      *         "folder1/*" // substitution will convert matched name to 'folder1/<matched name>',
29826      *                     // since it is not rooted then final candidate location will be /a/b/c/folder1/<matched name>
29827      *     ],
29828      *     // match module names that start with 'components/'
29829      *     "components/*": [ "/root/components/*" ] // substitution will convert /components/folder1/<matched name> to '/root/components/folder1/<matched name>',
29830      *                                              // it is rooted so it will be final candidate location
29831      * }
29832      *
29833      * 'rootDirs' allows the project to be spreaded across multiple locations and resolve modules with relative names as if
29834      * they were in the same location. For example lets say there are two files
29835      * '/local/src/content/file1.ts'
29836      * '/shared/components/contracts/src/content/protocols/file2.ts'
29837      * After bundling content of '/shared/components/contracts/src' will be merged with '/local/src' so
29838      * if file1 has the following import 'import {x} from "./protocols/file2"' it will be resolved successfully in runtime.
29839      * 'rootDirs' provides the way to tell compiler that in order to get the whole project it should behave as if content of all
29840      * root dirs were merged together.
29841      * I.e. for the example above 'rootDirs' will have two entries: [ '/local/src', '/shared/components/contracts/src' ].
29842      * Compiler will first convert './protocols/file2' into absolute path relative to the location of containing file:
29843      * '/local/src/content/protocols/file2' and try to load it - failure.
29844      * Then it will search 'rootDirs' looking for a longest matching prefix of this absolute path and if such prefix is found - absolute path will
29845      * be converted to a path relative to found rootDir entry './content/protocols/file2' (*). As a last step compiler will check all remaining
29846      * entries in 'rootDirs', use them to build absolute path out of (*) and try to resolve module from this location.
29847      */
29848     function tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, loader, state) {
29849         var resolved = tryLoadModuleUsingPathsIfEligible(extensions, moduleName, loader, state);
29850         if (resolved)
29851             return resolved.value;
29852         if (!ts.isExternalModuleNameRelative(moduleName)) {
29853             return tryLoadModuleUsingBaseUrl(extensions, moduleName, loader, state);
29854         }
29855         else {
29856             return tryLoadModuleUsingRootDirs(extensions, moduleName, containingDirectory, loader, state);
29857         }
29858     }
29859     function tryLoadModuleUsingPathsIfEligible(extensions, moduleName, loader, state) {
29860         var _a = state.compilerOptions, baseUrl = _a.baseUrl, paths = _a.paths;
29861         if (baseUrl && paths && !ts.pathIsRelative(moduleName)) {
29862             if (state.traceEnabled) {
29863                 trace(state.host, ts.Diagnostics.baseUrl_option_is_set_to_0_using_this_value_to_resolve_non_relative_module_name_1, baseUrl, moduleName);
29864                 trace(state.host, ts.Diagnostics.paths_option_is_specified_looking_for_a_pattern_to_match_module_name_0, moduleName);
29865             }
29866             return tryLoadModuleUsingPaths(extensions, moduleName, baseUrl, paths, loader, /*onlyRecordFailures*/ false, state);
29867         }
29868     }
29869     function tryLoadModuleUsingRootDirs(extensions, moduleName, containingDirectory, loader, state) {
29870         if (!state.compilerOptions.rootDirs) {
29871             return undefined;
29872         }
29873         if (state.traceEnabled) {
29874             trace(state.host, ts.Diagnostics.rootDirs_option_is_set_using_it_to_resolve_relative_module_name_0, moduleName);
29875         }
29876         var candidate = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName));
29877         var matchedRootDir;
29878         var matchedNormalizedPrefix;
29879         for (var _i = 0, _a = state.compilerOptions.rootDirs; _i < _a.length; _i++) {
29880             var rootDir = _a[_i];
29881             // rootDirs are expected to be absolute
29882             // in case of tsconfig.json this will happen automatically - compiler will expand relative names
29883             // using location of tsconfig.json as base location
29884             var normalizedRoot = ts.normalizePath(rootDir);
29885             if (!ts.endsWith(normalizedRoot, ts.directorySeparator)) {
29886                 normalizedRoot += ts.directorySeparator;
29887             }
29888             var isLongestMatchingPrefix = ts.startsWith(candidate, normalizedRoot) &&
29889                 (matchedNormalizedPrefix === undefined || matchedNormalizedPrefix.length < normalizedRoot.length);
29890             if (state.traceEnabled) {
29891                 trace(state.host, ts.Diagnostics.Checking_if_0_is_the_longest_matching_prefix_for_1_2, normalizedRoot, candidate, isLongestMatchingPrefix);
29892             }
29893             if (isLongestMatchingPrefix) {
29894                 matchedNormalizedPrefix = normalizedRoot;
29895                 matchedRootDir = rootDir;
29896             }
29897         }
29898         if (matchedNormalizedPrefix) {
29899             if (state.traceEnabled) {
29900                 trace(state.host, ts.Diagnostics.Longest_matching_prefix_for_0_is_1, candidate, matchedNormalizedPrefix);
29901             }
29902             var suffix = candidate.substr(matchedNormalizedPrefix.length);
29903             // first - try to load from a initial location
29904             if (state.traceEnabled) {
29905                 trace(state.host, ts.Diagnostics.Loading_0_from_the_root_dir_1_candidate_location_2, suffix, matchedNormalizedPrefix, candidate);
29906             }
29907             var resolvedFileName = loader(extensions, candidate, !ts.directoryProbablyExists(containingDirectory, state.host), state);
29908             if (resolvedFileName) {
29909                 return resolvedFileName;
29910             }
29911             if (state.traceEnabled) {
29912                 trace(state.host, ts.Diagnostics.Trying_other_entries_in_rootDirs);
29913             }
29914             // then try to resolve using remaining entries in rootDirs
29915             for (var _b = 0, _c = state.compilerOptions.rootDirs; _b < _c.length; _b++) {
29916                 var rootDir = _c[_b];
29917                 if (rootDir === matchedRootDir) {
29918                     // skip the initially matched entry
29919                     continue;
29920                 }
29921                 var candidate_1 = ts.combinePaths(ts.normalizePath(rootDir), suffix);
29922                 if (state.traceEnabled) {
29923                     trace(state.host, ts.Diagnostics.Loading_0_from_the_root_dir_1_candidate_location_2, suffix, rootDir, candidate_1);
29924                 }
29925                 var baseDirectory = ts.getDirectoryPath(candidate_1);
29926                 var resolvedFileName_1 = loader(extensions, candidate_1, !ts.directoryProbablyExists(baseDirectory, state.host), state);
29927                 if (resolvedFileName_1) {
29928                     return resolvedFileName_1;
29929                 }
29930             }
29931             if (state.traceEnabled) {
29932                 trace(state.host, ts.Diagnostics.Module_resolution_using_rootDirs_has_failed);
29933             }
29934         }
29935         return undefined;
29936     }
29937     function tryLoadModuleUsingBaseUrl(extensions, moduleName, loader, state) {
29938         var baseUrl = state.compilerOptions.baseUrl;
29939         if (!baseUrl) {
29940             return undefined;
29941         }
29942         if (state.traceEnabled) {
29943             trace(state.host, ts.Diagnostics.baseUrl_option_is_set_to_0_using_this_value_to_resolve_non_relative_module_name_1, baseUrl, moduleName);
29944         }
29945         var candidate = ts.normalizePath(ts.combinePaths(baseUrl, moduleName));
29946         if (state.traceEnabled) {
29947             trace(state.host, ts.Diagnostics.Resolving_module_name_0_relative_to_base_url_1_2, moduleName, baseUrl, candidate);
29948         }
29949         return loader(extensions, candidate, !ts.directoryProbablyExists(ts.getDirectoryPath(candidate), state.host), state);
29950     }
29951     /**
29952      * Expose resolution logic to allow us to use Node module resolution logic from arbitrary locations.
29953      * No way to do this with `require()`: https://github.com/nodejs/node/issues/5963
29954      * Throws an error if the module can't be resolved.
29955      */
29956     /* @internal */
29957     function resolveJSModule(moduleName, initialDir, host) {
29958         var _a = tryResolveJSModuleWorker(moduleName, initialDir, host), resolvedModule = _a.resolvedModule, failedLookupLocations = _a.failedLookupLocations;
29959         if (!resolvedModule) {
29960             throw new Error("Could not resolve JS module '" + moduleName + "' starting at '" + initialDir + "'. Looked in: " + failedLookupLocations.join(", "));
29961         }
29962         return resolvedModule.resolvedFileName;
29963     }
29964     ts.resolveJSModule = resolveJSModule;
29965     /* @internal */
29966     function tryResolveJSModule(moduleName, initialDir, host) {
29967         var resolvedModule = tryResolveJSModuleWorker(moduleName, initialDir, host).resolvedModule;
29968         return resolvedModule && resolvedModule.resolvedFileName;
29969     }
29970     ts.tryResolveJSModule = tryResolveJSModule;
29971     var jsOnlyExtensions = [Extensions.JavaScript];
29972     var tsExtensions = [Extensions.TypeScript, Extensions.JavaScript];
29973     var tsPlusJsonExtensions = __spreadArrays(tsExtensions, [Extensions.Json]);
29974     var tsconfigExtensions = [Extensions.TSConfig];
29975     function tryResolveJSModuleWorker(moduleName, initialDir, host) {
29976         return nodeModuleNameResolverWorker(moduleName, initialDir, { moduleResolution: ts.ModuleResolutionKind.NodeJs, allowJs: true }, host, /*cache*/ undefined, jsOnlyExtensions, /*redirectedReferences*/ undefined);
29977     }
29978     function nodeModuleNameResolver(moduleName, containingFile, compilerOptions, host, cache, redirectedReference, lookupConfig) {
29979         return nodeModuleNameResolverWorker(moduleName, ts.getDirectoryPath(containingFile), compilerOptions, host, cache, lookupConfig ? tsconfigExtensions : (compilerOptions.resolveJsonModule ? tsPlusJsonExtensions : tsExtensions), redirectedReference);
29980     }
29981     ts.nodeModuleNameResolver = nodeModuleNameResolver;
29982     function nodeModuleNameResolverWorker(moduleName, containingDirectory, compilerOptions, host, cache, extensions, redirectedReference) {
29983         var _a, _b;
29984         var traceEnabled = isTraceEnabled(compilerOptions, host);
29985         var failedLookupLocations = [];
29986         var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled, failedLookupLocations: failedLookupLocations };
29987         var result = ts.forEach(extensions, function (ext) { return tryResolve(ext); });
29988         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);
29989         function tryResolve(extensions) {
29990             var loader = function (extensions, candidate, onlyRecordFailures, state) { return nodeLoadModuleByRelativeName(extensions, candidate, onlyRecordFailures, state, /*considerPackageJson*/ true); };
29991             var resolved = tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, loader, state);
29992             if (resolved) {
29993                 return toSearchResult({ resolved: resolved, isExternalLibraryImport: pathContainsNodeModules(resolved.path) });
29994             }
29995             if (!ts.isExternalModuleNameRelative(moduleName)) {
29996                 if (traceEnabled) {
29997                     trace(host, ts.Diagnostics.Loading_module_0_from_node_modules_folder_target_file_type_1, moduleName, Extensions[extensions]);
29998                 }
29999                 var resolved_1 = loadModuleFromNearestNodeModulesDirectory(extensions, moduleName, containingDirectory, state, cache, redirectedReference);
30000                 if (!resolved_1)
30001                     return undefined;
30002                 var resolvedValue = resolved_1.value;
30003                 if (!compilerOptions.preserveSymlinks && resolvedValue && !resolvedValue.originalPath) {
30004                     var path = realPath(resolvedValue.path, host, traceEnabled);
30005                     var originalPath = path === resolvedValue.path ? undefined : resolvedValue.path;
30006                     resolvedValue = __assign(__assign({}, resolvedValue), { path: path, originalPath: originalPath });
30007                 }
30008                 // For node_modules lookups, get the real path so that multiple accesses to an `npm link`-ed module do not create duplicate files.
30009                 return { value: resolvedValue && { resolved: resolvedValue, isExternalLibraryImport: true } };
30010             }
30011             else {
30012                 var _a = ts.normalizePathAndParts(ts.combinePaths(containingDirectory, moduleName)), candidate = _a.path, parts = _a.parts;
30013                 var resolved_2 = nodeLoadModuleByRelativeName(extensions, candidate, /*onlyRecordFailures*/ false, state, /*considerPackageJson*/ true);
30014                 // Treat explicit "node_modules" import as an external library import.
30015                 return resolved_2 && toSearchResult({ resolved: resolved_2, isExternalLibraryImport: ts.contains(parts, "node_modules") });
30016             }
30017         }
30018     }
30019     function realPath(path, host, traceEnabled) {
30020         if (!host.realpath) {
30021             return path;
30022         }
30023         var real = ts.normalizePath(host.realpath(path));
30024         if (traceEnabled) {
30025             trace(host, ts.Diagnostics.Resolving_real_path_for_0_result_1, path, real);
30026         }
30027         ts.Debug.assert(host.fileExists(real), path + " linked to nonexistent file " + real);
30028         return real;
30029     }
30030     function nodeLoadModuleByRelativeName(extensions, candidate, onlyRecordFailures, state, considerPackageJson) {
30031         if (state.traceEnabled) {
30032             trace(state.host, ts.Diagnostics.Loading_module_as_file_Slash_folder_candidate_module_location_0_target_file_type_1, candidate, Extensions[extensions]);
30033         }
30034         if (!ts.hasTrailingDirectorySeparator(candidate)) {
30035             if (!onlyRecordFailures) {
30036                 var parentOfCandidate = ts.getDirectoryPath(candidate);
30037                 if (!ts.directoryProbablyExists(parentOfCandidate, state.host)) {
30038                     if (state.traceEnabled) {
30039                         trace(state.host, ts.Diagnostics.Directory_0_does_not_exist_skipping_all_lookups_in_it, parentOfCandidate);
30040                     }
30041                     onlyRecordFailures = true;
30042                 }
30043             }
30044             var resolvedFromFile = loadModuleFromFile(extensions, candidate, onlyRecordFailures, state);
30045             if (resolvedFromFile) {
30046                 var packageDirectory = considerPackageJson ? parseNodeModuleFromPath(resolvedFromFile) : undefined;
30047                 var packageInfo = packageDirectory ? getPackageJsonInfo(packageDirectory, /*onlyRecordFailures*/ false, state) : undefined;
30048                 return withPackageId(packageInfo, resolvedFromFile);
30049             }
30050         }
30051         if (!onlyRecordFailures) {
30052             var candidateExists = ts.directoryProbablyExists(candidate, state.host);
30053             if (!candidateExists) {
30054                 if (state.traceEnabled) {
30055                     trace(state.host, ts.Diagnostics.Directory_0_does_not_exist_skipping_all_lookups_in_it, candidate);
30056                 }
30057                 onlyRecordFailures = true;
30058             }
30059         }
30060         return loadNodeModuleFromDirectory(extensions, candidate, onlyRecordFailures, state, considerPackageJson);
30061     }
30062     /*@internal*/
30063     ts.nodeModulesPathPart = "/node_modules/";
30064     /*@internal*/
30065     function pathContainsNodeModules(path) {
30066         return ts.stringContains(path, ts.nodeModulesPathPart);
30067     }
30068     ts.pathContainsNodeModules = pathContainsNodeModules;
30069     /**
30070      * This will be called on the successfully resolved path from `loadModuleFromFile`.
30071      * (Not neeeded for `loadModuleFromNodeModules` as that looks up the `package.json` as part of resolution.)
30072      *
30073      * packageDirectory is the directory of the package itself.
30074      *   For `blah/node_modules/foo/index.d.ts` this is packageDirectory: "foo"
30075      *   For `/node_modules/foo/bar.d.ts` this is packageDirectory: "foo"
30076      *   For `/node_modules/@types/foo/bar/index.d.ts` this is packageDirectory: "@types/foo"
30077      *   For `/node_modules/foo/bar/index.d.ts` this is packageDirectory: "foo"
30078      */
30079     function parseNodeModuleFromPath(resolved) {
30080         var path = ts.normalizePath(resolved.path);
30081         var idx = path.lastIndexOf(ts.nodeModulesPathPart);
30082         if (idx === -1) {
30083             return undefined;
30084         }
30085         var indexAfterNodeModules = idx + ts.nodeModulesPathPart.length;
30086         var indexAfterPackageName = moveToNextDirectorySeparatorIfAvailable(path, indexAfterNodeModules);
30087         if (path.charCodeAt(indexAfterNodeModules) === 64 /* at */) {
30088             indexAfterPackageName = moveToNextDirectorySeparatorIfAvailable(path, indexAfterPackageName);
30089         }
30090         return path.slice(0, indexAfterPackageName);
30091     }
30092     function moveToNextDirectorySeparatorIfAvailable(path, prevSeparatorIndex) {
30093         var nextSeparatorIndex = path.indexOf(ts.directorySeparator, prevSeparatorIndex + 1);
30094         return nextSeparatorIndex === -1 ? prevSeparatorIndex : nextSeparatorIndex;
30095     }
30096     function loadModuleFromFileNoPackageId(extensions, candidate, onlyRecordFailures, state) {
30097         return noPackageId(loadModuleFromFile(extensions, candidate, onlyRecordFailures, state));
30098     }
30099     /**
30100      * @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
30101      * 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.
30102      */
30103     function loadModuleFromFile(extensions, candidate, onlyRecordFailures, state) {
30104         if (extensions === Extensions.Json || extensions === Extensions.TSConfig) {
30105             var extensionLess = ts.tryRemoveExtension(candidate, ".json" /* Json */);
30106             return (extensionLess === undefined && extensions === Extensions.Json) ? undefined : tryAddingExtensions(extensionLess || candidate, extensions, onlyRecordFailures, state);
30107         }
30108         // First, try adding an extension. An import of "foo" could be matched by a file "foo.ts", or "foo.js" by "foo.js.ts"
30109         var resolvedByAddingExtension = tryAddingExtensions(candidate, extensions, onlyRecordFailures, state);
30110         if (resolvedByAddingExtension) {
30111             return resolvedByAddingExtension;
30112         }
30113         // If that didn't work, try stripping a ".js" or ".jsx" extension and replacing it with a TypeScript one;
30114         // e.g. "./foo.js" can be matched by "./foo.ts" or "./foo.d.ts"
30115         if (ts.hasJSFileExtension(candidate)) {
30116             var extensionless = ts.removeFileExtension(candidate);
30117             if (state.traceEnabled) {
30118                 var extension = candidate.substring(extensionless.length);
30119                 trace(state.host, ts.Diagnostics.File_name_0_has_a_1_extension_stripping_it, candidate, extension);
30120             }
30121             return tryAddingExtensions(extensionless, extensions, onlyRecordFailures, state);
30122         }
30123     }
30124     /** Try to return an existing file that adds one of the `extensions` to `candidate`. */
30125     function tryAddingExtensions(candidate, extensions, onlyRecordFailures, state) {
30126         if (!onlyRecordFailures) {
30127             // check if containing folder exists - if it doesn't then just record failures for all supported extensions without disk probing
30128             var directory = ts.getDirectoryPath(candidate);
30129             if (directory) {
30130                 onlyRecordFailures = !ts.directoryProbablyExists(directory, state.host);
30131             }
30132         }
30133         switch (extensions) {
30134             case Extensions.DtsOnly:
30135                 return tryExtension(".d.ts" /* Dts */);
30136             case Extensions.TypeScript:
30137                 return tryExtension(".ts" /* Ts */) || tryExtension(".tsx" /* Tsx */) || tryExtension(".d.ts" /* Dts */);
30138             case Extensions.JavaScript:
30139                 return tryExtension(".js" /* Js */) || tryExtension(".jsx" /* Jsx */);
30140             case Extensions.TSConfig:
30141             case Extensions.Json:
30142                 return tryExtension(".json" /* Json */);
30143         }
30144         function tryExtension(ext) {
30145             var path = tryFile(candidate + ext, onlyRecordFailures, state);
30146             return path === undefined ? undefined : { path: path, ext: ext };
30147         }
30148     }
30149     /** Return the file if it exists. */
30150     function tryFile(fileName, onlyRecordFailures, state) {
30151         if (!onlyRecordFailures) {
30152             if (state.host.fileExists(fileName)) {
30153                 if (state.traceEnabled) {
30154                     trace(state.host, ts.Diagnostics.File_0_exist_use_it_as_a_name_resolution_result, fileName);
30155                 }
30156                 return fileName;
30157             }
30158             else {
30159                 if (state.traceEnabled) {
30160                     trace(state.host, ts.Diagnostics.File_0_does_not_exist, fileName);
30161                 }
30162             }
30163         }
30164         state.failedLookupLocations.push(fileName);
30165         return undefined;
30166     }
30167     function loadNodeModuleFromDirectory(extensions, candidate, onlyRecordFailures, state, considerPackageJson) {
30168         if (considerPackageJson === void 0) { considerPackageJson = true; }
30169         var packageInfo = considerPackageJson ? getPackageJsonInfo(candidate, onlyRecordFailures, state) : undefined;
30170         var packageJsonContent = packageInfo && packageInfo.packageJsonContent;
30171         var versionPaths = packageInfo && packageInfo.versionPaths;
30172         return withPackageId(packageInfo, loadNodeModuleFromDirectoryWorker(extensions, candidate, onlyRecordFailures, state, packageJsonContent, versionPaths));
30173     }
30174     function getPackageJsonInfo(packageDirectory, onlyRecordFailures, state) {
30175         var host = state.host, traceEnabled = state.traceEnabled;
30176         var directoryExists = !onlyRecordFailures && ts.directoryProbablyExists(packageDirectory, host);
30177         var packageJsonPath = ts.combinePaths(packageDirectory, "package.json");
30178         if (directoryExists && host.fileExists(packageJsonPath)) {
30179             var packageJsonContent = ts.readJson(packageJsonPath, host);
30180             if (traceEnabled) {
30181                 trace(host, ts.Diagnostics.Found_package_json_at_0, packageJsonPath);
30182             }
30183             var versionPaths = readPackageJsonTypesVersionPaths(packageJsonContent, state);
30184             return { packageDirectory: packageDirectory, packageJsonContent: packageJsonContent, versionPaths: versionPaths };
30185         }
30186         else {
30187             if (directoryExists && traceEnabled) {
30188                 trace(host, ts.Diagnostics.File_0_does_not_exist, packageJsonPath);
30189             }
30190             // record package json as one of failed lookup locations - in the future if this file will appear it will invalidate resolution results
30191             state.failedLookupLocations.push(packageJsonPath);
30192         }
30193     }
30194     function loadNodeModuleFromDirectoryWorker(extensions, candidate, onlyRecordFailures, state, jsonContent, versionPaths) {
30195         var packageFile;
30196         if (jsonContent) {
30197             switch (extensions) {
30198                 case Extensions.JavaScript:
30199                 case Extensions.Json:
30200                     packageFile = readPackageJsonMainField(jsonContent, candidate, state);
30201                     break;
30202                 case Extensions.TypeScript:
30203                     // When resolving typescript modules, try resolving using main field as well
30204                     packageFile = readPackageJsonTypesFields(jsonContent, candidate, state) || readPackageJsonMainField(jsonContent, candidate, state);
30205                     break;
30206                 case Extensions.DtsOnly:
30207                     packageFile = readPackageJsonTypesFields(jsonContent, candidate, state);
30208                     break;
30209                 case Extensions.TSConfig:
30210                     packageFile = readPackageJsonTSConfigField(jsonContent, candidate, state);
30211                     break;
30212                 default:
30213                     return ts.Debug.assertNever(extensions);
30214             }
30215         }
30216         var loader = function (extensions, candidate, onlyRecordFailures, state) {
30217             var fromFile = tryFile(candidate, onlyRecordFailures, state);
30218             if (fromFile) {
30219                 var resolved = resolvedIfExtensionMatches(extensions, fromFile);
30220                 if (resolved) {
30221                     return noPackageId(resolved);
30222                 }
30223                 if (state.traceEnabled) {
30224                     trace(state.host, ts.Diagnostics.File_0_has_an_unsupported_extension_so_skipping_it, fromFile);
30225                 }
30226             }
30227             // Even if extensions is DtsOnly, we can still look up a .ts file as a result of package.json "types"
30228             var nextExtensions = extensions === Extensions.DtsOnly ? Extensions.TypeScript : extensions;
30229             // Don't do package.json lookup recursively, because Node.js' package lookup doesn't.
30230             return nodeLoadModuleByRelativeName(nextExtensions, candidate, onlyRecordFailures, state, /*considerPackageJson*/ false);
30231         };
30232         var onlyRecordFailuresForPackageFile = packageFile ? !ts.directoryProbablyExists(ts.getDirectoryPath(packageFile), state.host) : undefined;
30233         var onlyRecordFailuresForIndex = onlyRecordFailures || !ts.directoryProbablyExists(candidate, state.host);
30234         var indexPath = ts.combinePaths(candidate, extensions === Extensions.TSConfig ? "tsconfig" : "index");
30235         if (versionPaths && (!packageFile || ts.containsPath(candidate, packageFile))) {
30236             var moduleName = ts.getRelativePathFromDirectory(candidate, packageFile || indexPath, /*ignoreCase*/ false);
30237             if (state.traceEnabled) {
30238                 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);
30239             }
30240             var result = tryLoadModuleUsingPaths(extensions, moduleName, candidate, versionPaths.paths, loader, onlyRecordFailuresForPackageFile || onlyRecordFailuresForIndex, state);
30241             if (result) {
30242                 return removeIgnoredPackageId(result.value);
30243             }
30244         }
30245         // It won't have a `packageId` set, because we disabled `considerPackageJson`.
30246         var packageFileResult = packageFile && removeIgnoredPackageId(loader(extensions, packageFile, onlyRecordFailuresForPackageFile, state));
30247         if (packageFileResult)
30248             return packageFileResult;
30249         return loadModuleFromFile(extensions, indexPath, onlyRecordFailuresForIndex, state);
30250     }
30251     /** Resolve from an arbitrarily specified file. Return `undefined` if it has an unsupported extension. */
30252     function resolvedIfExtensionMatches(extensions, path) {
30253         var ext = ts.tryGetExtensionFromPath(path);
30254         return ext !== undefined && extensionIsOk(extensions, ext) ? { path: path, ext: ext } : undefined;
30255     }
30256     /** True if `extension` is one of the supported `extensions`. */
30257     function extensionIsOk(extensions, extension) {
30258         switch (extensions) {
30259             case Extensions.JavaScript:
30260                 return extension === ".js" /* Js */ || extension === ".jsx" /* Jsx */;
30261             case Extensions.TSConfig:
30262             case Extensions.Json:
30263                 return extension === ".json" /* Json */;
30264             case Extensions.TypeScript:
30265                 return extension === ".ts" /* Ts */ || extension === ".tsx" /* Tsx */ || extension === ".d.ts" /* Dts */;
30266             case Extensions.DtsOnly:
30267                 return extension === ".d.ts" /* Dts */;
30268         }
30269     }
30270     /* @internal */
30271     function parsePackageName(moduleName) {
30272         var idx = moduleName.indexOf(ts.directorySeparator);
30273         if (moduleName[0] === "@") {
30274             idx = moduleName.indexOf(ts.directorySeparator, idx + 1);
30275         }
30276         return idx === -1 ? { packageName: moduleName, rest: "" } : { packageName: moduleName.slice(0, idx), rest: moduleName.slice(idx + 1) };
30277     }
30278     ts.parsePackageName = parsePackageName;
30279     function loadModuleFromNearestNodeModulesDirectory(extensions, moduleName, directory, state, cache, redirectedReference) {
30280         return loadModuleFromNearestNodeModulesDirectoryWorker(extensions, moduleName, directory, state, /*typesScopeOnly*/ false, cache, redirectedReference);
30281     }
30282     function loadModuleFromNearestNodeModulesDirectoryTypesScope(moduleName, directory, state) {
30283         // Extensions parameter here doesn't actually matter, because typesOnly ensures we're just doing @types lookup, which is always DtsOnly.
30284         return loadModuleFromNearestNodeModulesDirectoryWorker(Extensions.DtsOnly, moduleName, directory, state, /*typesScopeOnly*/ true, /*cache*/ undefined, /*redirectedReference*/ undefined);
30285     }
30286     function loadModuleFromNearestNodeModulesDirectoryWorker(extensions, moduleName, directory, state, typesScopeOnly, cache, redirectedReference) {
30287         var perModuleNameCache = cache && cache.getOrCreateCacheForModuleName(moduleName, redirectedReference);
30288         return ts.forEachAncestorDirectory(ts.normalizeSlashes(directory), function (ancestorDirectory) {
30289             if (ts.getBaseFileName(ancestorDirectory) !== "node_modules") {
30290                 var resolutionFromCache = tryFindNonRelativeModuleNameInCache(perModuleNameCache, moduleName, ancestorDirectory, state);
30291                 if (resolutionFromCache) {
30292                     return resolutionFromCache;
30293                 }
30294                 return toSearchResult(loadModuleFromImmediateNodeModulesDirectory(extensions, moduleName, ancestorDirectory, state, typesScopeOnly));
30295             }
30296         });
30297     }
30298     function loadModuleFromImmediateNodeModulesDirectory(extensions, moduleName, directory, state, typesScopeOnly) {
30299         var nodeModulesFolder = ts.combinePaths(directory, "node_modules");
30300         var nodeModulesFolderExists = ts.directoryProbablyExists(nodeModulesFolder, state.host);
30301         if (!nodeModulesFolderExists && state.traceEnabled) {
30302             trace(state.host, ts.Diagnostics.Directory_0_does_not_exist_skipping_all_lookups_in_it, nodeModulesFolder);
30303         }
30304         var packageResult = typesScopeOnly ? undefined : loadModuleFromSpecificNodeModulesDirectory(extensions, moduleName, nodeModulesFolder, nodeModulesFolderExists, state);
30305         if (packageResult) {
30306             return packageResult;
30307         }
30308         if (extensions === Extensions.TypeScript || extensions === Extensions.DtsOnly) {
30309             var nodeModulesAtTypes_1 = ts.combinePaths(nodeModulesFolder, "@types");
30310             var nodeModulesAtTypesExists = nodeModulesFolderExists;
30311             if (nodeModulesFolderExists && !ts.directoryProbablyExists(nodeModulesAtTypes_1, state.host)) {
30312                 if (state.traceEnabled) {
30313                     trace(state.host, ts.Diagnostics.Directory_0_does_not_exist_skipping_all_lookups_in_it, nodeModulesAtTypes_1);
30314                 }
30315                 nodeModulesAtTypesExists = false;
30316             }
30317             return loadModuleFromSpecificNodeModulesDirectory(Extensions.DtsOnly, mangleScopedPackageNameWithTrace(moduleName, state), nodeModulesAtTypes_1, nodeModulesAtTypesExists, state);
30318         }
30319     }
30320     function loadModuleFromSpecificNodeModulesDirectory(extensions, moduleName, nodeModulesDirectory, nodeModulesDirectoryExists, state) {
30321         var candidate = ts.normalizePath(ts.combinePaths(nodeModulesDirectory, moduleName));
30322         // First look for a nested package.json, as in `node_modules/foo/bar/package.json`.
30323         var packageInfo = getPackageJsonInfo(candidate, !nodeModulesDirectoryExists, state);
30324         if (packageInfo) {
30325             var fromFile = loadModuleFromFile(extensions, candidate, !nodeModulesDirectoryExists, state);
30326             if (fromFile) {
30327                 return noPackageId(fromFile);
30328             }
30329             var fromDirectory = loadNodeModuleFromDirectoryWorker(extensions, candidate, !nodeModulesDirectoryExists, state, packageInfo.packageJsonContent, packageInfo.versionPaths);
30330             return withPackageId(packageInfo, fromDirectory);
30331         }
30332         var loader = function (extensions, candidate, onlyRecordFailures, state) {
30333             var pathAndExtension = loadModuleFromFile(extensions, candidate, onlyRecordFailures, state) ||
30334                 loadNodeModuleFromDirectoryWorker(extensions, candidate, onlyRecordFailures, state, packageInfo && packageInfo.packageJsonContent, packageInfo && packageInfo.versionPaths);
30335             return withPackageId(packageInfo, pathAndExtension);
30336         };
30337         var _a = parsePackageName(moduleName), packageName = _a.packageName, rest = _a.rest;
30338         if (rest !== "") { // If "rest" is empty, we just did this search above.
30339             var packageDirectory = ts.combinePaths(nodeModulesDirectory, packageName);
30340             // 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.
30341             packageInfo = getPackageJsonInfo(packageDirectory, !nodeModulesDirectoryExists, state);
30342             if (packageInfo && packageInfo.versionPaths) {
30343                 if (state.traceEnabled) {
30344                     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);
30345                 }
30346                 var packageDirectoryExists = nodeModulesDirectoryExists && ts.directoryProbablyExists(packageDirectory, state.host);
30347                 var fromPaths = tryLoadModuleUsingPaths(extensions, rest, packageDirectory, packageInfo.versionPaths.paths, loader, !packageDirectoryExists, state);
30348                 if (fromPaths) {
30349                     return fromPaths.value;
30350                 }
30351             }
30352         }
30353         return loader(extensions, candidate, !nodeModulesDirectoryExists, state);
30354     }
30355     function tryLoadModuleUsingPaths(extensions, moduleName, baseDirectory, paths, loader, onlyRecordFailures, state) {
30356         var matchedPattern = ts.matchPatternOrExact(ts.getOwnKeys(paths), moduleName);
30357         if (matchedPattern) {
30358             var matchedStar_1 = ts.isString(matchedPattern) ? undefined : ts.matchedText(matchedPattern, moduleName);
30359             var matchedPatternText = ts.isString(matchedPattern) ? matchedPattern : ts.patternText(matchedPattern);
30360             if (state.traceEnabled) {
30361                 trace(state.host, ts.Diagnostics.Module_name_0_matched_pattern_1, moduleName, matchedPatternText);
30362             }
30363             var resolved = ts.forEach(paths[matchedPatternText], function (subst) {
30364                 var path = matchedStar_1 ? subst.replace("*", matchedStar_1) : subst;
30365                 var candidate = ts.normalizePath(ts.combinePaths(baseDirectory, path));
30366                 if (state.traceEnabled) {
30367                     trace(state.host, ts.Diagnostics.Trying_substitution_0_candidate_module_location_Colon_1, subst, path);
30368                 }
30369                 // A path mapping may have an extension, in contrast to an import, which should omit it.
30370                 var extension = ts.tryGetExtensionFromPath(candidate);
30371                 if (extension !== undefined) {
30372                     var path_1 = tryFile(candidate, onlyRecordFailures, state);
30373                     if (path_1 !== undefined) {
30374                         return noPackageId({ path: path_1, ext: extension });
30375                     }
30376                 }
30377                 return loader(extensions, candidate, onlyRecordFailures || !ts.directoryProbablyExists(ts.getDirectoryPath(candidate), state.host), state);
30378             });
30379             return { value: resolved };
30380         }
30381     }
30382     /** Double underscores are used in DefinitelyTyped to delimit scoped packages. */
30383     var mangledScopedPackageSeparator = "__";
30384     /** For a scoped package, we must look in `@types/foo__bar` instead of `@types/@foo/bar`. */
30385     function mangleScopedPackageNameWithTrace(packageName, state) {
30386         var mangled = mangleScopedPackageName(packageName);
30387         if (state.traceEnabled && mangled !== packageName) {
30388             trace(state.host, ts.Diagnostics.Scoped_package_detected_looking_in_0, mangled);
30389         }
30390         return mangled;
30391     }
30392     /* @internal */
30393     function getTypesPackageName(packageName) {
30394         return "@types/" + mangleScopedPackageName(packageName);
30395     }
30396     ts.getTypesPackageName = getTypesPackageName;
30397     /* @internal */
30398     function mangleScopedPackageName(packageName) {
30399         if (ts.startsWith(packageName, "@")) {
30400             var replaceSlash = packageName.replace(ts.directorySeparator, mangledScopedPackageSeparator);
30401             if (replaceSlash !== packageName) {
30402                 return replaceSlash.slice(1); // Take off the "@"
30403             }
30404         }
30405         return packageName;
30406     }
30407     ts.mangleScopedPackageName = mangleScopedPackageName;
30408     /* @internal */
30409     function getPackageNameFromTypesPackageName(mangledName) {
30410         var withoutAtTypePrefix = ts.removePrefix(mangledName, "@types/");
30411         if (withoutAtTypePrefix !== mangledName) {
30412             return unmangleScopedPackageName(withoutAtTypePrefix);
30413         }
30414         return mangledName;
30415     }
30416     ts.getPackageNameFromTypesPackageName = getPackageNameFromTypesPackageName;
30417     /* @internal */
30418     function unmangleScopedPackageName(typesPackageName) {
30419         return ts.stringContains(typesPackageName, mangledScopedPackageSeparator) ?
30420             "@" + typesPackageName.replace(mangledScopedPackageSeparator, ts.directorySeparator) :
30421             typesPackageName;
30422     }
30423     ts.unmangleScopedPackageName = unmangleScopedPackageName;
30424     function tryFindNonRelativeModuleNameInCache(cache, moduleName, containingDirectory, state) {
30425         var result = cache && cache.get(containingDirectory);
30426         if (result) {
30427             if (state.traceEnabled) {
30428                 trace(state.host, ts.Diagnostics.Resolution_for_module_0_was_found_in_cache_from_location_1, moduleName, containingDirectory);
30429             }
30430             state.resultFromCache = result;
30431             return { value: result.resolvedModule && { path: result.resolvedModule.resolvedFileName, originalPath: result.resolvedModule.originalPath || true, extension: result.resolvedModule.extension, packageId: result.resolvedModule.packageId } };
30432         }
30433     }
30434     function classicNameResolver(moduleName, containingFile, compilerOptions, host, cache, redirectedReference) {
30435         var traceEnabled = isTraceEnabled(compilerOptions, host);
30436         var failedLookupLocations = [];
30437         var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled, failedLookupLocations: failedLookupLocations };
30438         var containingDirectory = ts.getDirectoryPath(containingFile);
30439         var resolved = tryResolve(Extensions.TypeScript) || tryResolve(Extensions.JavaScript);
30440         // No originalPath because classic resolution doesn't resolve realPath
30441         return createResolvedModuleWithFailedLookupLocations(resolved && resolved.value, /*isExternalLibraryImport*/ false, failedLookupLocations, state.resultFromCache);
30442         function tryResolve(extensions) {
30443             var resolvedUsingSettings = tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, loadModuleFromFileNoPackageId, state);
30444             if (resolvedUsingSettings) {
30445                 return { value: resolvedUsingSettings };
30446             }
30447             if (!ts.isExternalModuleNameRelative(moduleName)) {
30448                 var perModuleNameCache_1 = cache && cache.getOrCreateCacheForModuleName(moduleName, redirectedReference);
30449                 // Climb up parent directories looking for a module.
30450                 var resolved_3 = ts.forEachAncestorDirectory(containingDirectory, function (directory) {
30451                     var resolutionFromCache = tryFindNonRelativeModuleNameInCache(perModuleNameCache_1, moduleName, directory, state);
30452                     if (resolutionFromCache) {
30453                         return resolutionFromCache;
30454                     }
30455                     var searchName = ts.normalizePath(ts.combinePaths(directory, moduleName));
30456                     return toSearchResult(loadModuleFromFileNoPackageId(extensions, searchName, /*onlyRecordFailures*/ false, state));
30457                 });
30458                 if (resolved_3) {
30459                     return resolved_3;
30460                 }
30461                 if (extensions === Extensions.TypeScript) {
30462                     // If we didn't find the file normally, look it up in @types.
30463                     return loadModuleFromNearestNodeModulesDirectoryTypesScope(moduleName, containingDirectory, state);
30464                 }
30465             }
30466             else {
30467                 var candidate = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName));
30468                 return toSearchResult(loadModuleFromFileNoPackageId(extensions, candidate, /*onlyRecordFailures*/ false, state));
30469             }
30470         }
30471     }
30472     ts.classicNameResolver = classicNameResolver;
30473     /**
30474      * A host may load a module from a global cache of typings.
30475      * This is the minumum code needed to expose that functionality; the rest is in the host.
30476      */
30477     /* @internal */
30478     function loadModuleFromGlobalCache(moduleName, projectName, compilerOptions, host, globalCache) {
30479         var traceEnabled = isTraceEnabled(compilerOptions, host);
30480         if (traceEnabled) {
30481             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);
30482         }
30483         var failedLookupLocations = [];
30484         var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled, failedLookupLocations: failedLookupLocations };
30485         var resolved = loadModuleFromImmediateNodeModulesDirectory(Extensions.DtsOnly, moduleName, globalCache, state, /*typesScopeOnly*/ false);
30486         return createResolvedModuleWithFailedLookupLocations(resolved, /*isExternalLibraryImport*/ true, failedLookupLocations, state.resultFromCache);
30487     }
30488     ts.loadModuleFromGlobalCache = loadModuleFromGlobalCache;
30489     /**
30490      * Wraps value to SearchResult.
30491      * @returns undefined if value is undefined or { value } otherwise
30492      */
30493     function toSearchResult(value) {
30494         return value !== undefined ? { value: value } : undefined;
30495     }
30496 })(ts || (ts = {}));
30497 /* @internal */
30498 var ts;
30499 (function (ts) {
30500     var ModuleInstanceState;
30501     (function (ModuleInstanceState) {
30502         ModuleInstanceState[ModuleInstanceState["NonInstantiated"] = 0] = "NonInstantiated";
30503         ModuleInstanceState[ModuleInstanceState["Instantiated"] = 1] = "Instantiated";
30504         ModuleInstanceState[ModuleInstanceState["ConstEnumOnly"] = 2] = "ConstEnumOnly";
30505     })(ModuleInstanceState = ts.ModuleInstanceState || (ts.ModuleInstanceState = {}));
30506     function getModuleInstanceState(node, visited) {
30507         if (node.body && !node.body.parent) {
30508             // getModuleInstanceStateForAliasTarget needs to walk up the parent chain, so parent pointers must be set on this tree already
30509             setParentPointers(node, node.body);
30510         }
30511         return node.body ? getModuleInstanceStateCached(node.body, visited) : 1 /* Instantiated */;
30512     }
30513     ts.getModuleInstanceState = getModuleInstanceState;
30514     function getModuleInstanceStateCached(node, visited) {
30515         if (visited === void 0) { visited = ts.createMap(); }
30516         var nodeId = "" + ts.getNodeId(node);
30517         if (visited.has(nodeId)) {
30518             return visited.get(nodeId) || 0 /* NonInstantiated */;
30519         }
30520         visited.set(nodeId, undefined);
30521         var result = getModuleInstanceStateWorker(node, visited);
30522         visited.set(nodeId, result);
30523         return result;
30524     }
30525     function getModuleInstanceStateWorker(node, visited) {
30526         // A module is uninstantiated if it contains only
30527         switch (node.kind) {
30528             // 1. interface declarations, type alias declarations
30529             case 246 /* InterfaceDeclaration */:
30530             case 247 /* TypeAliasDeclaration */:
30531                 return 0 /* NonInstantiated */;
30532             // 2. const enum declarations
30533             case 248 /* EnumDeclaration */:
30534                 if (ts.isEnumConst(node)) {
30535                     return 2 /* ConstEnumOnly */;
30536                 }
30537                 break;
30538             // 3. non-exported import declarations
30539             case 254 /* ImportDeclaration */:
30540             case 253 /* ImportEqualsDeclaration */:
30541                 if (!(ts.hasModifier(node, 1 /* Export */))) {
30542                     return 0 /* NonInstantiated */;
30543                 }
30544                 break;
30545             // 4. Export alias declarations pointing at only uninstantiated modules or things uninstantiated modules contain
30546             case 260 /* ExportDeclaration */:
30547                 var exportDeclaration = node;
30548                 if (!exportDeclaration.moduleSpecifier && exportDeclaration.exportClause && exportDeclaration.exportClause.kind === 261 /* NamedExports */) {
30549                     var state = 0 /* NonInstantiated */;
30550                     for (var _i = 0, _a = exportDeclaration.exportClause.elements; _i < _a.length; _i++) {
30551                         var specifier = _a[_i];
30552                         var specifierState = getModuleInstanceStateForAliasTarget(specifier, visited);
30553                         if (specifierState > state) {
30554                             state = specifierState;
30555                         }
30556                         if (state === 1 /* Instantiated */) {
30557                             return state;
30558                         }
30559                     }
30560                     return state;
30561                 }
30562                 break;
30563             // 5. other uninstantiated module declarations.
30564             case 250 /* ModuleBlock */: {
30565                 var state_1 = 0 /* NonInstantiated */;
30566                 ts.forEachChild(node, function (n) {
30567                     var childState = getModuleInstanceStateCached(n, visited);
30568                     switch (childState) {
30569                         case 0 /* NonInstantiated */:
30570                             // child is non-instantiated - continue searching
30571                             return;
30572                         case 2 /* ConstEnumOnly */:
30573                             // child is const enum only - record state and continue searching
30574                             state_1 = 2 /* ConstEnumOnly */;
30575                             return;
30576                         case 1 /* Instantiated */:
30577                             // child is instantiated - record state and stop
30578                             state_1 = 1 /* Instantiated */;
30579                             return true;
30580                         default:
30581                             ts.Debug.assertNever(childState);
30582                     }
30583                 });
30584                 return state_1;
30585             }
30586             case 249 /* ModuleDeclaration */:
30587                 return getModuleInstanceState(node, visited);
30588             case 75 /* Identifier */:
30589                 // Only jsdoc typedef definition can exist in jsdoc namespace, and it should
30590                 // be considered the same as type alias
30591                 if (node.isInJSDocNamespace) {
30592                     return 0 /* NonInstantiated */;
30593                 }
30594         }
30595         return 1 /* Instantiated */;
30596     }
30597     function getModuleInstanceStateForAliasTarget(specifier, visited) {
30598         var name = specifier.propertyName || specifier.name;
30599         var p = specifier.parent;
30600         while (p) {
30601             if (ts.isBlock(p) || ts.isModuleBlock(p) || ts.isSourceFile(p)) {
30602                 var statements = p.statements;
30603                 var found = void 0;
30604                 for (var _i = 0, statements_1 = statements; _i < statements_1.length; _i++) {
30605                     var statement = statements_1[_i];
30606                     if (ts.nodeHasName(statement, name)) {
30607                         if (!statement.parent) {
30608                             setParentPointers(p, statement);
30609                         }
30610                         var state = getModuleInstanceStateCached(statement, visited);
30611                         if (found === undefined || state > found) {
30612                             found = state;
30613                         }
30614                         if (found === 1 /* Instantiated */) {
30615                             return found;
30616                         }
30617                     }
30618                 }
30619                 if (found !== undefined) {
30620                     return found;
30621                 }
30622             }
30623             p = p.parent;
30624         }
30625         return 1 /* Instantiated */; // Couldn't locate, assume could refer to a value
30626     }
30627     var ContainerFlags;
30628     (function (ContainerFlags) {
30629         // The current node is not a container, and no container manipulation should happen before
30630         // recursing into it.
30631         ContainerFlags[ContainerFlags["None"] = 0] = "None";
30632         // The current node is a container.  It should be set as the current container (and block-
30633         // container) before recursing into it.  The current node does not have locals.  Examples:
30634         //
30635         //      Classes, ObjectLiterals, TypeLiterals, Interfaces...
30636         ContainerFlags[ContainerFlags["IsContainer"] = 1] = "IsContainer";
30637         // The current node is a block-scoped-container.  It should be set as the current block-
30638         // container before recursing into it.  Examples:
30639         //
30640         //      Blocks (when not parented by functions), Catch clauses, For/For-in/For-of statements...
30641         ContainerFlags[ContainerFlags["IsBlockScopedContainer"] = 2] = "IsBlockScopedContainer";
30642         // The current node is the container of a control flow path. The current control flow should
30643         // be saved and restored, and a new control flow initialized within the container.
30644         ContainerFlags[ContainerFlags["IsControlFlowContainer"] = 4] = "IsControlFlowContainer";
30645         ContainerFlags[ContainerFlags["IsFunctionLike"] = 8] = "IsFunctionLike";
30646         ContainerFlags[ContainerFlags["IsFunctionExpression"] = 16] = "IsFunctionExpression";
30647         ContainerFlags[ContainerFlags["HasLocals"] = 32] = "HasLocals";
30648         ContainerFlags[ContainerFlags["IsInterface"] = 64] = "IsInterface";
30649         ContainerFlags[ContainerFlags["IsObjectLiteralOrClassExpressionMethod"] = 128] = "IsObjectLiteralOrClassExpressionMethod";
30650     })(ContainerFlags || (ContainerFlags = {}));
30651     function initFlowNode(node) {
30652         ts.Debug.attachFlowNodeDebugInfo(node);
30653         return node;
30654     }
30655     var binder = createBinder();
30656     function bindSourceFile(file, options) {
30657         ts.performance.mark("beforeBind");
30658         ts.perfLogger.logStartBindFile("" + file.fileName);
30659         binder(file, options);
30660         ts.perfLogger.logStopBindFile();
30661         ts.performance.mark("afterBind");
30662         ts.performance.measure("Bind", "beforeBind", "afterBind");
30663     }
30664     ts.bindSourceFile = bindSourceFile;
30665     function createBinder() {
30666         var file;
30667         var options;
30668         var languageVersion;
30669         var parent;
30670         var container;
30671         var thisParentContainer; // Container one level up
30672         var blockScopeContainer;
30673         var lastContainer;
30674         var delayedTypeAliases;
30675         var seenThisKeyword;
30676         // state used by control flow analysis
30677         var currentFlow;
30678         var currentBreakTarget;
30679         var currentContinueTarget;
30680         var currentReturnTarget;
30681         var currentTrueTarget;
30682         var currentFalseTarget;
30683         var currentExceptionTarget;
30684         var preSwitchCaseFlow;
30685         var activeLabelList;
30686         var hasExplicitReturn;
30687         // state used for emit helpers
30688         var emitFlags;
30689         // If this file is an external module, then it is automatically in strict-mode according to
30690         // ES6.  If it is not an external module, then we'll determine if it is in strict mode or
30691         // not depending on if we see "use strict" in certain places or if we hit a class/namespace
30692         // or if compiler options contain alwaysStrict.
30693         var inStrictMode;
30694         var symbolCount = 0;
30695         var Symbol;
30696         var classifiableNames;
30697         var unreachableFlow = { flags: 1 /* Unreachable */ };
30698         var reportedUnreachableFlow = { flags: 1 /* Unreachable */ };
30699         // state used to aggregate transform flags during bind.
30700         var subtreeTransformFlags = 0 /* None */;
30701         var skipTransformFlagAggregation;
30702         /**
30703          * Inside the binder, we may create a diagnostic for an as-yet unbound node (with potentially no parent pointers, implying no accessible source file)
30704          * 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)
30705          * This version of `createDiagnosticForNode` uses the binder's context to account for this, and always yields correct diagnostics even in these situations.
30706          */
30707         function createDiagnosticForNode(node, message, arg0, arg1, arg2) {
30708             return ts.createDiagnosticForNodeInSourceFile(ts.getSourceFileOfNode(node) || file, node, message, arg0, arg1, arg2);
30709         }
30710         function bindSourceFile(f, opts) {
30711             file = f;
30712             options = opts;
30713             languageVersion = ts.getEmitScriptTarget(options);
30714             inStrictMode = bindInStrictMode(file, opts);
30715             classifiableNames = ts.createUnderscoreEscapedMap();
30716             symbolCount = 0;
30717             skipTransformFlagAggregation = file.isDeclarationFile;
30718             Symbol = ts.objectAllocator.getSymbolConstructor();
30719             // Attach debugging information if necessary
30720             ts.Debug.attachFlowNodeDebugInfo(unreachableFlow);
30721             ts.Debug.attachFlowNodeDebugInfo(reportedUnreachableFlow);
30722             if (!file.locals) {
30723                 bind(file);
30724                 file.symbolCount = symbolCount;
30725                 file.classifiableNames = classifiableNames;
30726                 delayedBindJSDocTypedefTag();
30727             }
30728             file = undefined;
30729             options = undefined;
30730             languageVersion = undefined;
30731             parent = undefined;
30732             container = undefined;
30733             thisParentContainer = undefined;
30734             blockScopeContainer = undefined;
30735             lastContainer = undefined;
30736             delayedTypeAliases = undefined;
30737             seenThisKeyword = false;
30738             currentFlow = undefined;
30739             currentBreakTarget = undefined;
30740             currentContinueTarget = undefined;
30741             currentReturnTarget = undefined;
30742             currentTrueTarget = undefined;
30743             currentFalseTarget = undefined;
30744             currentExceptionTarget = undefined;
30745             activeLabelList = undefined;
30746             hasExplicitReturn = false;
30747             emitFlags = 0 /* None */;
30748             subtreeTransformFlags = 0 /* None */;
30749         }
30750         return bindSourceFile;
30751         function bindInStrictMode(file, opts) {
30752             if (ts.getStrictOptionValue(opts, "alwaysStrict") && !file.isDeclarationFile) {
30753                 // bind in strict mode source files with alwaysStrict option
30754                 return true;
30755             }
30756             else {
30757                 return !!file.externalModuleIndicator;
30758             }
30759         }
30760         function createSymbol(flags, name) {
30761             symbolCount++;
30762             return new Symbol(flags, name);
30763         }
30764         function addDeclarationToSymbol(symbol, node, symbolFlags) {
30765             symbol.flags |= symbolFlags;
30766             node.symbol = symbol;
30767             symbol.declarations = ts.appendIfUnique(symbol.declarations, node);
30768             if (symbolFlags & (32 /* Class */ | 384 /* Enum */ | 1536 /* Module */ | 3 /* Variable */) && !symbol.exports) {
30769                 symbol.exports = ts.createSymbolTable();
30770             }
30771             if (symbolFlags & (32 /* Class */ | 64 /* Interface */ | 2048 /* TypeLiteral */ | 4096 /* ObjectLiteral */) && !symbol.members) {
30772                 symbol.members = ts.createSymbolTable();
30773             }
30774             // On merge of const enum module with class or function, reset const enum only flag (namespaces will already recalculate)
30775             if (symbol.constEnumOnlyModule && (symbol.flags & (16 /* Function */ | 32 /* Class */ | 256 /* RegularEnum */))) {
30776                 symbol.constEnumOnlyModule = false;
30777             }
30778             if (symbolFlags & 111551 /* Value */) {
30779                 ts.setValueDeclaration(symbol, node);
30780             }
30781         }
30782         // Should not be called on a declaration with a computed property name,
30783         // unless it is a well known Symbol.
30784         function getDeclarationName(node) {
30785             if (node.kind === 259 /* ExportAssignment */) {
30786                 return node.isExportEquals ? "export=" /* ExportEquals */ : "default" /* Default */;
30787             }
30788             var name = ts.getNameOfDeclaration(node);
30789             if (name) {
30790                 if (ts.isAmbientModule(node)) {
30791                     var moduleName = ts.getTextOfIdentifierOrLiteral(name);
30792                     return (ts.isGlobalScopeAugmentation(node) ? "__global" : "\"" + moduleName + "\"");
30793                 }
30794                 if (name.kind === 154 /* ComputedPropertyName */) {
30795                     var nameExpression = name.expression;
30796                     // treat computed property names where expression is string/numeric literal as just string/numeric literal
30797                     if (ts.isStringOrNumericLiteralLike(nameExpression)) {
30798                         return ts.escapeLeadingUnderscores(nameExpression.text);
30799                     }
30800                     if (ts.isSignedNumericLiteral(nameExpression)) {
30801                         return ts.tokenToString(nameExpression.operator) + nameExpression.operand.text;
30802                     }
30803                     ts.Debug.assert(ts.isWellKnownSymbolSyntactically(nameExpression));
30804                     return ts.getPropertyNameForKnownSymbolName(ts.idText(nameExpression.name));
30805                 }
30806                 if (ts.isWellKnownSymbolSyntactically(name)) {
30807                     return ts.getPropertyNameForKnownSymbolName(ts.idText(name.name));
30808                 }
30809                 if (ts.isPrivateIdentifier(name)) {
30810                     // containingClass exists because private names only allowed inside classes
30811                     var containingClass = ts.getContainingClass(node);
30812                     if (!containingClass) {
30813                         // we can get here in cases where there is already a parse error.
30814                         return undefined;
30815                     }
30816                     var containingClassSymbol = containingClass.symbol;
30817                     return ts.getSymbolNameForPrivateIdentifier(containingClassSymbol, name.escapedText);
30818                 }
30819                 return ts.isPropertyNameLiteral(name) ? ts.getEscapedTextOfIdentifierOrLiteral(name) : undefined;
30820             }
30821             switch (node.kind) {
30822                 case 162 /* Constructor */:
30823                     return "__constructor" /* Constructor */;
30824                 case 170 /* FunctionType */:
30825                 case 165 /* CallSignature */:
30826                 case 305 /* JSDocSignature */:
30827                     return "__call" /* Call */;
30828                 case 171 /* ConstructorType */:
30829                 case 166 /* ConstructSignature */:
30830                     return "__new" /* New */;
30831                 case 167 /* IndexSignature */:
30832                     return "__index" /* Index */;
30833                 case 260 /* ExportDeclaration */:
30834                     return "__export" /* ExportStar */;
30835                 case 290 /* SourceFile */:
30836                     // json file should behave as
30837                     // module.exports = ...
30838                     return "export=" /* ExportEquals */;
30839                 case 209 /* BinaryExpression */:
30840                     if (ts.getAssignmentDeclarationKind(node) === 2 /* ModuleExports */) {
30841                         // module.exports = ...
30842                         return "export=" /* ExportEquals */;
30843                     }
30844                     ts.Debug.fail("Unknown binary declaration kind");
30845                     break;
30846                 case 300 /* JSDocFunctionType */:
30847                     return (ts.isJSDocConstructSignature(node) ? "__new" /* New */ : "__call" /* Call */);
30848                 case 156 /* Parameter */:
30849                     // Parameters with names are handled at the top of this function.  Parameters
30850                     // without names can only come from JSDocFunctionTypes.
30851                     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"; });
30852                     var functionType = node.parent;
30853                     var index = functionType.parameters.indexOf(node);
30854                     return "arg" + index;
30855             }
30856         }
30857         function getDisplayName(node) {
30858             return ts.isNamedDeclaration(node) ? ts.declarationNameToString(node.name) : ts.unescapeLeadingUnderscores(ts.Debug.checkDefined(getDeclarationName(node)));
30859         }
30860         /**
30861          * Declares a Symbol for the node and adds it to symbols. Reports errors for conflicting identifier names.
30862          * @param symbolTable - The symbol table which node will be added to.
30863          * @param parent - node's parent declaration.
30864          * @param node - The declaration to be added to the symbol table
30865          * @param includes - The SymbolFlags that node has in addition to its declaration type (eg: export, ambient, etc.)
30866          * @param excludes - The flags which node cannot be declared alongside in a symbol table. Used to report forbidden declarations.
30867          */
30868         function declareSymbol(symbolTable, parent, node, includes, excludes, isReplaceableByMethod) {
30869             ts.Debug.assert(!ts.hasDynamicName(node));
30870             var isDefaultExport = ts.hasModifier(node, 512 /* Default */) || ts.isExportSpecifier(node) && node.name.escapedText === "default";
30871             // The exported symbol for an export default function/class node is always named "default"
30872             var name = isDefaultExport && parent ? "default" /* Default */ : getDeclarationName(node);
30873             var symbol;
30874             if (name === undefined) {
30875                 symbol = createSymbol(0 /* None */, "__missing" /* Missing */);
30876             }
30877             else {
30878                 // Check and see if the symbol table already has a symbol with this name.  If not,
30879                 // create a new symbol with this name and add it to the table.  Note that we don't
30880                 // give the new symbol any flags *yet*.  This ensures that it will not conflict
30881                 // with the 'excludes' flags we pass in.
30882                 //
30883                 // If we do get an existing symbol, see if it conflicts with the new symbol we're
30884                 // creating.  For example, a 'var' symbol and a 'class' symbol will conflict within
30885                 // the same symbol table.  If we have a conflict, report the issue on each
30886                 // declaration we have for this symbol, and then create a new symbol for this
30887                 // declaration.
30888                 //
30889                 // Note that when properties declared in Javascript constructors
30890                 // (marked by isReplaceableByMethod) conflict with another symbol, the property loses.
30891                 // Always. This allows the common Javascript pattern of overwriting a prototype method
30892                 // with an bound instance method of the same type: `this.method = this.method.bind(this)`
30893                 //
30894                 // If we created a new symbol, either because we didn't have a symbol with this name
30895                 // in the symbol table, or we conflicted with an existing symbol, then just add this
30896                 // node as the sole declaration of the new symbol.
30897                 //
30898                 // Otherwise, we'll be merging into a compatible existing symbol (for example when
30899                 // you have multiple 'vars' with the same name in the same container).  In this case
30900                 // just add this node into the declarations list of the symbol.
30901                 symbol = symbolTable.get(name);
30902                 if (includes & 2885600 /* Classifiable */) {
30903                     classifiableNames.set(name, true);
30904                 }
30905                 if (!symbol) {
30906                     symbolTable.set(name, symbol = createSymbol(0 /* None */, name));
30907                     if (isReplaceableByMethod)
30908                         symbol.isReplaceableByMethod = true;
30909                 }
30910                 else if (isReplaceableByMethod && !symbol.isReplaceableByMethod) {
30911                     // A symbol already exists, so don't add this as a declaration.
30912                     return symbol;
30913                 }
30914                 else if (symbol.flags & excludes) {
30915                     if (symbol.isReplaceableByMethod) {
30916                         // Javascript constructor-declared symbols can be discarded in favor of
30917                         // prototype symbols like methods.
30918                         symbolTable.set(name, symbol = createSymbol(0 /* None */, name));
30919                     }
30920                     else if (!(includes & 3 /* Variable */ && symbol.flags & 67108864 /* Assignment */)) {
30921                         // Assignment declarations are allowed to merge with variables, no matter what other flags they have.
30922                         if (ts.isNamedDeclaration(node)) {
30923                             node.name.parent = node;
30924                         }
30925                         // Report errors every position with duplicate declaration
30926                         // Report errors on previous encountered declarations
30927                         var message_1 = symbol.flags & 2 /* BlockScopedVariable */
30928                             ? ts.Diagnostics.Cannot_redeclare_block_scoped_variable_0
30929                             : ts.Diagnostics.Duplicate_identifier_0;
30930                         var messageNeedsName_1 = true;
30931                         if (symbol.flags & 384 /* Enum */ || includes & 384 /* Enum */) {
30932                             message_1 = ts.Diagnostics.Enum_declarations_can_only_merge_with_namespace_or_other_enum_declarations;
30933                             messageNeedsName_1 = false;
30934                         }
30935                         var multipleDefaultExports_1 = false;
30936                         if (ts.length(symbol.declarations)) {
30937                             // If the current node is a default export of some sort, then check if
30938                             // there are any other default exports that we need to error on.
30939                             // We'll know whether we have other default exports depending on if `symbol` already has a declaration list set.
30940                             if (isDefaultExport) {
30941                                 message_1 = ts.Diagnostics.A_module_cannot_have_multiple_default_exports;
30942                                 messageNeedsName_1 = false;
30943                                 multipleDefaultExports_1 = true;
30944                             }
30945                             else {
30946                                 // This is to properly report an error in the case "export default { }" is after export default of class declaration or function declaration.
30947                                 // Error on multiple export default in the following case:
30948                                 // 1. multiple export default of class declaration or function declaration by checking NodeFlags.Default
30949                                 // 2. multiple export default of export assignment. This one doesn't have NodeFlags.Default on (as export default doesn't considered as modifiers)
30950                                 if (symbol.declarations && symbol.declarations.length &&
30951                                     (node.kind === 259 /* ExportAssignment */ && !node.isExportEquals)) {
30952                                     message_1 = ts.Diagnostics.A_module_cannot_have_multiple_default_exports;
30953                                     messageNeedsName_1 = false;
30954                                     multipleDefaultExports_1 = true;
30955                                 }
30956                             }
30957                         }
30958                         var relatedInformation_1 = [];
30959                         if (ts.isTypeAliasDeclaration(node) && ts.nodeIsMissing(node.type) && ts.hasModifier(node, 1 /* Export */) && symbol.flags & (2097152 /* Alias */ | 788968 /* Type */ | 1920 /* Namespace */)) {
30960                             // export type T; - may have meant export type { T }?
30961                             relatedInformation_1.push(createDiagnosticForNode(node, ts.Diagnostics.Did_you_mean_0, "export type { " + ts.unescapeLeadingUnderscores(node.name.escapedText) + " }"));
30962                         }
30963                         var declarationName_1 = ts.getNameOfDeclaration(node) || node;
30964                         ts.forEach(symbol.declarations, function (declaration, index) {
30965                             var decl = ts.getNameOfDeclaration(declaration) || declaration;
30966                             var diag = createDiagnosticForNode(decl, message_1, messageNeedsName_1 ? getDisplayName(declaration) : undefined);
30967                             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);
30968                             if (multipleDefaultExports_1) {
30969                                 relatedInformation_1.push(createDiagnosticForNode(decl, ts.Diagnostics.The_first_export_default_is_here));
30970                             }
30971                         });
30972                         var diag = createDiagnosticForNode(declarationName_1, message_1, messageNeedsName_1 ? getDisplayName(node) : undefined);
30973                         file.bindDiagnostics.push(ts.addRelatedInfo.apply(void 0, __spreadArrays([diag], relatedInformation_1)));
30974                         symbol = createSymbol(0 /* None */, name);
30975                     }
30976                 }
30977             }
30978             addDeclarationToSymbol(symbol, node, includes);
30979             if (symbol.parent) {
30980                 ts.Debug.assert(symbol.parent === parent, "Existing symbol parent should match new one");
30981             }
30982             else {
30983                 symbol.parent = parent;
30984             }
30985             return symbol;
30986         }
30987         function declareModuleMember(node, symbolFlags, symbolExcludes) {
30988             var hasExportModifier = ts.getCombinedModifierFlags(node) & 1 /* Export */;
30989             if (symbolFlags & 2097152 /* Alias */) {
30990                 if (node.kind === 263 /* ExportSpecifier */ || (node.kind === 253 /* ImportEqualsDeclaration */ && hasExportModifier)) {
30991                     return declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes);
30992                 }
30993                 else {
30994                     return declareSymbol(container.locals, /*parent*/ undefined, node, symbolFlags, symbolExcludes);
30995                 }
30996             }
30997             else {
30998                 // Exported module members are given 2 symbols: A local symbol that is classified with an ExportValue flag,
30999                 // and an associated export symbol with all the correct flags set on it. There are 2 main reasons:
31000                 //
31001                 //   1. We treat locals and exports of the same name as mutually exclusive within a container.
31002                 //      That means the binder will issue a Duplicate Identifier error if you mix locals and exports
31003                 //      with the same name in the same container.
31004                 //      TODO: Make this a more specific error and decouple it from the exclusion logic.
31005                 //   2. When we checkIdentifier in the checker, we set its resolved symbol to the local symbol,
31006                 //      but return the export symbol (by calling getExportSymbolOfValueSymbolIfExported). That way
31007                 //      when the emitter comes back to it, it knows not to qualify the name if it was found in a containing scope.
31008                 // NOTE: Nested ambient modules always should go to to 'locals' table to prevent their automatic merge
31009                 //       during global merging in the checker. Why? The only case when ambient module is permitted inside another module is module augmentation
31010                 //       and this case is specially handled. Module augmentations should only be merged with original module definition
31011                 //       and should never be merged directly with other augmentation, and the latter case would be possible if automatic merge is allowed.
31012                 if (ts.isJSDocTypeAlias(node))
31013                     ts.Debug.assert(ts.isInJSFile(node)); // We shouldn't add symbols for JSDoc nodes if not in a JS file.
31014                 if ((!ts.isAmbientModule(node) && (hasExportModifier || container.flags & 64 /* ExportContext */)) || ts.isJSDocTypeAlias(node)) {
31015                     if (!container.locals || (ts.hasModifier(node, 512 /* Default */) && !getDeclarationName(node))) {
31016                         return declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes); // No local symbol for an unnamed default!
31017                     }
31018                     var exportKind = symbolFlags & 111551 /* Value */ ? 1048576 /* ExportValue */ : 0;
31019                     var local = declareSymbol(container.locals, /*parent*/ undefined, node, exportKind, symbolExcludes);
31020                     local.exportSymbol = declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes);
31021                     node.localSymbol = local;
31022                     return local;
31023                 }
31024                 else {
31025                     return declareSymbol(container.locals, /*parent*/ undefined, node, symbolFlags, symbolExcludes);
31026                 }
31027             }
31028         }
31029         // All container nodes are kept on a linked list in declaration order. This list is used by
31030         // the getLocalNameOfContainer function in the type checker to validate that the local name
31031         // used for a container is unique.
31032         function bindContainer(node, containerFlags) {
31033             // Before we recurse into a node's children, we first save the existing parent, container
31034             // and block-container.  Then after we pop out of processing the children, we restore
31035             // these saved values.
31036             var saveContainer = container;
31037             var saveThisParentContainer = thisParentContainer;
31038             var savedBlockScopeContainer = blockScopeContainer;
31039             // Depending on what kind of node this is, we may have to adjust the current container
31040             // and block-container.   If the current node is a container, then it is automatically
31041             // considered the current block-container as well.  Also, for containers that we know
31042             // may contain locals, we eagerly initialize the .locals field. We do this because
31043             // it's highly likely that the .locals will be needed to place some child in (for example,
31044             // a parameter, or variable declaration).
31045             //
31046             // However, we do not proactively create the .locals for block-containers because it's
31047             // totally normal and common for block-containers to never actually have a block-scoped
31048             // variable in them.  We don't want to end up allocating an object for every 'block' we
31049             // run into when most of them won't be necessary.
31050             //
31051             // Finally, if this is a block-container, then we clear out any existing .locals object
31052             // it may contain within it.  This happens in incremental scenarios.  Because we can be
31053             // reusing a node from a previous compilation, that node may have had 'locals' created
31054             // for it.  We must clear this so we don't accidentally move any stale data forward from
31055             // a previous compilation.
31056             if (containerFlags & 1 /* IsContainer */) {
31057                 if (node.kind !== 202 /* ArrowFunction */) {
31058                     thisParentContainer = container;
31059                 }
31060                 container = blockScopeContainer = node;
31061                 if (containerFlags & 32 /* HasLocals */) {
31062                     container.locals = ts.createSymbolTable();
31063                 }
31064                 addToContainerChain(container);
31065             }
31066             else if (containerFlags & 2 /* IsBlockScopedContainer */) {
31067                 blockScopeContainer = node;
31068                 blockScopeContainer.locals = undefined;
31069             }
31070             if (containerFlags & 4 /* IsControlFlowContainer */) {
31071                 var saveCurrentFlow = currentFlow;
31072                 var saveBreakTarget = currentBreakTarget;
31073                 var saveContinueTarget = currentContinueTarget;
31074                 var saveReturnTarget = currentReturnTarget;
31075                 var saveExceptionTarget = currentExceptionTarget;
31076                 var saveActiveLabelList = activeLabelList;
31077                 var saveHasExplicitReturn = hasExplicitReturn;
31078                 var isIIFE = containerFlags & 16 /* IsFunctionExpression */ && !ts.hasModifier(node, 256 /* Async */) &&
31079                     !node.asteriskToken && !!ts.getImmediatelyInvokedFunctionExpression(node);
31080                 // A non-async, non-generator IIFE is considered part of the containing control flow. Return statements behave
31081                 // similarly to break statements that exit to a label just past the statement body.
31082                 if (!isIIFE) {
31083                     currentFlow = initFlowNode({ flags: 2 /* Start */ });
31084                     if (containerFlags & (16 /* IsFunctionExpression */ | 128 /* IsObjectLiteralOrClassExpressionMethod */)) {
31085                         currentFlow.node = node;
31086                     }
31087                 }
31088                 // We create a return control flow graph for IIFEs and constructors. For constructors
31089                 // we use the return control flow graph in strict property initialization checks.
31090                 currentReturnTarget = isIIFE || node.kind === 162 /* Constructor */ ? createBranchLabel() : undefined;
31091                 currentExceptionTarget = undefined;
31092                 currentBreakTarget = undefined;
31093                 currentContinueTarget = undefined;
31094                 activeLabelList = undefined;
31095                 hasExplicitReturn = false;
31096                 bindChildren(node);
31097                 // Reset all reachability check related flags on node (for incremental scenarios)
31098                 node.flags &= ~2816 /* ReachabilityAndEmitFlags */;
31099                 if (!(currentFlow.flags & 1 /* Unreachable */) && containerFlags & 8 /* IsFunctionLike */ && ts.nodeIsPresent(node.body)) {
31100                     node.flags |= 256 /* HasImplicitReturn */;
31101                     if (hasExplicitReturn)
31102                         node.flags |= 512 /* HasExplicitReturn */;
31103                     node.endFlowNode = currentFlow;
31104                 }
31105                 if (node.kind === 290 /* SourceFile */) {
31106                     node.flags |= emitFlags;
31107                 }
31108                 if (currentReturnTarget) {
31109                     addAntecedent(currentReturnTarget, currentFlow);
31110                     currentFlow = finishFlowLabel(currentReturnTarget);
31111                     if (node.kind === 162 /* Constructor */) {
31112                         node.returnFlowNode = currentFlow;
31113                     }
31114                 }
31115                 if (!isIIFE) {
31116                     currentFlow = saveCurrentFlow;
31117                 }
31118                 currentBreakTarget = saveBreakTarget;
31119                 currentContinueTarget = saveContinueTarget;
31120                 currentReturnTarget = saveReturnTarget;
31121                 currentExceptionTarget = saveExceptionTarget;
31122                 activeLabelList = saveActiveLabelList;
31123                 hasExplicitReturn = saveHasExplicitReturn;
31124             }
31125             else if (containerFlags & 64 /* IsInterface */) {
31126                 seenThisKeyword = false;
31127                 bindChildren(node);
31128                 node.flags = seenThisKeyword ? node.flags | 128 /* ContainsThis */ : node.flags & ~128 /* ContainsThis */;
31129             }
31130             else {
31131                 bindChildren(node);
31132             }
31133             container = saveContainer;
31134             thisParentContainer = saveThisParentContainer;
31135             blockScopeContainer = savedBlockScopeContainer;
31136         }
31137         function bindChildren(node) {
31138             if (skipTransformFlagAggregation) {
31139                 bindChildrenWorker(node);
31140             }
31141             else if (node.transformFlags & 536870912 /* HasComputedFlags */) {
31142                 skipTransformFlagAggregation = true;
31143                 bindChildrenWorker(node);
31144                 skipTransformFlagAggregation = false;
31145                 subtreeTransformFlags |= node.transformFlags & ~getTransformFlagsSubtreeExclusions(node.kind);
31146             }
31147             else {
31148                 var savedSubtreeTransformFlags = subtreeTransformFlags;
31149                 subtreeTransformFlags = 0;
31150                 bindChildrenWorker(node);
31151                 subtreeTransformFlags = savedSubtreeTransformFlags | computeTransformFlagsForNode(node, subtreeTransformFlags);
31152             }
31153         }
31154         function bindEachFunctionsFirst(nodes) {
31155             bindEach(nodes, function (n) { return n.kind === 244 /* FunctionDeclaration */ ? bind(n) : undefined; });
31156             bindEach(nodes, function (n) { return n.kind !== 244 /* FunctionDeclaration */ ? bind(n) : undefined; });
31157         }
31158         function bindEach(nodes, bindFunction) {
31159             if (bindFunction === void 0) { bindFunction = bind; }
31160             if (nodes === undefined) {
31161                 return;
31162             }
31163             if (skipTransformFlagAggregation) {
31164                 ts.forEach(nodes, bindFunction);
31165             }
31166             else {
31167                 var savedSubtreeTransformFlags = subtreeTransformFlags;
31168                 subtreeTransformFlags = 0 /* None */;
31169                 var nodeArrayFlags = 0 /* None */;
31170                 for (var _i = 0, nodes_2 = nodes; _i < nodes_2.length; _i++) {
31171                     var node = nodes_2[_i];
31172                     bindFunction(node);
31173                     nodeArrayFlags |= node.transformFlags & ~536870912 /* HasComputedFlags */;
31174                 }
31175                 nodes.transformFlags = nodeArrayFlags | 536870912 /* HasComputedFlags */;
31176                 subtreeTransformFlags |= savedSubtreeTransformFlags;
31177             }
31178         }
31179         function bindEachChild(node) {
31180             ts.forEachChild(node, bind, bindEach);
31181         }
31182         function bindChildrenWorker(node) {
31183             if (checkUnreachable(node)) {
31184                 bindEachChild(node);
31185                 bindJSDoc(node);
31186                 return;
31187             }
31188             if (node.kind >= 225 /* FirstStatement */ && node.kind <= 241 /* LastStatement */ && !options.allowUnreachableCode) {
31189                 node.flowNode = currentFlow;
31190             }
31191             switch (node.kind) {
31192                 case 229 /* WhileStatement */:
31193                     bindWhileStatement(node);
31194                     break;
31195                 case 228 /* DoStatement */:
31196                     bindDoStatement(node);
31197                     break;
31198                 case 230 /* ForStatement */:
31199                     bindForStatement(node);
31200                     break;
31201                 case 231 /* ForInStatement */:
31202                 case 232 /* ForOfStatement */:
31203                     bindForInOrForOfStatement(node);
31204                     break;
31205                 case 227 /* IfStatement */:
31206                     bindIfStatement(node);
31207                     break;
31208                 case 235 /* ReturnStatement */:
31209                 case 239 /* ThrowStatement */:
31210                     bindReturnOrThrow(node);
31211                     break;
31212                 case 234 /* BreakStatement */:
31213                 case 233 /* ContinueStatement */:
31214                     bindBreakOrContinueStatement(node);
31215                     break;
31216                 case 240 /* TryStatement */:
31217                     bindTryStatement(node);
31218                     break;
31219                 case 237 /* SwitchStatement */:
31220                     bindSwitchStatement(node);
31221                     break;
31222                 case 251 /* CaseBlock */:
31223                     bindCaseBlock(node);
31224                     break;
31225                 case 277 /* CaseClause */:
31226                     bindCaseClause(node);
31227                     break;
31228                 case 226 /* ExpressionStatement */:
31229                     bindExpressionStatement(node);
31230                     break;
31231                 case 238 /* LabeledStatement */:
31232                     bindLabeledStatement(node);
31233                     break;
31234                 case 207 /* PrefixUnaryExpression */:
31235                     bindPrefixUnaryExpressionFlow(node);
31236                     break;
31237                 case 208 /* PostfixUnaryExpression */:
31238                     bindPostfixUnaryExpressionFlow(node);
31239                     break;
31240                 case 209 /* BinaryExpression */:
31241                     bindBinaryExpressionFlow(node);
31242                     break;
31243                 case 203 /* DeleteExpression */:
31244                     bindDeleteExpressionFlow(node);
31245                     break;
31246                 case 210 /* ConditionalExpression */:
31247                     bindConditionalExpressionFlow(node);
31248                     break;
31249                 case 242 /* VariableDeclaration */:
31250                     bindVariableDeclarationFlow(node);
31251                     break;
31252                 case 194 /* PropertyAccessExpression */:
31253                 case 195 /* ElementAccessExpression */:
31254                     bindAccessExpressionFlow(node);
31255                     break;
31256                 case 196 /* CallExpression */:
31257                     bindCallExpressionFlow(node);
31258                     break;
31259                 case 218 /* NonNullExpression */:
31260                     bindNonNullExpressionFlow(node);
31261                     break;
31262                 case 322 /* JSDocTypedefTag */:
31263                 case 315 /* JSDocCallbackTag */:
31264                 case 316 /* JSDocEnumTag */:
31265                     bindJSDocTypeAlias(node);
31266                     break;
31267                 // In source files and blocks, bind functions first to match hoisting that occurs at runtime
31268                 case 290 /* SourceFile */: {
31269                     bindEachFunctionsFirst(node.statements);
31270                     bind(node.endOfFileToken);
31271                     break;
31272                 }
31273                 case 223 /* Block */:
31274                 case 250 /* ModuleBlock */:
31275                     bindEachFunctionsFirst(node.statements);
31276                     break;
31277                 default:
31278                     bindEachChild(node);
31279                     break;
31280             }
31281             bindJSDoc(node);
31282         }
31283         function isNarrowingExpression(expr) {
31284             switch (expr.kind) {
31285                 case 75 /* Identifier */:
31286                 case 104 /* ThisKeyword */:
31287                 case 194 /* PropertyAccessExpression */:
31288                 case 195 /* ElementAccessExpression */:
31289                     return containsNarrowableReference(expr);
31290                 case 196 /* CallExpression */:
31291                     return hasNarrowableArgument(expr);
31292                 case 200 /* ParenthesizedExpression */:
31293                     return isNarrowingExpression(expr.expression);
31294                 case 209 /* BinaryExpression */:
31295                     return isNarrowingBinaryExpression(expr);
31296                 case 207 /* PrefixUnaryExpression */:
31297                     return expr.operator === 53 /* ExclamationToken */ && isNarrowingExpression(expr.operand);
31298                 case 204 /* TypeOfExpression */:
31299                     return isNarrowingExpression(expr.expression);
31300             }
31301             return false;
31302         }
31303         function isNarrowableReference(expr) {
31304             return expr.kind === 75 /* Identifier */ || expr.kind === 104 /* ThisKeyword */ || expr.kind === 102 /* SuperKeyword */ ||
31305                 (ts.isPropertyAccessExpression(expr) || ts.isNonNullExpression(expr) || ts.isParenthesizedExpression(expr)) && isNarrowableReference(expr.expression) ||
31306                 ts.isElementAccessExpression(expr) && ts.isStringOrNumericLiteralLike(expr.argumentExpression) && isNarrowableReference(expr.expression);
31307         }
31308         function containsNarrowableReference(expr) {
31309             return isNarrowableReference(expr) || ts.isOptionalChain(expr) && containsNarrowableReference(expr.expression);
31310         }
31311         function hasNarrowableArgument(expr) {
31312             if (expr.arguments) {
31313                 for (var _i = 0, _a = expr.arguments; _i < _a.length; _i++) {
31314                     var argument = _a[_i];
31315                     if (containsNarrowableReference(argument)) {
31316                         return true;
31317                     }
31318                 }
31319             }
31320             if (expr.expression.kind === 194 /* PropertyAccessExpression */ &&
31321                 containsNarrowableReference(expr.expression.expression)) {
31322                 return true;
31323             }
31324             return false;
31325         }
31326         function isNarrowingTypeofOperands(expr1, expr2) {
31327             return ts.isTypeOfExpression(expr1) && isNarrowableOperand(expr1.expression) && ts.isStringLiteralLike(expr2);
31328         }
31329         function isNarrowableInOperands(left, right) {
31330             return ts.isStringLiteralLike(left) && isNarrowingExpression(right);
31331         }
31332         function isNarrowingBinaryExpression(expr) {
31333             switch (expr.operatorToken.kind) {
31334                 case 62 /* EqualsToken */:
31335                     return containsNarrowableReference(expr.left);
31336                 case 34 /* EqualsEqualsToken */:
31337                 case 35 /* ExclamationEqualsToken */:
31338                 case 36 /* EqualsEqualsEqualsToken */:
31339                 case 37 /* ExclamationEqualsEqualsToken */:
31340                     return isNarrowableOperand(expr.left) || isNarrowableOperand(expr.right) ||
31341                         isNarrowingTypeofOperands(expr.right, expr.left) || isNarrowingTypeofOperands(expr.left, expr.right);
31342                 case 98 /* InstanceOfKeyword */:
31343                     return isNarrowableOperand(expr.left);
31344                 case 97 /* InKeyword */:
31345                     return isNarrowableInOperands(expr.left, expr.right);
31346                 case 27 /* CommaToken */:
31347                     return isNarrowingExpression(expr.right);
31348             }
31349             return false;
31350         }
31351         function isNarrowableOperand(expr) {
31352             switch (expr.kind) {
31353                 case 200 /* ParenthesizedExpression */:
31354                     return isNarrowableOperand(expr.expression);
31355                 case 209 /* BinaryExpression */:
31356                     switch (expr.operatorToken.kind) {
31357                         case 62 /* EqualsToken */:
31358                             return isNarrowableOperand(expr.left);
31359                         case 27 /* CommaToken */:
31360                             return isNarrowableOperand(expr.right);
31361                     }
31362             }
31363             return containsNarrowableReference(expr);
31364         }
31365         function createBranchLabel() {
31366             return initFlowNode({ flags: 4 /* BranchLabel */, antecedents: undefined });
31367         }
31368         function createLoopLabel() {
31369             return initFlowNode({ flags: 8 /* LoopLabel */, antecedents: undefined });
31370         }
31371         function createReduceLabel(target, antecedents, antecedent) {
31372             return initFlowNode({ flags: 1024 /* ReduceLabel */, target: target, antecedents: antecedents, antecedent: antecedent });
31373         }
31374         function setFlowNodeReferenced(flow) {
31375             // On first reference we set the Referenced flag, thereafter we set the Shared flag
31376             flow.flags |= flow.flags & 2048 /* Referenced */ ? 4096 /* Shared */ : 2048 /* Referenced */;
31377         }
31378         function addAntecedent(label, antecedent) {
31379             if (!(antecedent.flags & 1 /* Unreachable */) && !ts.contains(label.antecedents, antecedent)) {
31380                 (label.antecedents || (label.antecedents = [])).push(antecedent);
31381                 setFlowNodeReferenced(antecedent);
31382             }
31383         }
31384         function createFlowCondition(flags, antecedent, expression) {
31385             if (antecedent.flags & 1 /* Unreachable */) {
31386                 return antecedent;
31387             }
31388             if (!expression) {
31389                 return flags & 32 /* TrueCondition */ ? antecedent : unreachableFlow;
31390             }
31391             if ((expression.kind === 106 /* TrueKeyword */ && flags & 64 /* FalseCondition */ ||
31392                 expression.kind === 91 /* FalseKeyword */ && flags & 32 /* TrueCondition */) &&
31393                 !ts.isExpressionOfOptionalChainRoot(expression) && !ts.isNullishCoalesce(expression.parent)) {
31394                 return unreachableFlow;
31395             }
31396             if (!isNarrowingExpression(expression)) {
31397                 return antecedent;
31398             }
31399             setFlowNodeReferenced(antecedent);
31400             return initFlowNode({ flags: flags, antecedent: antecedent, node: expression });
31401         }
31402         function createFlowSwitchClause(antecedent, switchStatement, clauseStart, clauseEnd) {
31403             setFlowNodeReferenced(antecedent);
31404             return initFlowNode({ flags: 128 /* SwitchClause */, antecedent: antecedent, switchStatement: switchStatement, clauseStart: clauseStart, clauseEnd: clauseEnd });
31405         }
31406         function createFlowMutation(flags, antecedent, node) {
31407             setFlowNodeReferenced(antecedent);
31408             var result = initFlowNode({ flags: flags, antecedent: antecedent, node: node });
31409             if (currentExceptionTarget) {
31410                 addAntecedent(currentExceptionTarget, result);
31411             }
31412             return result;
31413         }
31414         function createFlowCall(antecedent, node) {
31415             setFlowNodeReferenced(antecedent);
31416             return initFlowNode({ flags: 512 /* Call */, antecedent: antecedent, node: node });
31417         }
31418         function finishFlowLabel(flow) {
31419             var antecedents = flow.antecedents;
31420             if (!antecedents) {
31421                 return unreachableFlow;
31422             }
31423             if (antecedents.length === 1) {
31424                 return antecedents[0];
31425             }
31426             return flow;
31427         }
31428         function isStatementCondition(node) {
31429             var parent = node.parent;
31430             switch (parent.kind) {
31431                 case 227 /* IfStatement */:
31432                 case 229 /* WhileStatement */:
31433                 case 228 /* DoStatement */:
31434                     return parent.expression === node;
31435                 case 230 /* ForStatement */:
31436                 case 210 /* ConditionalExpression */:
31437                     return parent.condition === node;
31438             }
31439             return false;
31440         }
31441         function isLogicalExpression(node) {
31442             while (true) {
31443                 if (node.kind === 200 /* ParenthesizedExpression */) {
31444                     node = node.expression;
31445                 }
31446                 else if (node.kind === 207 /* PrefixUnaryExpression */ && node.operator === 53 /* ExclamationToken */) {
31447                     node = node.operand;
31448                 }
31449                 else {
31450                     return node.kind === 209 /* BinaryExpression */ && (node.operatorToken.kind === 55 /* AmpersandAmpersandToken */ ||
31451                         node.operatorToken.kind === 56 /* BarBarToken */ ||
31452                         node.operatorToken.kind === 60 /* QuestionQuestionToken */);
31453                 }
31454             }
31455         }
31456         function isTopLevelLogicalExpression(node) {
31457             while (ts.isParenthesizedExpression(node.parent) ||
31458                 ts.isPrefixUnaryExpression(node.parent) && node.parent.operator === 53 /* ExclamationToken */) {
31459                 node = node.parent;
31460             }
31461             return !isStatementCondition(node) &&
31462                 !isLogicalExpression(node.parent) &&
31463                 !(ts.isOptionalChain(node.parent) && node.parent.expression === node);
31464         }
31465         function doWithConditionalBranches(action, value, trueTarget, falseTarget) {
31466             var savedTrueTarget = currentTrueTarget;
31467             var savedFalseTarget = currentFalseTarget;
31468             currentTrueTarget = trueTarget;
31469             currentFalseTarget = falseTarget;
31470             action(value);
31471             currentTrueTarget = savedTrueTarget;
31472             currentFalseTarget = savedFalseTarget;
31473         }
31474         function bindCondition(node, trueTarget, falseTarget) {
31475             doWithConditionalBranches(bind, node, trueTarget, falseTarget);
31476             if (!node || !isLogicalExpression(node) && !(ts.isOptionalChain(node) && ts.isOutermostOptionalChain(node))) {
31477                 addAntecedent(trueTarget, createFlowCondition(32 /* TrueCondition */, currentFlow, node));
31478                 addAntecedent(falseTarget, createFlowCondition(64 /* FalseCondition */, currentFlow, node));
31479             }
31480         }
31481         function bindIterativeStatement(node, breakTarget, continueTarget) {
31482             var saveBreakTarget = currentBreakTarget;
31483             var saveContinueTarget = currentContinueTarget;
31484             currentBreakTarget = breakTarget;
31485             currentContinueTarget = continueTarget;
31486             bind(node);
31487             currentBreakTarget = saveBreakTarget;
31488             currentContinueTarget = saveContinueTarget;
31489         }
31490         function setContinueTarget(node, target) {
31491             var label = activeLabelList;
31492             while (label && node.parent.kind === 238 /* LabeledStatement */) {
31493                 label.continueTarget = target;
31494                 label = label.next;
31495                 node = node.parent;
31496             }
31497             return target;
31498         }
31499         function bindWhileStatement(node) {
31500             var preWhileLabel = setContinueTarget(node, createLoopLabel());
31501             var preBodyLabel = createBranchLabel();
31502             var postWhileLabel = createBranchLabel();
31503             addAntecedent(preWhileLabel, currentFlow);
31504             currentFlow = preWhileLabel;
31505             bindCondition(node.expression, preBodyLabel, postWhileLabel);
31506             currentFlow = finishFlowLabel(preBodyLabel);
31507             bindIterativeStatement(node.statement, postWhileLabel, preWhileLabel);
31508             addAntecedent(preWhileLabel, currentFlow);
31509             currentFlow = finishFlowLabel(postWhileLabel);
31510         }
31511         function bindDoStatement(node) {
31512             var preDoLabel = createLoopLabel();
31513             var preConditionLabel = setContinueTarget(node, createBranchLabel());
31514             var postDoLabel = createBranchLabel();
31515             addAntecedent(preDoLabel, currentFlow);
31516             currentFlow = preDoLabel;
31517             bindIterativeStatement(node.statement, postDoLabel, preConditionLabel);
31518             addAntecedent(preConditionLabel, currentFlow);
31519             currentFlow = finishFlowLabel(preConditionLabel);
31520             bindCondition(node.expression, preDoLabel, postDoLabel);
31521             currentFlow = finishFlowLabel(postDoLabel);
31522         }
31523         function bindForStatement(node) {
31524             var preLoopLabel = setContinueTarget(node, createLoopLabel());
31525             var preBodyLabel = createBranchLabel();
31526             var postLoopLabel = createBranchLabel();
31527             bind(node.initializer);
31528             addAntecedent(preLoopLabel, currentFlow);
31529             currentFlow = preLoopLabel;
31530             bindCondition(node.condition, preBodyLabel, postLoopLabel);
31531             currentFlow = finishFlowLabel(preBodyLabel);
31532             bindIterativeStatement(node.statement, postLoopLabel, preLoopLabel);
31533             bind(node.incrementor);
31534             addAntecedent(preLoopLabel, currentFlow);
31535             currentFlow = finishFlowLabel(postLoopLabel);
31536         }
31537         function bindForInOrForOfStatement(node) {
31538             var preLoopLabel = setContinueTarget(node, createLoopLabel());
31539             var postLoopLabel = createBranchLabel();
31540             bind(node.expression);
31541             addAntecedent(preLoopLabel, currentFlow);
31542             currentFlow = preLoopLabel;
31543             if (node.kind === 232 /* ForOfStatement */) {
31544                 bind(node.awaitModifier);
31545             }
31546             addAntecedent(postLoopLabel, currentFlow);
31547             bind(node.initializer);
31548             if (node.initializer.kind !== 243 /* VariableDeclarationList */) {
31549                 bindAssignmentTargetFlow(node.initializer);
31550             }
31551             bindIterativeStatement(node.statement, postLoopLabel, preLoopLabel);
31552             addAntecedent(preLoopLabel, currentFlow);
31553             currentFlow = finishFlowLabel(postLoopLabel);
31554         }
31555         function bindIfStatement(node) {
31556             var thenLabel = createBranchLabel();
31557             var elseLabel = createBranchLabel();
31558             var postIfLabel = createBranchLabel();
31559             bindCondition(node.expression, thenLabel, elseLabel);
31560             currentFlow = finishFlowLabel(thenLabel);
31561             bind(node.thenStatement);
31562             addAntecedent(postIfLabel, currentFlow);
31563             currentFlow = finishFlowLabel(elseLabel);
31564             bind(node.elseStatement);
31565             addAntecedent(postIfLabel, currentFlow);
31566             currentFlow = finishFlowLabel(postIfLabel);
31567         }
31568         function bindReturnOrThrow(node) {
31569             bind(node.expression);
31570             if (node.kind === 235 /* ReturnStatement */) {
31571                 hasExplicitReturn = true;
31572                 if (currentReturnTarget) {
31573                     addAntecedent(currentReturnTarget, currentFlow);
31574                 }
31575             }
31576             currentFlow = unreachableFlow;
31577         }
31578         function findActiveLabel(name) {
31579             for (var label = activeLabelList; label; label = label.next) {
31580                 if (label.name === name) {
31581                     return label;
31582                 }
31583             }
31584             return undefined;
31585         }
31586         function bindBreakOrContinueFlow(node, breakTarget, continueTarget) {
31587             var flowLabel = node.kind === 234 /* BreakStatement */ ? breakTarget : continueTarget;
31588             if (flowLabel) {
31589                 addAntecedent(flowLabel, currentFlow);
31590                 currentFlow = unreachableFlow;
31591             }
31592         }
31593         function bindBreakOrContinueStatement(node) {
31594             bind(node.label);
31595             if (node.label) {
31596                 var activeLabel = findActiveLabel(node.label.escapedText);
31597                 if (activeLabel) {
31598                     activeLabel.referenced = true;
31599                     bindBreakOrContinueFlow(node, activeLabel.breakTarget, activeLabel.continueTarget);
31600                 }
31601             }
31602             else {
31603                 bindBreakOrContinueFlow(node, currentBreakTarget, currentContinueTarget);
31604             }
31605         }
31606         function bindTryStatement(node) {
31607             // We conservatively assume that *any* code in the try block can cause an exception, but we only need
31608             // to track code that causes mutations (because only mutations widen the possible control flow type of
31609             // a variable). The exceptionLabel is the target label for control flows that result from exceptions.
31610             // We add all mutation flow nodes as antecedents of this label such that we can analyze them as possible
31611             // antecedents of the start of catch or finally blocks. Furthermore, we add the current control flow to
31612             // represent exceptions that occur before any mutations.
31613             var saveReturnTarget = currentReturnTarget;
31614             var saveExceptionTarget = currentExceptionTarget;
31615             var normalExitLabel = createBranchLabel();
31616             var returnLabel = createBranchLabel();
31617             var exceptionLabel = createBranchLabel();
31618             if (node.finallyBlock) {
31619                 currentReturnTarget = returnLabel;
31620             }
31621             addAntecedent(exceptionLabel, currentFlow);
31622             currentExceptionTarget = exceptionLabel;
31623             bind(node.tryBlock);
31624             addAntecedent(normalExitLabel, currentFlow);
31625             if (node.catchClause) {
31626                 // Start of catch clause is the target of exceptions from try block.
31627                 currentFlow = finishFlowLabel(exceptionLabel);
31628                 // The currentExceptionTarget now represents control flows from exceptions in the catch clause.
31629                 // Effectively, in a try-catch-finally, if an exception occurs in the try block, the catch block
31630                 // acts like a second try block.
31631                 exceptionLabel = createBranchLabel();
31632                 addAntecedent(exceptionLabel, currentFlow);
31633                 currentExceptionTarget = exceptionLabel;
31634                 bind(node.catchClause);
31635                 addAntecedent(normalExitLabel, currentFlow);
31636             }
31637             currentReturnTarget = saveReturnTarget;
31638             currentExceptionTarget = saveExceptionTarget;
31639             if (node.finallyBlock) {
31640                 // Possible ways control can reach the finally block:
31641                 // 1) Normal completion of try block of a try-finally or try-catch-finally
31642                 // 2) Normal completion of catch block (following exception in try block) of a try-catch-finally
31643                 // 3) Return in try or catch block of a try-finally or try-catch-finally
31644                 // 4) Exception in try block of a try-finally
31645                 // 5) Exception in catch block of a try-catch-finally
31646                 // When analyzing a control flow graph that starts inside a finally block we want to consider all
31647                 // five possibilities above. However, when analyzing a control flow graph that starts outside (past)
31648                 // the finally block, we only want to consider the first two (if we're past a finally block then it
31649                 // must have completed normally). Likewise, when analyzing a control flow graph from return statements
31650                 // in try or catch blocks in an IIFE, we only want to consider the third. To make this possible, we
31651                 // inject a ReduceLabel node into the control flow graph. This node contains an alternate reduced
31652                 // set of antecedents for the pre-finally label. As control flow analysis passes by a ReduceLabel
31653                 // node, the pre-finally label is temporarily switched to the reduced antecedent set.
31654                 var finallyLabel = createBranchLabel();
31655                 finallyLabel.antecedents = ts.concatenate(ts.concatenate(normalExitLabel.antecedents, exceptionLabel.antecedents), returnLabel.antecedents);
31656                 currentFlow = finallyLabel;
31657                 bind(node.finallyBlock);
31658                 if (currentFlow.flags & 1 /* Unreachable */) {
31659                     // If the end of the finally block is unreachable, the end of the entire try statement is unreachable.
31660                     currentFlow = unreachableFlow;
31661                 }
31662                 else {
31663                     // If we have an IIFE return target and return statements in the try or catch blocks, add a control
31664                     // flow that goes back through the finally block and back through only the return statements.
31665                     if (currentReturnTarget && returnLabel.antecedents) {
31666                         addAntecedent(currentReturnTarget, createReduceLabel(finallyLabel, returnLabel.antecedents, currentFlow));
31667                     }
31668                     // If the end of the finally block is reachable, but the end of the try and catch blocks are not,
31669                     // convert the current flow to unreachable. For example, 'try { return 1; } finally { ... }' should
31670                     // result in an unreachable current control flow.
31671                     currentFlow = normalExitLabel.antecedents ? createReduceLabel(finallyLabel, normalExitLabel.antecedents, currentFlow) : unreachableFlow;
31672                 }
31673             }
31674             else {
31675                 currentFlow = finishFlowLabel(normalExitLabel);
31676             }
31677         }
31678         function bindSwitchStatement(node) {
31679             var postSwitchLabel = createBranchLabel();
31680             bind(node.expression);
31681             var saveBreakTarget = currentBreakTarget;
31682             var savePreSwitchCaseFlow = preSwitchCaseFlow;
31683             currentBreakTarget = postSwitchLabel;
31684             preSwitchCaseFlow = currentFlow;
31685             bind(node.caseBlock);
31686             addAntecedent(postSwitchLabel, currentFlow);
31687             var hasDefault = ts.forEach(node.caseBlock.clauses, function (c) { return c.kind === 278 /* DefaultClause */; });
31688             // We mark a switch statement as possibly exhaustive if it has no default clause and if all
31689             // case clauses have unreachable end points (e.g. they all return). Note, we no longer need
31690             // this property in control flow analysis, it's there only for backwards compatibility.
31691             node.possiblyExhaustive = !hasDefault && !postSwitchLabel.antecedents;
31692             if (!hasDefault) {
31693                 addAntecedent(postSwitchLabel, createFlowSwitchClause(preSwitchCaseFlow, node, 0, 0));
31694             }
31695             currentBreakTarget = saveBreakTarget;
31696             preSwitchCaseFlow = savePreSwitchCaseFlow;
31697             currentFlow = finishFlowLabel(postSwitchLabel);
31698         }
31699         function bindCaseBlock(node) {
31700             var savedSubtreeTransformFlags = subtreeTransformFlags;
31701             subtreeTransformFlags = 0;
31702             var clauses = node.clauses;
31703             var isNarrowingSwitch = isNarrowingExpression(node.parent.expression);
31704             var fallthroughFlow = unreachableFlow;
31705             for (var i = 0; i < clauses.length; i++) {
31706                 var clauseStart = i;
31707                 while (!clauses[i].statements.length && i + 1 < clauses.length) {
31708                     bind(clauses[i]);
31709                     i++;
31710                 }
31711                 var preCaseLabel = createBranchLabel();
31712                 addAntecedent(preCaseLabel, isNarrowingSwitch ? createFlowSwitchClause(preSwitchCaseFlow, node.parent, clauseStart, i + 1) : preSwitchCaseFlow);
31713                 addAntecedent(preCaseLabel, fallthroughFlow);
31714                 currentFlow = finishFlowLabel(preCaseLabel);
31715                 var clause = clauses[i];
31716                 bind(clause);
31717                 fallthroughFlow = currentFlow;
31718                 if (!(currentFlow.flags & 1 /* Unreachable */) && i !== clauses.length - 1 && options.noFallthroughCasesInSwitch) {
31719                     clause.fallthroughFlowNode = currentFlow;
31720                 }
31721             }
31722             clauses.transformFlags = subtreeTransformFlags | 536870912 /* HasComputedFlags */;
31723             subtreeTransformFlags |= savedSubtreeTransformFlags;
31724         }
31725         function bindCaseClause(node) {
31726             var saveCurrentFlow = currentFlow;
31727             currentFlow = preSwitchCaseFlow;
31728             bind(node.expression);
31729             currentFlow = saveCurrentFlow;
31730             bindEach(node.statements);
31731         }
31732         function bindExpressionStatement(node) {
31733             bind(node.expression);
31734             // A top level call expression with a dotted function name and at least one argument
31735             // is potentially an assertion and is therefore included in the control flow.
31736             if (node.expression.kind === 196 /* CallExpression */) {
31737                 var call = node.expression;
31738                 if (ts.isDottedName(call.expression)) {
31739                     currentFlow = createFlowCall(currentFlow, call);
31740                 }
31741             }
31742         }
31743         function bindLabeledStatement(node) {
31744             var postStatementLabel = createBranchLabel();
31745             activeLabelList = {
31746                 next: activeLabelList,
31747                 name: node.label.escapedText,
31748                 breakTarget: postStatementLabel,
31749                 continueTarget: undefined,
31750                 referenced: false
31751             };
31752             bind(node.label);
31753             bind(node.statement);
31754             if (!activeLabelList.referenced && !options.allowUnusedLabels) {
31755                 errorOrSuggestionOnNode(ts.unusedLabelIsError(options), node.label, ts.Diagnostics.Unused_label);
31756             }
31757             activeLabelList = activeLabelList.next;
31758             addAntecedent(postStatementLabel, currentFlow);
31759             currentFlow = finishFlowLabel(postStatementLabel);
31760         }
31761         function bindDestructuringTargetFlow(node) {
31762             if (node.kind === 209 /* BinaryExpression */ && node.operatorToken.kind === 62 /* EqualsToken */) {
31763                 bindAssignmentTargetFlow(node.left);
31764             }
31765             else {
31766                 bindAssignmentTargetFlow(node);
31767             }
31768         }
31769         function bindAssignmentTargetFlow(node) {
31770             if (isNarrowableReference(node)) {
31771                 currentFlow = createFlowMutation(16 /* Assignment */, currentFlow, node);
31772             }
31773             else if (node.kind === 192 /* ArrayLiteralExpression */) {
31774                 for (var _i = 0, _a = node.elements; _i < _a.length; _i++) {
31775                     var e = _a[_i];
31776                     if (e.kind === 213 /* SpreadElement */) {
31777                         bindAssignmentTargetFlow(e.expression);
31778                     }
31779                     else {
31780                         bindDestructuringTargetFlow(e);
31781                     }
31782                 }
31783             }
31784             else if (node.kind === 193 /* ObjectLiteralExpression */) {
31785                 for (var _b = 0, _c = node.properties; _b < _c.length; _b++) {
31786                     var p = _c[_b];
31787                     if (p.kind === 281 /* PropertyAssignment */) {
31788                         bindDestructuringTargetFlow(p.initializer);
31789                     }
31790                     else if (p.kind === 282 /* ShorthandPropertyAssignment */) {
31791                         bindAssignmentTargetFlow(p.name);
31792                     }
31793                     else if (p.kind === 283 /* SpreadAssignment */) {
31794                         bindAssignmentTargetFlow(p.expression);
31795                     }
31796                 }
31797             }
31798         }
31799         function bindLogicalExpression(node, trueTarget, falseTarget) {
31800             var preRightLabel = createBranchLabel();
31801             if (node.operatorToken.kind === 55 /* AmpersandAmpersandToken */) {
31802                 bindCondition(node.left, preRightLabel, falseTarget);
31803             }
31804             else {
31805                 bindCondition(node.left, trueTarget, preRightLabel);
31806             }
31807             currentFlow = finishFlowLabel(preRightLabel);
31808             bind(node.operatorToken);
31809             bindCondition(node.right, trueTarget, falseTarget);
31810         }
31811         function bindPrefixUnaryExpressionFlow(node) {
31812             if (node.operator === 53 /* ExclamationToken */) {
31813                 var saveTrueTarget = currentTrueTarget;
31814                 currentTrueTarget = currentFalseTarget;
31815                 currentFalseTarget = saveTrueTarget;
31816                 bindEachChild(node);
31817                 currentFalseTarget = currentTrueTarget;
31818                 currentTrueTarget = saveTrueTarget;
31819             }
31820             else {
31821                 bindEachChild(node);
31822                 if (node.operator === 45 /* PlusPlusToken */ || node.operator === 46 /* MinusMinusToken */) {
31823                     bindAssignmentTargetFlow(node.operand);
31824                 }
31825             }
31826         }
31827         function bindPostfixUnaryExpressionFlow(node) {
31828             bindEachChild(node);
31829             if (node.operator === 45 /* PlusPlusToken */ || node.operator === 46 /* MinusMinusToken */) {
31830                 bindAssignmentTargetFlow(node.operand);
31831             }
31832         }
31833         var BindBinaryExpressionFlowState;
31834         (function (BindBinaryExpressionFlowState) {
31835             BindBinaryExpressionFlowState[BindBinaryExpressionFlowState["BindThenBindChildren"] = 0] = "BindThenBindChildren";
31836             BindBinaryExpressionFlowState[BindBinaryExpressionFlowState["MaybeBindLeft"] = 1] = "MaybeBindLeft";
31837             BindBinaryExpressionFlowState[BindBinaryExpressionFlowState["BindToken"] = 2] = "BindToken";
31838             BindBinaryExpressionFlowState[BindBinaryExpressionFlowState["BindRight"] = 3] = "BindRight";
31839             BindBinaryExpressionFlowState[BindBinaryExpressionFlowState["FinishBind"] = 4] = "FinishBind";
31840         })(BindBinaryExpressionFlowState || (BindBinaryExpressionFlowState = {}));
31841         function bindBinaryExpressionFlow(node) {
31842             var workStacks = {
31843                 expr: [node],
31844                 state: [1 /* MaybeBindLeft */],
31845                 inStrictMode: [undefined],
31846                 parent: [undefined],
31847                 subtreeFlags: [undefined]
31848             };
31849             var stackIndex = 0;
31850             while (stackIndex >= 0) {
31851                 node = workStacks.expr[stackIndex];
31852                 switch (workStacks.state[stackIndex]) {
31853                     case 0 /* BindThenBindChildren */: {
31854                         // This state is used only when recuring, to emulate the work that `bind` does before
31855                         // reaching `bindChildren`. A normal call to `bindBinaryExpressionFlow` will already have done this work.
31856                         node.parent = parent;
31857                         var saveInStrictMode = inStrictMode;
31858                         bindWorker(node);
31859                         var saveParent = parent;
31860                         parent = node;
31861                         var subtreeFlagsState = void 0;
31862                         // While this next part does the work of `bindChildren` before it descends into `bindChildrenWorker`
31863                         // and uses `subtreeFlagsState` to queue up the work that needs to be done once the node is bound.
31864                         if (skipTransformFlagAggregation) {
31865                             // do nothing extra
31866                         }
31867                         else if (node.transformFlags & 536870912 /* HasComputedFlags */) {
31868                             skipTransformFlagAggregation = true;
31869                             subtreeFlagsState = -1;
31870                         }
31871                         else {
31872                             var savedSubtreeTransformFlags = subtreeTransformFlags;
31873                             subtreeTransformFlags = 0;
31874                             subtreeFlagsState = savedSubtreeTransformFlags;
31875                         }
31876                         advanceState(1 /* MaybeBindLeft */, saveInStrictMode, saveParent, subtreeFlagsState);
31877                         break;
31878                     }
31879                     case 1 /* MaybeBindLeft */: {
31880                         var operator = node.operatorToken.kind;
31881                         // TODO: bindLogicalExpression is recursive - if we want to handle deeply nested `&&` expressions
31882                         // we'll need to handle the `bindLogicalExpression` scenarios in this state machine, too
31883                         // For now, though, since the common cases are chained `+`, leaving it recursive is fine
31884                         if (operator === 55 /* AmpersandAmpersandToken */ || operator === 56 /* BarBarToken */ || operator === 60 /* QuestionQuestionToken */) {
31885                             if (isTopLevelLogicalExpression(node)) {
31886                                 var postExpressionLabel = createBranchLabel();
31887                                 bindLogicalExpression(node, postExpressionLabel, postExpressionLabel);
31888                                 currentFlow = finishFlowLabel(postExpressionLabel);
31889                             }
31890                             else {
31891                                 bindLogicalExpression(node, currentTrueTarget, currentFalseTarget);
31892                             }
31893                             completeNode();
31894                         }
31895                         else {
31896                             advanceState(2 /* BindToken */);
31897                             maybeBind(node.left);
31898                         }
31899                         break;
31900                     }
31901                     case 2 /* BindToken */: {
31902                         advanceState(3 /* BindRight */);
31903                         maybeBind(node.operatorToken);
31904                         break;
31905                     }
31906                     case 3 /* BindRight */: {
31907                         advanceState(4 /* FinishBind */);
31908                         maybeBind(node.right);
31909                         break;
31910                     }
31911                     case 4 /* FinishBind */: {
31912                         var operator = node.operatorToken.kind;
31913                         if (ts.isAssignmentOperator(operator) && !ts.isAssignmentTarget(node)) {
31914                             bindAssignmentTargetFlow(node.left);
31915                             if (operator === 62 /* EqualsToken */ && node.left.kind === 195 /* ElementAccessExpression */) {
31916                                 var elementAccess = node.left;
31917                                 if (isNarrowableOperand(elementAccess.expression)) {
31918                                     currentFlow = createFlowMutation(256 /* ArrayMutation */, currentFlow, node);
31919                                 }
31920                             }
31921                         }
31922                         completeNode();
31923                         break;
31924                     }
31925                     default: return ts.Debug.fail("Invalid state " + workStacks.state[stackIndex] + " for bindBinaryExpressionFlow");
31926                 }
31927             }
31928             /**
31929              * Note that `advanceState` sets the _current_ head state, and that `maybeBind` potentially pushes on a new
31930              * head state; so `advanceState` must be called before any `maybeBind` during a state's execution.
31931              */
31932             function advanceState(state, isInStrictMode, parent, subtreeFlags) {
31933                 workStacks.state[stackIndex] = state;
31934                 if (isInStrictMode !== undefined) {
31935                     workStacks.inStrictMode[stackIndex] = isInStrictMode;
31936                 }
31937                 if (parent !== undefined) {
31938                     workStacks.parent[stackIndex] = parent;
31939                 }
31940                 if (subtreeFlags !== undefined) {
31941                     workStacks.subtreeFlags[stackIndex] = subtreeFlags;
31942                 }
31943             }
31944             function completeNode() {
31945                 if (workStacks.inStrictMode[stackIndex] !== undefined) {
31946                     if (workStacks.subtreeFlags[stackIndex] === -1) {
31947                         skipTransformFlagAggregation = false;
31948                         subtreeTransformFlags |= node.transformFlags & ~getTransformFlagsSubtreeExclusions(node.kind);
31949                     }
31950                     else if (workStacks.subtreeFlags[stackIndex] !== undefined) {
31951                         subtreeTransformFlags = workStacks.subtreeFlags[stackIndex] | computeTransformFlagsForNode(node, subtreeTransformFlags);
31952                     }
31953                     inStrictMode = workStacks.inStrictMode[stackIndex];
31954                     parent = workStacks.parent[stackIndex];
31955                 }
31956                 stackIndex--;
31957             }
31958             /**
31959              * If `node` is a BinaryExpression, adds it to the local work stack, otherwise recursively binds it
31960              */
31961             function maybeBind(node) {
31962                 if (node && ts.isBinaryExpression(node)) {
31963                     stackIndex++;
31964                     workStacks.expr[stackIndex] = node;
31965                     workStacks.state[stackIndex] = 0 /* BindThenBindChildren */;
31966                     workStacks.inStrictMode[stackIndex] = undefined;
31967                     workStacks.parent[stackIndex] = undefined;
31968                     workStacks.subtreeFlags[stackIndex] = undefined;
31969                 }
31970                 else {
31971                     bind(node);
31972                 }
31973             }
31974         }
31975         function bindDeleteExpressionFlow(node) {
31976             bindEachChild(node);
31977             if (node.expression.kind === 194 /* PropertyAccessExpression */) {
31978                 bindAssignmentTargetFlow(node.expression);
31979             }
31980         }
31981         function bindConditionalExpressionFlow(node) {
31982             var trueLabel = createBranchLabel();
31983             var falseLabel = createBranchLabel();
31984             var postExpressionLabel = createBranchLabel();
31985             bindCondition(node.condition, trueLabel, falseLabel);
31986             currentFlow = finishFlowLabel(trueLabel);
31987             bind(node.questionToken);
31988             bind(node.whenTrue);
31989             addAntecedent(postExpressionLabel, currentFlow);
31990             currentFlow = finishFlowLabel(falseLabel);
31991             bind(node.colonToken);
31992             bind(node.whenFalse);
31993             addAntecedent(postExpressionLabel, currentFlow);
31994             currentFlow = finishFlowLabel(postExpressionLabel);
31995         }
31996         function bindInitializedVariableFlow(node) {
31997             var name = !ts.isOmittedExpression(node) ? node.name : undefined;
31998             if (ts.isBindingPattern(name)) {
31999                 for (var _i = 0, _a = name.elements; _i < _a.length; _i++) {
32000                     var child = _a[_i];
32001                     bindInitializedVariableFlow(child);
32002                 }
32003             }
32004             else {
32005                 currentFlow = createFlowMutation(16 /* Assignment */, currentFlow, node);
32006             }
32007         }
32008         function bindVariableDeclarationFlow(node) {
32009             bindEachChild(node);
32010             if (node.initializer || ts.isForInOrOfStatement(node.parent.parent)) {
32011                 bindInitializedVariableFlow(node);
32012             }
32013         }
32014         function bindJSDocTypeAlias(node) {
32015             node.tagName.parent = node;
32016             if (node.kind !== 316 /* JSDocEnumTag */ && node.fullName) {
32017                 setParentPointers(node, node.fullName);
32018             }
32019         }
32020         function bindJSDocClassTag(node) {
32021             bindEachChild(node);
32022             var host = ts.getHostSignatureFromJSDoc(node);
32023             if (host && host.kind !== 161 /* MethodDeclaration */) {
32024                 addDeclarationToSymbol(host.symbol, host, 32 /* Class */);
32025             }
32026         }
32027         function bindOptionalExpression(node, trueTarget, falseTarget) {
32028             doWithConditionalBranches(bind, node, trueTarget, falseTarget);
32029             if (!ts.isOptionalChain(node) || ts.isOutermostOptionalChain(node)) {
32030                 addAntecedent(trueTarget, createFlowCondition(32 /* TrueCondition */, currentFlow, node));
32031                 addAntecedent(falseTarget, createFlowCondition(64 /* FalseCondition */, currentFlow, node));
32032             }
32033         }
32034         function bindOptionalChainRest(node) {
32035             switch (node.kind) {
32036                 case 194 /* PropertyAccessExpression */:
32037                     bind(node.questionDotToken);
32038                     bind(node.name);
32039                     break;
32040                 case 195 /* ElementAccessExpression */:
32041                     bind(node.questionDotToken);
32042                     bind(node.argumentExpression);
32043                     break;
32044                 case 196 /* CallExpression */:
32045                     bind(node.questionDotToken);
32046                     bindEach(node.typeArguments);
32047                     bindEach(node.arguments);
32048                     break;
32049             }
32050         }
32051         function bindOptionalChain(node, trueTarget, falseTarget) {
32052             // For an optional chain, we emulate the behavior of a logical expression:
32053             //
32054             // a?.b         -> a && a.b
32055             // a?.b.c       -> a && a.b.c
32056             // a?.b?.c      -> a && a.b && a.b.c
32057             // a?.[x = 1]   -> a && a[x = 1]
32058             //
32059             // To do this we descend through the chain until we reach the root of a chain (the expression with a `?.`)
32060             // and build it's CFA graph as if it were the first condition (`a && ...`). Then we bind the rest
32061             // of the node as part of the "true" branch, and continue to do so as we ascend back up to the outermost
32062             // chain node. We then treat the entire node as the right side of the expression.
32063             var preChainLabel = ts.isOptionalChainRoot(node) ? createBranchLabel() : undefined;
32064             bindOptionalExpression(node.expression, preChainLabel || trueTarget, falseTarget);
32065             if (preChainLabel) {
32066                 currentFlow = finishFlowLabel(preChainLabel);
32067             }
32068             doWithConditionalBranches(bindOptionalChainRest, node, trueTarget, falseTarget);
32069             if (ts.isOutermostOptionalChain(node)) {
32070                 addAntecedent(trueTarget, createFlowCondition(32 /* TrueCondition */, currentFlow, node));
32071                 addAntecedent(falseTarget, createFlowCondition(64 /* FalseCondition */, currentFlow, node));
32072             }
32073         }
32074         function bindOptionalChainFlow(node) {
32075             if (isTopLevelLogicalExpression(node)) {
32076                 var postExpressionLabel = createBranchLabel();
32077                 bindOptionalChain(node, postExpressionLabel, postExpressionLabel);
32078                 currentFlow = finishFlowLabel(postExpressionLabel);
32079             }
32080             else {
32081                 bindOptionalChain(node, currentTrueTarget, currentFalseTarget);
32082             }
32083         }
32084         function bindNonNullExpressionFlow(node) {
32085             if (ts.isOptionalChain(node)) {
32086                 bindOptionalChainFlow(node);
32087             }
32088             else {
32089                 bindEachChild(node);
32090             }
32091         }
32092         function bindAccessExpressionFlow(node) {
32093             if (ts.isOptionalChain(node)) {
32094                 bindOptionalChainFlow(node);
32095             }
32096             else {
32097                 bindEachChild(node);
32098             }
32099         }
32100         function bindCallExpressionFlow(node) {
32101             if (ts.isOptionalChain(node)) {
32102                 bindOptionalChainFlow(node);
32103             }
32104             else {
32105                 // If the target of the call expression is a function expression or arrow function we have
32106                 // an immediately invoked function expression (IIFE). Initialize the flowNode property to
32107                 // the current control flow (which includes evaluation of the IIFE arguments).
32108                 var expr = ts.skipParentheses(node.expression);
32109                 if (expr.kind === 201 /* FunctionExpression */ || expr.kind === 202 /* ArrowFunction */) {
32110                     bindEach(node.typeArguments);
32111                     bindEach(node.arguments);
32112                     bind(node.expression);
32113                 }
32114                 else {
32115                     bindEachChild(node);
32116                 }
32117             }
32118             if (node.expression.kind === 194 /* PropertyAccessExpression */) {
32119                 var propertyAccess = node.expression;
32120                 if (ts.isIdentifier(propertyAccess.name) && isNarrowableOperand(propertyAccess.expression) && ts.isPushOrUnshiftIdentifier(propertyAccess.name)) {
32121                     currentFlow = createFlowMutation(256 /* ArrayMutation */, currentFlow, node);
32122                 }
32123             }
32124         }
32125         function getContainerFlags(node) {
32126             switch (node.kind) {
32127                 case 214 /* ClassExpression */:
32128                 case 245 /* ClassDeclaration */:
32129                 case 248 /* EnumDeclaration */:
32130                 case 193 /* ObjectLiteralExpression */:
32131                 case 173 /* TypeLiteral */:
32132                 case 304 /* JSDocTypeLiteral */:
32133                 case 274 /* JsxAttributes */:
32134                     return 1 /* IsContainer */;
32135                 case 246 /* InterfaceDeclaration */:
32136                     return 1 /* IsContainer */ | 64 /* IsInterface */;
32137                 case 249 /* ModuleDeclaration */:
32138                 case 247 /* TypeAliasDeclaration */:
32139                 case 186 /* MappedType */:
32140                     return 1 /* IsContainer */ | 32 /* HasLocals */;
32141                 case 290 /* SourceFile */:
32142                     return 1 /* IsContainer */ | 4 /* IsControlFlowContainer */ | 32 /* HasLocals */;
32143                 case 161 /* MethodDeclaration */:
32144                     if (ts.isObjectLiteralOrClassExpressionMethod(node)) {
32145                         return 1 /* IsContainer */ | 4 /* IsControlFlowContainer */ | 32 /* HasLocals */ | 8 /* IsFunctionLike */ | 128 /* IsObjectLiteralOrClassExpressionMethod */;
32146                     }
32147                 // falls through
32148                 case 162 /* Constructor */:
32149                 case 244 /* FunctionDeclaration */:
32150                 case 160 /* MethodSignature */:
32151                 case 163 /* GetAccessor */:
32152                 case 164 /* SetAccessor */:
32153                 case 165 /* CallSignature */:
32154                 case 305 /* JSDocSignature */:
32155                 case 300 /* JSDocFunctionType */:
32156                 case 170 /* FunctionType */:
32157                 case 166 /* ConstructSignature */:
32158                 case 167 /* IndexSignature */:
32159                 case 171 /* ConstructorType */:
32160                     return 1 /* IsContainer */ | 4 /* IsControlFlowContainer */ | 32 /* HasLocals */ | 8 /* IsFunctionLike */;
32161                 case 201 /* FunctionExpression */:
32162                 case 202 /* ArrowFunction */:
32163                     return 1 /* IsContainer */ | 4 /* IsControlFlowContainer */ | 32 /* HasLocals */ | 8 /* IsFunctionLike */ | 16 /* IsFunctionExpression */;
32164                 case 250 /* ModuleBlock */:
32165                     return 4 /* IsControlFlowContainer */;
32166                 case 159 /* PropertyDeclaration */:
32167                     return node.initializer ? 4 /* IsControlFlowContainer */ : 0;
32168                 case 280 /* CatchClause */:
32169                 case 230 /* ForStatement */:
32170                 case 231 /* ForInStatement */:
32171                 case 232 /* ForOfStatement */:
32172                 case 251 /* CaseBlock */:
32173                     return 2 /* IsBlockScopedContainer */;
32174                 case 223 /* Block */:
32175                     // do not treat blocks directly inside a function as a block-scoped-container.
32176                     // Locals that reside in this block should go to the function locals. Otherwise 'x'
32177                     // would not appear to be a redeclaration of a block scoped local in the following
32178                     // example:
32179                     //
32180                     //      function foo() {
32181                     //          var x;
32182                     //          let x;
32183                     //      }
32184                     //
32185                     // If we placed 'var x' into the function locals and 'let x' into the locals of
32186                     // the block, then there would be no collision.
32187                     //
32188                     // By not creating a new block-scoped-container here, we ensure that both 'var x'
32189                     // and 'let x' go into the Function-container's locals, and we do get a collision
32190                     // conflict.
32191                     return ts.isFunctionLike(node.parent) ? 0 /* None */ : 2 /* IsBlockScopedContainer */;
32192             }
32193             return 0 /* None */;
32194         }
32195         function addToContainerChain(next) {
32196             if (lastContainer) {
32197                 lastContainer.nextContainer = next;
32198             }
32199             lastContainer = next;
32200         }
32201         function declareSymbolAndAddToSymbolTable(node, symbolFlags, symbolExcludes) {
32202             switch (container.kind) {
32203                 // Modules, source files, and classes need specialized handling for how their
32204                 // members are declared (for example, a member of a class will go into a specific
32205                 // symbol table depending on if it is static or not). We defer to specialized
32206                 // handlers to take care of declaring these child members.
32207                 case 249 /* ModuleDeclaration */:
32208                     return declareModuleMember(node, symbolFlags, symbolExcludes);
32209                 case 290 /* SourceFile */:
32210                     return declareSourceFileMember(node, symbolFlags, symbolExcludes);
32211                 case 214 /* ClassExpression */:
32212                 case 245 /* ClassDeclaration */:
32213                     return declareClassMember(node, symbolFlags, symbolExcludes);
32214                 case 248 /* EnumDeclaration */:
32215                     return declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes);
32216                 case 173 /* TypeLiteral */:
32217                 case 304 /* JSDocTypeLiteral */:
32218                 case 193 /* ObjectLiteralExpression */:
32219                 case 246 /* InterfaceDeclaration */:
32220                 case 274 /* JsxAttributes */:
32221                     // Interface/Object-types always have their children added to the 'members' of
32222                     // their container. They are only accessible through an instance of their
32223                     // container, and are never in scope otherwise (even inside the body of the
32224                     // object / type / interface declaring them). An exception is type parameters,
32225                     // which are in scope without qualification (similar to 'locals').
32226                     return declareSymbol(container.symbol.members, container.symbol, node, symbolFlags, symbolExcludes);
32227                 case 170 /* FunctionType */:
32228                 case 171 /* ConstructorType */:
32229                 case 165 /* CallSignature */:
32230                 case 166 /* ConstructSignature */:
32231                 case 305 /* JSDocSignature */:
32232                 case 167 /* IndexSignature */:
32233                 case 161 /* MethodDeclaration */:
32234                 case 160 /* MethodSignature */:
32235                 case 162 /* Constructor */:
32236                 case 163 /* GetAccessor */:
32237                 case 164 /* SetAccessor */:
32238                 case 244 /* FunctionDeclaration */:
32239                 case 201 /* FunctionExpression */:
32240                 case 202 /* ArrowFunction */:
32241                 case 300 /* JSDocFunctionType */:
32242                 case 322 /* JSDocTypedefTag */:
32243                 case 315 /* JSDocCallbackTag */:
32244                 case 247 /* TypeAliasDeclaration */:
32245                 case 186 /* MappedType */:
32246                     // All the children of these container types are never visible through another
32247                     // symbol (i.e. through another symbol's 'exports' or 'members').  Instead,
32248                     // they're only accessed 'lexically' (i.e. from code that exists underneath
32249                     // their container in the tree). To accomplish this, we simply add their declared
32250                     // symbol to the 'locals' of the container.  These symbols can then be found as
32251                     // the type checker walks up the containers, checking them for matching names.
32252                     return declareSymbol(container.locals, /*parent*/ undefined, node, symbolFlags, symbolExcludes);
32253             }
32254         }
32255         function declareClassMember(node, symbolFlags, symbolExcludes) {
32256             return ts.hasModifier(node, 32 /* Static */)
32257                 ? declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes)
32258                 : declareSymbol(container.symbol.members, container.symbol, node, symbolFlags, symbolExcludes);
32259         }
32260         function declareSourceFileMember(node, symbolFlags, symbolExcludes) {
32261             return ts.isExternalModule(file)
32262                 ? declareModuleMember(node, symbolFlags, symbolExcludes)
32263                 : declareSymbol(file.locals, /*parent*/ undefined, node, symbolFlags, symbolExcludes);
32264         }
32265         function hasExportDeclarations(node) {
32266             var body = ts.isSourceFile(node) ? node : ts.tryCast(node.body, ts.isModuleBlock);
32267             return !!body && body.statements.some(function (s) { return ts.isExportDeclaration(s) || ts.isExportAssignment(s); });
32268         }
32269         function setExportContextFlag(node) {
32270             // A declaration source file or ambient module declaration that contains no export declarations (but possibly regular
32271             // declarations with export modifiers) is an export context in which declarations are implicitly exported.
32272             if (node.flags & 8388608 /* Ambient */ && !hasExportDeclarations(node)) {
32273                 node.flags |= 64 /* ExportContext */;
32274             }
32275             else {
32276                 node.flags &= ~64 /* ExportContext */;
32277             }
32278         }
32279         function bindModuleDeclaration(node) {
32280             setExportContextFlag(node);
32281             if (ts.isAmbientModule(node)) {
32282                 if (ts.hasModifier(node, 1 /* Export */)) {
32283                     errorOnFirstToken(node, ts.Diagnostics.export_modifier_cannot_be_applied_to_ambient_modules_and_module_augmentations_since_they_are_always_visible);
32284                 }
32285                 if (ts.isModuleAugmentationExternal(node)) {
32286                     declareModuleSymbol(node);
32287                 }
32288                 else {
32289                     var pattern = void 0;
32290                     if (node.name.kind === 10 /* StringLiteral */) {
32291                         var text = node.name.text;
32292                         if (ts.hasZeroOrOneAsteriskCharacter(text)) {
32293                             pattern = ts.tryParsePattern(text);
32294                         }
32295                         else {
32296                             errorOnFirstToken(node.name, ts.Diagnostics.Pattern_0_can_have_at_most_one_Asterisk_character, text);
32297                         }
32298                     }
32299                     var symbol = declareSymbolAndAddToSymbolTable(node, 512 /* ValueModule */, 110735 /* ValueModuleExcludes */);
32300                     file.patternAmbientModules = ts.append(file.patternAmbientModules, pattern && { pattern: pattern, symbol: symbol });
32301                 }
32302             }
32303             else {
32304                 var state = declareModuleSymbol(node);
32305                 if (state !== 0 /* NonInstantiated */) {
32306                     var symbol = node.symbol;
32307                     // if module was already merged with some function, class or non-const enum, treat it as non-const-enum-only
32308                     symbol.constEnumOnlyModule = (!(symbol.flags & (16 /* Function */ | 32 /* Class */ | 256 /* RegularEnum */)))
32309                         // Current must be `const enum` only
32310                         && state === 2 /* ConstEnumOnly */
32311                         // Can't have been set to 'false' in a previous merged symbol. ('undefined' OK)
32312                         && symbol.constEnumOnlyModule !== false;
32313                 }
32314             }
32315         }
32316         function declareModuleSymbol(node) {
32317             var state = getModuleInstanceState(node);
32318             var instantiated = state !== 0 /* NonInstantiated */;
32319             declareSymbolAndAddToSymbolTable(node, instantiated ? 512 /* ValueModule */ : 1024 /* NamespaceModule */, instantiated ? 110735 /* ValueModuleExcludes */ : 0 /* NamespaceModuleExcludes */);
32320             return state;
32321         }
32322         function bindFunctionOrConstructorType(node) {
32323             // For a given function symbol "<...>(...) => T" we want to generate a symbol identical
32324             // to the one we would get for: { <...>(...): T }
32325             //
32326             // We do that by making an anonymous type literal symbol, and then setting the function
32327             // symbol as its sole member. To the rest of the system, this symbol will be indistinguishable
32328             // from an actual type literal symbol you would have gotten had you used the long form.
32329             var symbol = createSymbol(131072 /* Signature */, getDeclarationName(node)); // TODO: GH#18217
32330             addDeclarationToSymbol(symbol, node, 131072 /* Signature */);
32331             var typeLiteralSymbol = createSymbol(2048 /* TypeLiteral */, "__type" /* Type */);
32332             addDeclarationToSymbol(typeLiteralSymbol, node, 2048 /* TypeLiteral */);
32333             typeLiteralSymbol.members = ts.createSymbolTable();
32334             typeLiteralSymbol.members.set(symbol.escapedName, symbol);
32335         }
32336         function bindObjectLiteralExpression(node) {
32337             var ElementKind;
32338             (function (ElementKind) {
32339                 ElementKind[ElementKind["Property"] = 1] = "Property";
32340                 ElementKind[ElementKind["Accessor"] = 2] = "Accessor";
32341             })(ElementKind || (ElementKind = {}));
32342             if (inStrictMode && !ts.isAssignmentTarget(node)) {
32343                 var seen = ts.createUnderscoreEscapedMap();
32344                 for (var _i = 0, _a = node.properties; _i < _a.length; _i++) {
32345                     var prop = _a[_i];
32346                     if (prop.kind === 283 /* SpreadAssignment */ || prop.name.kind !== 75 /* Identifier */) {
32347                         continue;
32348                     }
32349                     var identifier = prop.name;
32350                     // ECMA-262 11.1.5 Object Initializer
32351                     // If previous is not undefined then throw a SyntaxError exception if any of the following conditions are true
32352                     // a.This production is contained in strict code and IsDataDescriptor(previous) is true and
32353                     // IsDataDescriptor(propId.descriptor) is true.
32354                     //    b.IsDataDescriptor(previous) is true and IsAccessorDescriptor(propId.descriptor) is true.
32355                     //    c.IsAccessorDescriptor(previous) is true and IsDataDescriptor(propId.descriptor) is true.
32356                     //    d.IsAccessorDescriptor(previous) is true and IsAccessorDescriptor(propId.descriptor) is true
32357                     // and either both previous and propId.descriptor have[[Get]] fields or both previous and propId.descriptor have[[Set]] fields
32358                     var currentKind = prop.kind === 281 /* PropertyAssignment */ || prop.kind === 282 /* ShorthandPropertyAssignment */ || prop.kind === 161 /* MethodDeclaration */
32359                         ? 1 /* Property */
32360                         : 2 /* Accessor */;
32361                     var existingKind = seen.get(identifier.escapedText);
32362                     if (!existingKind) {
32363                         seen.set(identifier.escapedText, currentKind);
32364                         continue;
32365                     }
32366                     if (currentKind === 1 /* Property */ && existingKind === 1 /* Property */) {
32367                         var span = ts.getErrorSpanForNode(file, identifier);
32368                         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));
32369                     }
32370                 }
32371             }
32372             return bindAnonymousDeclaration(node, 4096 /* ObjectLiteral */, "__object" /* Object */);
32373         }
32374         function bindJsxAttributes(node) {
32375             return bindAnonymousDeclaration(node, 4096 /* ObjectLiteral */, "__jsxAttributes" /* JSXAttributes */);
32376         }
32377         function bindJsxAttribute(node, symbolFlags, symbolExcludes) {
32378             return declareSymbolAndAddToSymbolTable(node, symbolFlags, symbolExcludes);
32379         }
32380         function bindAnonymousDeclaration(node, symbolFlags, name) {
32381             var symbol = createSymbol(symbolFlags, name);
32382             if (symbolFlags & (8 /* EnumMember */ | 106500 /* ClassMember */)) {
32383                 symbol.parent = container.symbol;
32384             }
32385             addDeclarationToSymbol(symbol, node, symbolFlags);
32386             return symbol;
32387         }
32388         function bindBlockScopedDeclaration(node, symbolFlags, symbolExcludes) {
32389             switch (blockScopeContainer.kind) {
32390                 case 249 /* ModuleDeclaration */:
32391                     declareModuleMember(node, symbolFlags, symbolExcludes);
32392                     break;
32393                 case 290 /* SourceFile */:
32394                     if (ts.isExternalOrCommonJsModule(container)) {
32395                         declareModuleMember(node, symbolFlags, symbolExcludes);
32396                         break;
32397                     }
32398                 // falls through
32399                 default:
32400                     if (!blockScopeContainer.locals) {
32401                         blockScopeContainer.locals = ts.createSymbolTable();
32402                         addToContainerChain(blockScopeContainer);
32403                     }
32404                     declareSymbol(blockScopeContainer.locals, /*parent*/ undefined, node, symbolFlags, symbolExcludes);
32405             }
32406         }
32407         function delayedBindJSDocTypedefTag() {
32408             if (!delayedTypeAliases) {
32409                 return;
32410             }
32411             var saveContainer = container;
32412             var saveLastContainer = lastContainer;
32413             var saveBlockScopeContainer = blockScopeContainer;
32414             var saveParent = parent;
32415             var saveCurrentFlow = currentFlow;
32416             for (var _i = 0, delayedTypeAliases_1 = delayedTypeAliases; _i < delayedTypeAliases_1.length; _i++) {
32417                 var typeAlias = delayedTypeAliases_1[_i];
32418                 var host = ts.getJSDocHost(typeAlias);
32419                 container = ts.findAncestor(host.parent, function (n) { return !!(getContainerFlags(n) & 1 /* IsContainer */); }) || file;
32420                 blockScopeContainer = ts.getEnclosingBlockScopeContainer(host) || file;
32421                 currentFlow = initFlowNode({ flags: 2 /* Start */ });
32422                 parent = typeAlias;
32423                 bind(typeAlias.typeExpression);
32424                 var declName = ts.getNameOfDeclaration(typeAlias);
32425                 if ((ts.isJSDocEnumTag(typeAlias) || !typeAlias.fullName) && declName && ts.isPropertyAccessEntityNameExpression(declName.parent)) {
32426                     // typedef anchored to an A.B.C assignment - we need to bind into B's namespace under name C
32427                     var isTopLevel = isTopLevelNamespaceAssignment(declName.parent);
32428                     if (isTopLevel) {
32429                         bindPotentiallyMissingNamespaces(file.symbol, declName.parent, isTopLevel, !!ts.findAncestor(declName, function (d) { return ts.isPropertyAccessExpression(d) && d.name.escapedText === "prototype"; }), /*containerIsClass*/ false);
32430                         var oldContainer = container;
32431                         switch (ts.getAssignmentDeclarationPropertyAccessKind(declName.parent)) {
32432                             case 1 /* ExportsProperty */:
32433                             case 2 /* ModuleExports */:
32434                                 if (!ts.isExternalOrCommonJsModule(file)) {
32435                                     container = undefined;
32436                                 }
32437                                 else {
32438                                     container = file;
32439                                 }
32440                                 break;
32441                             case 4 /* ThisProperty */:
32442                                 container = declName.parent.expression;
32443                                 break;
32444                             case 3 /* PrototypeProperty */:
32445                                 container = declName.parent.expression.name;
32446                                 break;
32447                             case 5 /* Property */:
32448                                 container = isExportsOrModuleExportsOrAlias(file, declName.parent.expression) ? file
32449                                     : ts.isPropertyAccessExpression(declName.parent.expression) ? declName.parent.expression.name
32450                                         : declName.parent.expression;
32451                                 break;
32452                             case 0 /* None */:
32453                                 return ts.Debug.fail("Shouldn't have detected typedef or enum on non-assignment declaration");
32454                         }
32455                         if (container) {
32456                             declareModuleMember(typeAlias, 524288 /* TypeAlias */, 788968 /* TypeAliasExcludes */);
32457                         }
32458                         container = oldContainer;
32459                     }
32460                 }
32461                 else if (ts.isJSDocEnumTag(typeAlias) || !typeAlias.fullName || typeAlias.fullName.kind === 75 /* Identifier */) {
32462                     parent = typeAlias.parent;
32463                     bindBlockScopedDeclaration(typeAlias, 524288 /* TypeAlias */, 788968 /* TypeAliasExcludes */);
32464                 }
32465                 else {
32466                     bind(typeAlias.fullName);
32467                 }
32468             }
32469             container = saveContainer;
32470             lastContainer = saveLastContainer;
32471             blockScopeContainer = saveBlockScopeContainer;
32472             parent = saveParent;
32473             currentFlow = saveCurrentFlow;
32474         }
32475         // The binder visits every node in the syntax tree so it is a convenient place to perform a single localized
32476         // check for reserved words used as identifiers in strict mode code.
32477         function checkStrictModeIdentifier(node) {
32478             if (inStrictMode &&
32479                 node.originalKeywordKind >= 113 /* FirstFutureReservedWord */ &&
32480                 node.originalKeywordKind <= 121 /* LastFutureReservedWord */ &&
32481                 !ts.isIdentifierName(node) &&
32482                 !(node.flags & 8388608 /* Ambient */) &&
32483                 !(node.flags & 4194304 /* JSDoc */)) {
32484                 // Report error only if there are no parse errors in file
32485                 if (!file.parseDiagnostics.length) {
32486                     file.bindDiagnostics.push(createDiagnosticForNode(node, getStrictModeIdentifierMessage(node), ts.declarationNameToString(node)));
32487                 }
32488             }
32489         }
32490         function getStrictModeIdentifierMessage(node) {
32491             // Provide specialized messages to help the user understand why we think they're in
32492             // strict mode.
32493             if (ts.getContainingClass(node)) {
32494                 return ts.Diagnostics.Identifier_expected_0_is_a_reserved_word_in_strict_mode_Class_definitions_are_automatically_in_strict_mode;
32495             }
32496             if (file.externalModuleIndicator) {
32497                 return ts.Diagnostics.Identifier_expected_0_is_a_reserved_word_in_strict_mode_Modules_are_automatically_in_strict_mode;
32498             }
32499             return ts.Diagnostics.Identifier_expected_0_is_a_reserved_word_in_strict_mode;
32500         }
32501         // The binder visits every node, so this is a good place to check for
32502         // the reserved private name (there is only one)
32503         function checkPrivateIdentifier(node) {
32504             if (node.escapedText === "#constructor") {
32505                 // Report error only if there are no parse errors in file
32506                 if (!file.parseDiagnostics.length) {
32507                     file.bindDiagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.constructor_is_a_reserved_word, ts.declarationNameToString(node)));
32508                 }
32509             }
32510         }
32511         function checkStrictModeBinaryExpression(node) {
32512             if (inStrictMode && ts.isLeftHandSideExpression(node.left) && ts.isAssignmentOperator(node.operatorToken.kind)) {
32513                 // ECMA 262 (Annex C) The identifier eval or arguments may not appear as the LeftHandSideExpression of an
32514                 // Assignment operator(11.13) or of a PostfixExpression(11.3)
32515                 checkStrictModeEvalOrArguments(node, node.left);
32516             }
32517         }
32518         function checkStrictModeCatchClause(node) {
32519             // It is a SyntaxError if a TryStatement with a Catch occurs within strict code and the Identifier of the
32520             // Catch production is eval or arguments
32521             if (inStrictMode && node.variableDeclaration) {
32522                 checkStrictModeEvalOrArguments(node, node.variableDeclaration.name);
32523             }
32524         }
32525         function checkStrictModeDeleteExpression(node) {
32526             // Grammar checking
32527             if (inStrictMode && node.expression.kind === 75 /* Identifier */) {
32528                 // When a delete operator occurs within strict mode code, a SyntaxError is thrown if its
32529                 // UnaryExpression is a direct reference to a variable, function argument, or function name
32530                 var span = ts.getErrorSpanForNode(file, node.expression);
32531                 file.bindDiagnostics.push(ts.createFileDiagnostic(file, span.start, span.length, ts.Diagnostics.delete_cannot_be_called_on_an_identifier_in_strict_mode));
32532             }
32533         }
32534         function isEvalOrArgumentsIdentifier(node) {
32535             return ts.isIdentifier(node) && (node.escapedText === "eval" || node.escapedText === "arguments");
32536         }
32537         function checkStrictModeEvalOrArguments(contextNode, name) {
32538             if (name && name.kind === 75 /* Identifier */) {
32539                 var identifier = name;
32540                 if (isEvalOrArgumentsIdentifier(identifier)) {
32541                     // We check first if the name is inside class declaration or class expression; if so give explicit message
32542                     // otherwise report generic error message.
32543                     var span = ts.getErrorSpanForNode(file, name);
32544                     file.bindDiagnostics.push(ts.createFileDiagnostic(file, span.start, span.length, getStrictModeEvalOrArgumentsMessage(contextNode), ts.idText(identifier)));
32545                 }
32546             }
32547         }
32548         function getStrictModeEvalOrArgumentsMessage(node) {
32549             // Provide specialized messages to help the user understand why we think they're in
32550             // strict mode.
32551             if (ts.getContainingClass(node)) {
32552                 return ts.Diagnostics.Invalid_use_of_0_Class_definitions_are_automatically_in_strict_mode;
32553             }
32554             if (file.externalModuleIndicator) {
32555                 return ts.Diagnostics.Invalid_use_of_0_Modules_are_automatically_in_strict_mode;
32556             }
32557             return ts.Diagnostics.Invalid_use_of_0_in_strict_mode;
32558         }
32559         function checkStrictModeFunctionName(node) {
32560             if (inStrictMode) {
32561                 // It is a SyntaxError if the identifier eval or arguments appears within a FormalParameterList of a strict mode FunctionDeclaration or FunctionExpression (13.1))
32562                 checkStrictModeEvalOrArguments(node, node.name);
32563             }
32564         }
32565         function getStrictModeBlockScopeFunctionDeclarationMessage(node) {
32566             // Provide specialized messages to help the user understand why we think they're in
32567             // strict mode.
32568             if (ts.getContainingClass(node)) {
32569                 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;
32570             }
32571             if (file.externalModuleIndicator) {
32572                 return ts.Diagnostics.Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Modules_are_automatically_in_strict_mode;
32573             }
32574             return ts.Diagnostics.Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5;
32575         }
32576         function checkStrictModeFunctionDeclaration(node) {
32577             if (languageVersion < 2 /* ES2015 */) {
32578                 // Report error if function is not top level function declaration
32579                 if (blockScopeContainer.kind !== 290 /* SourceFile */ &&
32580                     blockScopeContainer.kind !== 249 /* ModuleDeclaration */ &&
32581                     !ts.isFunctionLike(blockScopeContainer)) {
32582                     // We check first if the name is inside class declaration or class expression; if so give explicit message
32583                     // otherwise report generic error message.
32584                     var errorSpan = ts.getErrorSpanForNode(file, node);
32585                     file.bindDiagnostics.push(ts.createFileDiagnostic(file, errorSpan.start, errorSpan.length, getStrictModeBlockScopeFunctionDeclarationMessage(node)));
32586                 }
32587             }
32588         }
32589         function checkStrictModeNumericLiteral(node) {
32590             if (inStrictMode && node.numericLiteralFlags & 32 /* Octal */) {
32591                 file.bindDiagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.Octal_literals_are_not_allowed_in_strict_mode));
32592             }
32593         }
32594         function checkStrictModePostfixUnaryExpression(node) {
32595             // Grammar checking
32596             // The identifier eval or arguments may not appear as the LeftHandSideExpression of an
32597             // Assignment operator(11.13) or of a PostfixExpression(11.3) or as the UnaryExpression
32598             // operated upon by a Prefix Increment(11.4.4) or a Prefix Decrement(11.4.5) operator.
32599             if (inStrictMode) {
32600                 checkStrictModeEvalOrArguments(node, node.operand);
32601             }
32602         }
32603         function checkStrictModePrefixUnaryExpression(node) {
32604             // Grammar checking
32605             if (inStrictMode) {
32606                 if (node.operator === 45 /* PlusPlusToken */ || node.operator === 46 /* MinusMinusToken */) {
32607                     checkStrictModeEvalOrArguments(node, node.operand);
32608                 }
32609             }
32610         }
32611         function checkStrictModeWithStatement(node) {
32612             // Grammar checking for withStatement
32613             if (inStrictMode) {
32614                 errorOnFirstToken(node, ts.Diagnostics.with_statements_are_not_allowed_in_strict_mode);
32615             }
32616         }
32617         function checkStrictModeLabeledStatement(node) {
32618             // Grammar checking for labeledStatement
32619             if (inStrictMode && options.target >= 2 /* ES2015 */) {
32620                 if (ts.isDeclarationStatement(node.statement) || ts.isVariableStatement(node.statement)) {
32621                     errorOnFirstToken(node.label, ts.Diagnostics.A_label_is_not_allowed_here);
32622                 }
32623             }
32624         }
32625         function errorOnFirstToken(node, message, arg0, arg1, arg2) {
32626             var span = ts.getSpanOfTokenAtPosition(file, node.pos);
32627             file.bindDiagnostics.push(ts.createFileDiagnostic(file, span.start, span.length, message, arg0, arg1, arg2));
32628         }
32629         function errorOrSuggestionOnNode(isError, node, message) {
32630             errorOrSuggestionOnRange(isError, node, node, message);
32631         }
32632         function errorOrSuggestionOnRange(isError, startNode, endNode, message) {
32633             addErrorOrSuggestionDiagnostic(isError, { pos: ts.getTokenPosOfNode(startNode, file), end: endNode.end }, message);
32634         }
32635         function addErrorOrSuggestionDiagnostic(isError, range, message) {
32636             var diag = ts.createFileDiagnostic(file, range.pos, range.end - range.pos, message);
32637             if (isError) {
32638                 file.bindDiagnostics.push(diag);
32639             }
32640             else {
32641                 file.bindSuggestionDiagnostics = ts.append(file.bindSuggestionDiagnostics, __assign(__assign({}, diag), { category: ts.DiagnosticCategory.Suggestion }));
32642             }
32643         }
32644         function bind(node) {
32645             if (!node) {
32646                 return;
32647             }
32648             node.parent = parent;
32649             var saveInStrictMode = inStrictMode;
32650             // Even though in the AST the jsdoc @typedef node belongs to the current node,
32651             // its symbol might be in the same scope with the current node's symbol. Consider:
32652             //
32653             //     /** @typedef {string | number} MyType */
32654             //     function foo();
32655             //
32656             // Here the current node is "foo", which is a container, but the scope of "MyType" should
32657             // not be inside "foo". Therefore we always bind @typedef before bind the parent node,
32658             // and skip binding this tag later when binding all the other jsdoc tags.
32659             // First we bind declaration nodes to a symbol if possible. We'll both create a symbol
32660             // and then potentially add the symbol to an appropriate symbol table. Possible
32661             // destination symbol tables are:
32662             //
32663             //  1) The 'exports' table of the current container's symbol.
32664             //  2) The 'members' table of the current container's symbol.
32665             //  3) The 'locals' table of the current container.
32666             //
32667             // However, not all symbols will end up in any of these tables. 'Anonymous' symbols
32668             // (like TypeLiterals for example) will not be put in any table.
32669             bindWorker(node);
32670             // Then we recurse into the children of the node to bind them as well. For certain
32671             // symbols we do specialized work when we recurse. For example, we'll keep track of
32672             // the current 'container' node when it changes. This helps us know which symbol table
32673             // a local should go into for example. Since terminal nodes are known not to have
32674             // children, as an optimization we don't process those.
32675             if (node.kind > 152 /* LastToken */) {
32676                 var saveParent = parent;
32677                 parent = node;
32678                 var containerFlags = getContainerFlags(node);
32679                 if (containerFlags === 0 /* None */) {
32680                     bindChildren(node);
32681                 }
32682                 else {
32683                     bindContainer(node, containerFlags);
32684                 }
32685                 parent = saveParent;
32686             }
32687             else if (!skipTransformFlagAggregation && (node.transformFlags & 536870912 /* HasComputedFlags */) === 0) {
32688                 subtreeTransformFlags |= computeTransformFlagsForNode(node, 0);
32689                 var saveParent = parent;
32690                 if (node.kind === 1 /* EndOfFileToken */)
32691                     parent = node;
32692                 bindJSDoc(node);
32693                 parent = saveParent;
32694             }
32695             inStrictMode = saveInStrictMode;
32696         }
32697         function bindJSDoc(node) {
32698             if (ts.hasJSDocNodes(node)) {
32699                 if (ts.isInJSFile(node)) {
32700                     for (var _i = 0, _a = node.jsDoc; _i < _a.length; _i++) {
32701                         var j = _a[_i];
32702                         bind(j);
32703                     }
32704                 }
32705                 else {
32706                     for (var _b = 0, _c = node.jsDoc; _b < _c.length; _b++) {
32707                         var j = _c[_b];
32708                         setParentPointers(node, j);
32709                     }
32710                 }
32711             }
32712         }
32713         function updateStrictModeStatementList(statements) {
32714             if (!inStrictMode) {
32715                 for (var _i = 0, statements_2 = statements; _i < statements_2.length; _i++) {
32716                     var statement = statements_2[_i];
32717                     if (!ts.isPrologueDirective(statement)) {
32718                         return;
32719                     }
32720                     if (isUseStrictPrologueDirective(statement)) {
32721                         inStrictMode = true;
32722                         return;
32723                     }
32724                 }
32725             }
32726         }
32727         /// Should be called only on prologue directives (isPrologueDirective(node) should be true)
32728         function isUseStrictPrologueDirective(node) {
32729             var nodeText = ts.getSourceTextOfNodeFromSourceFile(file, node.expression);
32730             // Note: the node text must be exactly "use strict" or 'use strict'.  It is not ok for the
32731             // string to contain unicode escapes (as per ES5).
32732             return nodeText === '"use strict"' || nodeText === "'use strict'";
32733         }
32734         function bindWorker(node) {
32735             switch (node.kind) {
32736                 /* Strict mode checks */
32737                 case 75 /* Identifier */:
32738                     // for typedef type names with namespaces, bind the new jsdoc type symbol here
32739                     // because it requires all containing namespaces to be in effect, namely the
32740                     // current "blockScopeContainer" needs to be set to its immediate namespace parent.
32741                     if (node.isInJSDocNamespace) {
32742                         var parentNode = node.parent;
32743                         while (parentNode && !ts.isJSDocTypeAlias(parentNode)) {
32744                             parentNode = parentNode.parent;
32745                         }
32746                         bindBlockScopedDeclaration(parentNode, 524288 /* TypeAlias */, 788968 /* TypeAliasExcludes */);
32747                         break;
32748                     }
32749                 // falls through
32750                 case 104 /* ThisKeyword */:
32751                     if (currentFlow && (ts.isExpression(node) || parent.kind === 282 /* ShorthandPropertyAssignment */)) {
32752                         node.flowNode = currentFlow;
32753                     }
32754                     return checkStrictModeIdentifier(node);
32755                 case 76 /* PrivateIdentifier */:
32756                     return checkPrivateIdentifier(node);
32757                 case 194 /* PropertyAccessExpression */:
32758                 case 195 /* ElementAccessExpression */:
32759                     var expr = node;
32760                     if (currentFlow && isNarrowableReference(expr)) {
32761                         expr.flowNode = currentFlow;
32762                     }
32763                     if (ts.isSpecialPropertyDeclaration(expr)) {
32764                         bindSpecialPropertyDeclaration(expr);
32765                     }
32766                     if (ts.isInJSFile(expr) &&
32767                         file.commonJsModuleIndicator &&
32768                         ts.isModuleExportsAccessExpression(expr) &&
32769                         !lookupSymbolForNameWorker(blockScopeContainer, "module")) {
32770                         declareSymbol(file.locals, /*parent*/ undefined, expr.expression, 1 /* FunctionScopedVariable */ | 134217728 /* ModuleExports */, 111550 /* FunctionScopedVariableExcludes */);
32771                     }
32772                     break;
32773                 case 209 /* BinaryExpression */:
32774                     var specialKind = ts.getAssignmentDeclarationKind(node);
32775                     switch (specialKind) {
32776                         case 1 /* ExportsProperty */:
32777                             bindExportsPropertyAssignment(node);
32778                             break;
32779                         case 2 /* ModuleExports */:
32780                             bindModuleExportsAssignment(node);
32781                             break;
32782                         case 3 /* PrototypeProperty */:
32783                             bindPrototypePropertyAssignment(node.left, node);
32784                             break;
32785                         case 6 /* Prototype */:
32786                             bindPrototypeAssignment(node);
32787                             break;
32788                         case 4 /* ThisProperty */:
32789                             bindThisPropertyAssignment(node);
32790                             break;
32791                         case 5 /* Property */:
32792                             bindSpecialPropertyAssignment(node);
32793                             break;
32794                         case 0 /* None */:
32795                             // Nothing to do
32796                             break;
32797                         default:
32798                             ts.Debug.fail("Unknown binary expression special property assignment kind");
32799                     }
32800                     return checkStrictModeBinaryExpression(node);
32801                 case 280 /* CatchClause */:
32802                     return checkStrictModeCatchClause(node);
32803                 case 203 /* DeleteExpression */:
32804                     return checkStrictModeDeleteExpression(node);
32805                 case 8 /* NumericLiteral */:
32806                     return checkStrictModeNumericLiteral(node);
32807                 case 208 /* PostfixUnaryExpression */:
32808                     return checkStrictModePostfixUnaryExpression(node);
32809                 case 207 /* PrefixUnaryExpression */:
32810                     return checkStrictModePrefixUnaryExpression(node);
32811                 case 236 /* WithStatement */:
32812                     return checkStrictModeWithStatement(node);
32813                 case 238 /* LabeledStatement */:
32814                     return checkStrictModeLabeledStatement(node);
32815                 case 183 /* ThisType */:
32816                     seenThisKeyword = true;
32817                     return;
32818                 case 168 /* TypePredicate */:
32819                     break; // Binding the children will handle everything
32820                 case 155 /* TypeParameter */:
32821                     return bindTypeParameter(node);
32822                 case 156 /* Parameter */:
32823                     return bindParameter(node);
32824                 case 242 /* VariableDeclaration */:
32825                     return bindVariableDeclarationOrBindingElement(node);
32826                 case 191 /* BindingElement */:
32827                     node.flowNode = currentFlow;
32828                     return bindVariableDeclarationOrBindingElement(node);
32829                 case 159 /* PropertyDeclaration */:
32830                 case 158 /* PropertySignature */:
32831                     return bindPropertyWorker(node);
32832                 case 281 /* PropertyAssignment */:
32833                 case 282 /* ShorthandPropertyAssignment */:
32834                     return bindPropertyOrMethodOrAccessor(node, 4 /* Property */, 0 /* PropertyExcludes */);
32835                 case 284 /* EnumMember */:
32836                     return bindPropertyOrMethodOrAccessor(node, 8 /* EnumMember */, 900095 /* EnumMemberExcludes */);
32837                 case 165 /* CallSignature */:
32838                 case 166 /* ConstructSignature */:
32839                 case 167 /* IndexSignature */:
32840                     return declareSymbolAndAddToSymbolTable(node, 131072 /* Signature */, 0 /* None */);
32841                 case 161 /* MethodDeclaration */:
32842                 case 160 /* MethodSignature */:
32843                     // If this is an ObjectLiteralExpression method, then it sits in the same space
32844                     // as other properties in the object literal.  So we use SymbolFlags.PropertyExcludes
32845                     // so that it will conflict with any other object literal members with the same
32846                     // name.
32847                     return bindPropertyOrMethodOrAccessor(node, 8192 /* Method */ | (node.questionToken ? 16777216 /* Optional */ : 0 /* None */), ts.isObjectLiteralMethod(node) ? 0 /* PropertyExcludes */ : 103359 /* MethodExcludes */);
32848                 case 244 /* FunctionDeclaration */:
32849                     return bindFunctionDeclaration(node);
32850                 case 162 /* Constructor */:
32851                     return declareSymbolAndAddToSymbolTable(node, 16384 /* Constructor */, /*symbolExcludes:*/ 0 /* None */);
32852                 case 163 /* GetAccessor */:
32853                     return bindPropertyOrMethodOrAccessor(node, 32768 /* GetAccessor */, 46015 /* GetAccessorExcludes */);
32854                 case 164 /* SetAccessor */:
32855                     return bindPropertyOrMethodOrAccessor(node, 65536 /* SetAccessor */, 78783 /* SetAccessorExcludes */);
32856                 case 170 /* FunctionType */:
32857                 case 300 /* JSDocFunctionType */:
32858                 case 305 /* JSDocSignature */:
32859                 case 171 /* ConstructorType */:
32860                     return bindFunctionOrConstructorType(node);
32861                 case 173 /* TypeLiteral */:
32862                 case 304 /* JSDocTypeLiteral */:
32863                 case 186 /* MappedType */:
32864                     return bindAnonymousTypeWorker(node);
32865                 case 310 /* JSDocClassTag */:
32866                     return bindJSDocClassTag(node);
32867                 case 193 /* ObjectLiteralExpression */:
32868                     return bindObjectLiteralExpression(node);
32869                 case 201 /* FunctionExpression */:
32870                 case 202 /* ArrowFunction */:
32871                     return bindFunctionExpression(node);
32872                 case 196 /* CallExpression */:
32873                     var assignmentKind = ts.getAssignmentDeclarationKind(node);
32874                     switch (assignmentKind) {
32875                         case 7 /* ObjectDefinePropertyValue */:
32876                             return bindObjectDefinePropertyAssignment(node);
32877                         case 8 /* ObjectDefinePropertyExports */:
32878                             return bindObjectDefinePropertyExport(node);
32879                         case 9 /* ObjectDefinePrototypeProperty */:
32880                             return bindObjectDefinePrototypeProperty(node);
32881                         case 0 /* None */:
32882                             break; // Nothing to do
32883                         default:
32884                             return ts.Debug.fail("Unknown call expression assignment declaration kind");
32885                     }
32886                     if (ts.isInJSFile(node)) {
32887                         bindCallExpression(node);
32888                     }
32889                     break;
32890                 // Members of classes, interfaces, and modules
32891                 case 214 /* ClassExpression */:
32892                 case 245 /* ClassDeclaration */:
32893                     // All classes are automatically in strict mode in ES6.
32894                     inStrictMode = true;
32895                     return bindClassLikeDeclaration(node);
32896                 case 246 /* InterfaceDeclaration */:
32897                     return bindBlockScopedDeclaration(node, 64 /* Interface */, 788872 /* InterfaceExcludes */);
32898                 case 247 /* TypeAliasDeclaration */:
32899                     return bindBlockScopedDeclaration(node, 524288 /* TypeAlias */, 788968 /* TypeAliasExcludes */);
32900                 case 248 /* EnumDeclaration */:
32901                     return bindEnumDeclaration(node);
32902                 case 249 /* ModuleDeclaration */:
32903                     return bindModuleDeclaration(node);
32904                 // Jsx-attributes
32905                 case 274 /* JsxAttributes */:
32906                     return bindJsxAttributes(node);
32907                 case 273 /* JsxAttribute */:
32908                     return bindJsxAttribute(node, 4 /* Property */, 0 /* PropertyExcludes */);
32909                 // Imports and exports
32910                 case 253 /* ImportEqualsDeclaration */:
32911                 case 256 /* NamespaceImport */:
32912                 case 258 /* ImportSpecifier */:
32913                 case 263 /* ExportSpecifier */:
32914                     return declareSymbolAndAddToSymbolTable(node, 2097152 /* Alias */, 2097152 /* AliasExcludes */);
32915                 case 252 /* NamespaceExportDeclaration */:
32916                     return bindNamespaceExportDeclaration(node);
32917                 case 255 /* ImportClause */:
32918                     return bindImportClause(node);
32919                 case 260 /* ExportDeclaration */:
32920                     return bindExportDeclaration(node);
32921                 case 259 /* ExportAssignment */:
32922                     return bindExportAssignment(node);
32923                 case 290 /* SourceFile */:
32924                     updateStrictModeStatementList(node.statements);
32925                     return bindSourceFileIfExternalModule();
32926                 case 223 /* Block */:
32927                     if (!ts.isFunctionLike(node.parent)) {
32928                         return;
32929                     }
32930                 // falls through
32931                 case 250 /* ModuleBlock */:
32932                     return updateStrictModeStatementList(node.statements);
32933                 case 317 /* JSDocParameterTag */:
32934                     if (node.parent.kind === 305 /* JSDocSignature */) {
32935                         return bindParameter(node);
32936                     }
32937                     if (node.parent.kind !== 304 /* JSDocTypeLiteral */) {
32938                         break;
32939                     }
32940                 // falls through
32941                 case 323 /* JSDocPropertyTag */:
32942                     var propTag = node;
32943                     var flags = propTag.isBracketed || propTag.typeExpression && propTag.typeExpression.type.kind === 299 /* JSDocOptionalType */ ?
32944                         4 /* Property */ | 16777216 /* Optional */ :
32945                         4 /* Property */;
32946                     return declareSymbolAndAddToSymbolTable(propTag, flags, 0 /* PropertyExcludes */);
32947                 case 322 /* JSDocTypedefTag */:
32948                 case 315 /* JSDocCallbackTag */:
32949                 case 316 /* JSDocEnumTag */:
32950                     return (delayedTypeAliases || (delayedTypeAliases = [])).push(node);
32951             }
32952         }
32953         function bindPropertyWorker(node) {
32954             return bindPropertyOrMethodOrAccessor(node, 4 /* Property */ | (node.questionToken ? 16777216 /* Optional */ : 0 /* None */), 0 /* PropertyExcludes */);
32955         }
32956         function bindAnonymousTypeWorker(node) {
32957             return bindAnonymousDeclaration(node, 2048 /* TypeLiteral */, "__type" /* Type */);
32958         }
32959         function bindSourceFileIfExternalModule() {
32960             setExportContextFlag(file);
32961             if (ts.isExternalModule(file)) {
32962                 bindSourceFileAsExternalModule();
32963             }
32964             else if (ts.isJsonSourceFile(file)) {
32965                 bindSourceFileAsExternalModule();
32966                 // Create symbol equivalent for the module.exports = {}
32967                 var originalSymbol = file.symbol;
32968                 declareSymbol(file.symbol.exports, file.symbol, file, 4 /* Property */, 67108863 /* All */);
32969                 file.symbol = originalSymbol;
32970             }
32971         }
32972         function bindSourceFileAsExternalModule() {
32973             bindAnonymousDeclaration(file, 512 /* ValueModule */, "\"" + ts.removeFileExtension(file.fileName) + "\"");
32974         }
32975         function bindExportAssignment(node) {
32976             if (!container.symbol || !container.symbol.exports) {
32977                 // Export assignment in some sort of block construct
32978                 bindAnonymousDeclaration(node, 2097152 /* Alias */, getDeclarationName(node));
32979             }
32980             else {
32981                 var flags = ts.exportAssignmentIsAlias(node)
32982                     // An export default clause with an EntityNameExpression or a class expression exports all meanings of that identifier or expression;
32983                     ? 2097152 /* Alias */
32984                     // An export default clause with any other expression exports a value
32985                     : 4 /* Property */;
32986                 // If there is an `export default x;` alias declaration, can't `export default` anything else.
32987                 // (In contrast, you can still have `export default function f() {}` and `export default interface I {}`.)
32988                 var symbol = declareSymbol(container.symbol.exports, container.symbol, node, flags, 67108863 /* All */);
32989                 if (node.isExportEquals) {
32990                     // Will be an error later, since the module already has other exports. Just make sure this has a valueDeclaration set.
32991                     ts.setValueDeclaration(symbol, node);
32992                 }
32993             }
32994         }
32995         function bindNamespaceExportDeclaration(node) {
32996             if (node.modifiers && node.modifiers.length) {
32997                 file.bindDiagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.Modifiers_cannot_appear_here));
32998             }
32999             var diag = !ts.isSourceFile(node.parent) ? ts.Diagnostics.Global_module_exports_may_only_appear_at_top_level
33000                 : !ts.isExternalModule(node.parent) ? ts.Diagnostics.Global_module_exports_may_only_appear_in_module_files
33001                     : !node.parent.isDeclarationFile ? ts.Diagnostics.Global_module_exports_may_only_appear_in_declaration_files
33002                         : undefined;
33003             if (diag) {
33004                 file.bindDiagnostics.push(createDiagnosticForNode(node, diag));
33005             }
33006             else {
33007                 file.symbol.globalExports = file.symbol.globalExports || ts.createSymbolTable();
33008                 declareSymbol(file.symbol.globalExports, file.symbol, node, 2097152 /* Alias */, 2097152 /* AliasExcludes */);
33009             }
33010         }
33011         function bindExportDeclaration(node) {
33012             if (!container.symbol || !container.symbol.exports) {
33013                 // Export * in some sort of block construct
33014                 bindAnonymousDeclaration(node, 8388608 /* ExportStar */, getDeclarationName(node));
33015             }
33016             else if (!node.exportClause) {
33017                 // All export * declarations are collected in an __export symbol
33018                 declareSymbol(container.symbol.exports, container.symbol, node, 8388608 /* ExportStar */, 0 /* None */);
33019             }
33020             else if (ts.isNamespaceExport(node.exportClause)) {
33021                 // declareSymbol walks up parents to find name text, parent _must_ be set
33022                 // but won't be set by the normal binder walk until `bindChildren` later on.
33023                 node.exportClause.parent = node;
33024                 declareSymbol(container.symbol.exports, container.symbol, node.exportClause, 2097152 /* Alias */, 2097152 /* AliasExcludes */);
33025             }
33026         }
33027         function bindImportClause(node) {
33028             if (node.name) {
33029                 declareSymbolAndAddToSymbolTable(node, 2097152 /* Alias */, 2097152 /* AliasExcludes */);
33030             }
33031         }
33032         function setCommonJsModuleIndicator(node) {
33033             if (file.externalModuleIndicator) {
33034                 return false;
33035             }
33036             if (!file.commonJsModuleIndicator) {
33037                 file.commonJsModuleIndicator = node;
33038                 bindSourceFileAsExternalModule();
33039             }
33040             return true;
33041         }
33042         function bindObjectDefinePropertyExport(node) {
33043             if (!setCommonJsModuleIndicator(node)) {
33044                 return;
33045             }
33046             var symbol = forEachIdentifierInEntityName(node.arguments[0], /*parent*/ undefined, function (id, symbol) {
33047                 if (symbol) {
33048                     addDeclarationToSymbol(symbol, id, 1536 /* Module */ | 67108864 /* Assignment */);
33049                 }
33050                 return symbol;
33051             });
33052             if (symbol) {
33053                 var flags = 4 /* Property */ | 1048576 /* ExportValue */;
33054                 declareSymbol(symbol.exports, symbol, node, flags, 0 /* None */);
33055             }
33056         }
33057         function bindExportsPropertyAssignment(node) {
33058             // When we create a property via 'exports.foo = bar', the 'exports.foo' property access
33059             // expression is the declaration
33060             if (!setCommonJsModuleIndicator(node)) {
33061                 return;
33062             }
33063             var symbol = forEachIdentifierInEntityName(node.left.expression, /*parent*/ undefined, function (id, symbol) {
33064                 if (symbol) {
33065                     addDeclarationToSymbol(symbol, id, 1536 /* Module */ | 67108864 /* Assignment */);
33066                 }
33067                 return symbol;
33068             });
33069             if (symbol) {
33070                 var flags = ts.isClassExpression(node.right) ?
33071                     4 /* Property */ | 1048576 /* ExportValue */ | 32 /* Class */ :
33072                     4 /* Property */ | 1048576 /* ExportValue */;
33073                 declareSymbol(symbol.exports, symbol, node.left, flags, 0 /* None */);
33074             }
33075         }
33076         function bindModuleExportsAssignment(node) {
33077             // A common practice in node modules is to set 'export = module.exports = {}', this ensures that 'exports'
33078             // is still pointing to 'module.exports'.
33079             // We do not want to consider this as 'export=' since a module can have only one of these.
33080             // Similarly we do not want to treat 'module.exports = exports' as an 'export='.
33081             if (!setCommonJsModuleIndicator(node)) {
33082                 return;
33083             }
33084             var assignedExpression = ts.getRightMostAssignedExpression(node.right);
33085             if (ts.isEmptyObjectLiteral(assignedExpression) || container === file && isExportsOrModuleExportsOrAlias(file, assignedExpression)) {
33086                 return;
33087             }
33088             // 'module.exports = expr' assignment
33089             var flags = ts.exportAssignmentIsAlias(node)
33090                 ? 2097152 /* Alias */
33091                 : 4 /* Property */ | 1048576 /* ExportValue */ | 512 /* ValueModule */;
33092             var symbol = declareSymbol(file.symbol.exports, file.symbol, node, flags | 67108864 /* Assignment */, 0 /* None */);
33093             ts.setValueDeclaration(symbol, node);
33094         }
33095         function bindThisPropertyAssignment(node) {
33096             ts.Debug.assert(ts.isInJSFile(node));
33097             // private identifiers *must* be declared (even in JS files)
33098             var hasPrivateIdentifier = (ts.isBinaryExpression(node) && ts.isPropertyAccessExpression(node.left) && ts.isPrivateIdentifier(node.left.name))
33099                 || (ts.isPropertyAccessExpression(node) && ts.isPrivateIdentifier(node.name));
33100             if (hasPrivateIdentifier) {
33101                 return;
33102             }
33103             var thisContainer = ts.getThisContainer(node, /*includeArrowFunctions*/ false);
33104             switch (thisContainer.kind) {
33105                 case 244 /* FunctionDeclaration */:
33106                 case 201 /* FunctionExpression */:
33107                     var constructorSymbol = thisContainer.symbol;
33108                     // For `f.prototype.m = function() { this.x = 0; }`, `this.x = 0` should modify `f`'s members, not the function expression.
33109                     if (ts.isBinaryExpression(thisContainer.parent) && thisContainer.parent.operatorToken.kind === 62 /* EqualsToken */) {
33110                         var l = thisContainer.parent.left;
33111                         if (ts.isBindableStaticAccessExpression(l) && ts.isPrototypeAccess(l.expression)) {
33112                             constructorSymbol = lookupSymbolForPropertyAccess(l.expression.expression, thisParentContainer);
33113                         }
33114                     }
33115                     if (constructorSymbol && constructorSymbol.valueDeclaration) {
33116                         // Declare a 'member' if the container is an ES5 class or ES6 constructor
33117                         constructorSymbol.members = constructorSymbol.members || ts.createSymbolTable();
33118                         // It's acceptable for multiple 'this' assignments of the same identifier to occur
33119                         if (ts.hasDynamicName(node)) {
33120                             bindDynamicallyNamedThisPropertyAssignment(node, constructorSymbol);
33121                         }
33122                         else {
33123                             declareSymbol(constructorSymbol.members, constructorSymbol, node, 4 /* Property */ | 67108864 /* Assignment */, 0 /* PropertyExcludes */ & ~4 /* Property */);
33124                         }
33125                         addDeclarationToSymbol(constructorSymbol, constructorSymbol.valueDeclaration, 32 /* Class */);
33126                     }
33127                     break;
33128                 case 162 /* Constructor */:
33129                 case 159 /* PropertyDeclaration */:
33130                 case 161 /* MethodDeclaration */:
33131                 case 163 /* GetAccessor */:
33132                 case 164 /* SetAccessor */:
33133                     // this.foo assignment in a JavaScript class
33134                     // Bind this property to the containing class
33135                     var containingClass = thisContainer.parent;
33136                     var symbolTable = ts.hasModifier(thisContainer, 32 /* Static */) ? containingClass.symbol.exports : containingClass.symbol.members;
33137                     if (ts.hasDynamicName(node)) {
33138                         bindDynamicallyNamedThisPropertyAssignment(node, containingClass.symbol);
33139                     }
33140                     else {
33141                         declareSymbol(symbolTable, containingClass.symbol, node, 4 /* Property */ | 67108864 /* Assignment */, 0 /* None */, /*isReplaceableByMethod*/ true);
33142                     }
33143                     break;
33144                 case 290 /* SourceFile */:
33145                     // this.property = assignment in a source file -- declare symbol in exports for a module, in locals for a script
33146                     if (ts.hasDynamicName(node)) {
33147                         break;
33148                     }
33149                     else if (thisContainer.commonJsModuleIndicator) {
33150                         declareSymbol(thisContainer.symbol.exports, thisContainer.symbol, node, 4 /* Property */ | 1048576 /* ExportValue */, 0 /* None */);
33151                     }
33152                     else {
33153                         declareSymbolAndAddToSymbolTable(node, 1 /* FunctionScopedVariable */, 111550 /* FunctionScopedVariableExcludes */);
33154                     }
33155                     break;
33156                 default:
33157                     ts.Debug.failBadSyntaxKind(thisContainer);
33158             }
33159         }
33160         function bindDynamicallyNamedThisPropertyAssignment(node, symbol) {
33161             bindAnonymousDeclaration(node, 4 /* Property */, "__computed" /* Computed */);
33162             addLateBoundAssignmentDeclarationToSymbol(node, symbol);
33163         }
33164         function addLateBoundAssignmentDeclarationToSymbol(node, symbol) {
33165             if (symbol) {
33166                 var members = symbol.assignmentDeclarationMembers || (symbol.assignmentDeclarationMembers = ts.createMap());
33167                 members.set("" + ts.getNodeId(node), node);
33168             }
33169         }
33170         function bindSpecialPropertyDeclaration(node) {
33171             if (node.expression.kind === 104 /* ThisKeyword */) {
33172                 bindThisPropertyAssignment(node);
33173             }
33174             else if (ts.isBindableStaticAccessExpression(node) && node.parent.parent.kind === 290 /* SourceFile */) {
33175                 if (ts.isPrototypeAccess(node.expression)) {
33176                     bindPrototypePropertyAssignment(node, node.parent);
33177                 }
33178                 else {
33179                     bindStaticPropertyAssignment(node);
33180                 }
33181             }
33182         }
33183         /** For `x.prototype = { p, ... }`, declare members p,... if `x` is function/class/{}, or not declared. */
33184         function bindPrototypeAssignment(node) {
33185             node.left.parent = node;
33186             node.right.parent = node;
33187             bindPropertyAssignment(node.left.expression, node.left, /*isPrototypeProperty*/ false, /*containerIsClass*/ true);
33188         }
33189         function bindObjectDefinePrototypeProperty(node) {
33190             var namespaceSymbol = lookupSymbolForPropertyAccess(node.arguments[0].expression);
33191             if (namespaceSymbol && namespaceSymbol.valueDeclaration) {
33192                 // Ensure the namespace symbol becomes class-like
33193                 addDeclarationToSymbol(namespaceSymbol, namespaceSymbol.valueDeclaration, 32 /* Class */);
33194             }
33195             bindPotentiallyNewExpandoMemberToNamespace(node, namespaceSymbol, /*isPrototypeProperty*/ true);
33196         }
33197         /**
33198          * For `x.prototype.y = z`, declare a member `y` on `x` if `x` is a function or class, or not declared.
33199          * Note that jsdoc preceding an ExpressionStatement like `x.prototype.y;` is also treated as a declaration.
33200          */
33201         function bindPrototypePropertyAssignment(lhs, parent) {
33202             // Look up the function in the local scope, since prototype assignments should
33203             // follow the function declaration
33204             var classPrototype = lhs.expression;
33205             var constructorFunction = classPrototype.expression;
33206             // Fix up parent pointers since we're going to use these nodes before we bind into them
33207             lhs.parent = parent;
33208             constructorFunction.parent = classPrototype;
33209             classPrototype.parent = lhs;
33210             bindPropertyAssignment(constructorFunction, lhs, /*isPrototypeProperty*/ true, /*containerIsClass*/ true);
33211         }
33212         function bindObjectDefinePropertyAssignment(node) {
33213             var namespaceSymbol = lookupSymbolForPropertyAccess(node.arguments[0]);
33214             var isToplevel = node.parent.parent.kind === 290 /* SourceFile */;
33215             namespaceSymbol = bindPotentiallyMissingNamespaces(namespaceSymbol, node.arguments[0], isToplevel, /*isPrototypeProperty*/ false, /*containerIsClass*/ false);
33216             bindPotentiallyNewExpandoMemberToNamespace(node, namespaceSymbol, /*isPrototypeProperty*/ false);
33217         }
33218         function bindSpecialPropertyAssignment(node) {
33219             // Class declarations in Typescript do not allow property declarations
33220             var parentSymbol = lookupSymbolForPropertyAccess(node.left.expression);
33221             if (!ts.isInJSFile(node) && !ts.isFunctionSymbol(parentSymbol)) {
33222                 return;
33223             }
33224             // Fix up parent pointers since we're going to use these nodes before we bind into them
33225             node.left.parent = node;
33226             node.right.parent = node;
33227             if (ts.isIdentifier(node.left.expression) && container === file && isExportsOrModuleExportsOrAlias(file, node.left.expression)) {
33228                 // This can be an alias for the 'exports' or 'module.exports' names, e.g.
33229                 //    var util = module.exports;
33230                 //    util.property = function ...
33231                 bindExportsPropertyAssignment(node);
33232             }
33233             else if (ts.hasDynamicName(node)) {
33234                 bindAnonymousDeclaration(node, 4 /* Property */ | 67108864 /* Assignment */, "__computed" /* Computed */);
33235                 var sym = bindPotentiallyMissingNamespaces(parentSymbol, node.left.expression, isTopLevelNamespaceAssignment(node.left), /*isPrototype*/ false, /*containerIsClass*/ false);
33236                 addLateBoundAssignmentDeclarationToSymbol(node, sym);
33237             }
33238             else {
33239                 bindStaticPropertyAssignment(ts.cast(node.left, ts.isBindableStaticNameExpression));
33240             }
33241         }
33242         /**
33243          * 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.
33244          * Also works for expression statements preceded by JSDoc, like / ** @type number * / x.y;
33245          */
33246         function bindStaticPropertyAssignment(node) {
33247             ts.Debug.assert(!ts.isIdentifier(node));
33248             node.expression.parent = node;
33249             bindPropertyAssignment(node.expression, node, /*isPrototypeProperty*/ false, /*containerIsClass*/ false);
33250         }
33251         function bindPotentiallyMissingNamespaces(namespaceSymbol, entityName, isToplevel, isPrototypeProperty, containerIsClass) {
33252             if (isToplevel && !isPrototypeProperty) {
33253                 // make symbols or add declarations for intermediate containers
33254                 var flags_1 = 1536 /* Module */ | 67108864 /* Assignment */;
33255                 var excludeFlags_1 = 110735 /* ValueModuleExcludes */ & ~67108864 /* Assignment */;
33256                 namespaceSymbol = forEachIdentifierInEntityName(entityName, namespaceSymbol, function (id, symbol, parent) {
33257                     if (symbol) {
33258                         addDeclarationToSymbol(symbol, id, flags_1);
33259                         return symbol;
33260                     }
33261                     else {
33262                         var table = parent ? parent.exports :
33263                             file.jsGlobalAugmentations || (file.jsGlobalAugmentations = ts.createSymbolTable());
33264                         return declareSymbol(table, parent, id, flags_1, excludeFlags_1);
33265                     }
33266                 });
33267             }
33268             if (containerIsClass && namespaceSymbol && namespaceSymbol.valueDeclaration) {
33269                 addDeclarationToSymbol(namespaceSymbol, namespaceSymbol.valueDeclaration, 32 /* Class */);
33270             }
33271             return namespaceSymbol;
33272         }
33273         function bindPotentiallyNewExpandoMemberToNamespace(declaration, namespaceSymbol, isPrototypeProperty) {
33274             if (!namespaceSymbol || !isExpandoSymbol(namespaceSymbol)) {
33275                 return;
33276             }
33277             // Set up the members collection if it doesn't exist already
33278             var symbolTable = isPrototypeProperty ?
33279                 (namespaceSymbol.members || (namespaceSymbol.members = ts.createSymbolTable())) :
33280                 (namespaceSymbol.exports || (namespaceSymbol.exports = ts.createSymbolTable()));
33281             var includes = 0 /* None */;
33282             var excludes = 0 /* None */;
33283             // Method-like
33284             if (ts.isFunctionLikeDeclaration(ts.getAssignedExpandoInitializer(declaration))) {
33285                 includes = 8192 /* Method */;
33286                 excludes = 103359 /* MethodExcludes */;
33287             }
33288             // Maybe accessor-like
33289             else if (ts.isCallExpression(declaration) && ts.isBindableObjectDefinePropertyCall(declaration)) {
33290                 if (ts.some(declaration.arguments[2].properties, function (p) {
33291                     var id = ts.getNameOfDeclaration(p);
33292                     return !!id && ts.isIdentifier(id) && ts.idText(id) === "set";
33293                 })) {
33294                     // We mix in `SymbolFLags.Property` so in the checker `getTypeOfVariableParameterOrProperty` is used for this
33295                     // symbol, instead of `getTypeOfAccessor` (which will assert as there is no real accessor declaration)
33296                     includes |= 65536 /* SetAccessor */ | 4 /* Property */;
33297                     excludes |= 78783 /* SetAccessorExcludes */;
33298                 }
33299                 if (ts.some(declaration.arguments[2].properties, function (p) {
33300                     var id = ts.getNameOfDeclaration(p);
33301                     return !!id && ts.isIdentifier(id) && ts.idText(id) === "get";
33302                 })) {
33303                     includes |= 32768 /* GetAccessor */ | 4 /* Property */;
33304                     excludes |= 46015 /* GetAccessorExcludes */;
33305                 }
33306             }
33307             if (includes === 0 /* None */) {
33308                 includes = 4 /* Property */;
33309                 excludes = 0 /* PropertyExcludes */;
33310             }
33311             declareSymbol(symbolTable, namespaceSymbol, declaration, includes | 67108864 /* Assignment */, excludes & ~67108864 /* Assignment */);
33312         }
33313         function isTopLevelNamespaceAssignment(propertyAccess) {
33314             return ts.isBinaryExpression(propertyAccess.parent)
33315                 ? getParentOfBinaryExpression(propertyAccess.parent).parent.kind === 290 /* SourceFile */
33316                 : propertyAccess.parent.parent.kind === 290 /* SourceFile */;
33317         }
33318         function bindPropertyAssignment(name, propertyAccess, isPrototypeProperty, containerIsClass) {
33319             var namespaceSymbol = lookupSymbolForPropertyAccess(name);
33320             var isToplevel = isTopLevelNamespaceAssignment(propertyAccess);
33321             namespaceSymbol = bindPotentiallyMissingNamespaces(namespaceSymbol, propertyAccess.expression, isToplevel, isPrototypeProperty, containerIsClass);
33322             bindPotentiallyNewExpandoMemberToNamespace(propertyAccess, namespaceSymbol, isPrototypeProperty);
33323         }
33324         /**
33325          * Javascript expando values are:
33326          * - Functions
33327          * - classes
33328          * - namespaces
33329          * - variables initialized with function expressions
33330          * -                       with class expressions
33331          * -                       with empty object literals
33332          * -                       with non-empty object literals if assigned to the prototype property
33333          */
33334         function isExpandoSymbol(symbol) {
33335             if (symbol.flags & (16 /* Function */ | 32 /* Class */ | 1024 /* NamespaceModule */)) {
33336                 return true;
33337             }
33338             var node = symbol.valueDeclaration;
33339             if (node && ts.isCallExpression(node)) {
33340                 return !!ts.getAssignedExpandoInitializer(node);
33341             }
33342             var init = !node ? undefined :
33343                 ts.isVariableDeclaration(node) ? node.initializer :
33344                     ts.isBinaryExpression(node) ? node.right :
33345                         ts.isPropertyAccessExpression(node) && ts.isBinaryExpression(node.parent) ? node.parent.right :
33346                             undefined;
33347             init = init && ts.getRightMostAssignedExpression(init);
33348             if (init) {
33349                 var isPrototypeAssignment = ts.isPrototypeAccess(ts.isVariableDeclaration(node) ? node.name : ts.isBinaryExpression(node) ? node.left : node);
33350                 return !!ts.getExpandoInitializer(ts.isBinaryExpression(init) && (init.operatorToken.kind === 56 /* BarBarToken */ || init.operatorToken.kind === 60 /* QuestionQuestionToken */) ? init.right : init, isPrototypeAssignment);
33351             }
33352             return false;
33353         }
33354         function getParentOfBinaryExpression(expr) {
33355             while (ts.isBinaryExpression(expr.parent)) {
33356                 expr = expr.parent;
33357             }
33358             return expr.parent;
33359         }
33360         function lookupSymbolForPropertyAccess(node, lookupContainer) {
33361             if (lookupContainer === void 0) { lookupContainer = container; }
33362             if (ts.isIdentifier(node)) {
33363                 return lookupSymbolForNameWorker(lookupContainer, node.escapedText);
33364             }
33365             else {
33366                 var symbol = lookupSymbolForPropertyAccess(node.expression);
33367                 return symbol && symbol.exports && symbol.exports.get(ts.getElementOrPropertyAccessName(node));
33368             }
33369         }
33370         function forEachIdentifierInEntityName(e, parent, action) {
33371             if (isExportsOrModuleExportsOrAlias(file, e)) {
33372                 return file.symbol;
33373             }
33374             else if (ts.isIdentifier(e)) {
33375                 return action(e, lookupSymbolForPropertyAccess(e), parent);
33376             }
33377             else {
33378                 var s = forEachIdentifierInEntityName(e.expression, parent, action);
33379                 var name = ts.getNameOrArgument(e);
33380                 // unreachable
33381                 if (ts.isPrivateIdentifier(name)) {
33382                     ts.Debug.fail("unexpected PrivateIdentifier");
33383                 }
33384                 return action(name, s && s.exports && s.exports.get(ts.getElementOrPropertyAccessName(e)), s);
33385             }
33386         }
33387         function bindCallExpression(node) {
33388             // We're only inspecting call expressions to detect CommonJS modules, so we can skip
33389             // this check if we've already seen the module indicator
33390             if (!file.commonJsModuleIndicator && ts.isRequireCall(node, /*checkArgumentIsStringLiteralLike*/ false)) {
33391                 setCommonJsModuleIndicator(node);
33392             }
33393         }
33394         function bindClassLikeDeclaration(node) {
33395             if (node.kind === 245 /* ClassDeclaration */) {
33396                 bindBlockScopedDeclaration(node, 32 /* Class */, 899503 /* ClassExcludes */);
33397             }
33398             else {
33399                 var bindingName = node.name ? node.name.escapedText : "__class" /* Class */;
33400                 bindAnonymousDeclaration(node, 32 /* Class */, bindingName);
33401                 // Add name of class expression into the map for semantic classifier
33402                 if (node.name) {
33403                     classifiableNames.set(node.name.escapedText, true);
33404                 }
33405             }
33406             var symbol = node.symbol;
33407             // TypeScript 1.0 spec (April 2014): 8.4
33408             // Every class automatically contains a static property member named 'prototype', the
33409             // type of which is an instantiation of the class type with type Any supplied as a type
33410             // argument for each type parameter. It is an error to explicitly declare a static
33411             // property member with the name 'prototype'.
33412             //
33413             // Note: we check for this here because this class may be merging into a module.  The
33414             // module might have an exported variable called 'prototype'.  We can't allow that as
33415             // that would clash with the built-in 'prototype' for the class.
33416             var prototypeSymbol = createSymbol(4 /* Property */ | 4194304 /* Prototype */, "prototype");
33417             var symbolExport = symbol.exports.get(prototypeSymbol.escapedName);
33418             if (symbolExport) {
33419                 if (node.name) {
33420                     node.name.parent = node;
33421                 }
33422                 file.bindDiagnostics.push(createDiagnosticForNode(symbolExport.declarations[0], ts.Diagnostics.Duplicate_identifier_0, ts.symbolName(prototypeSymbol)));
33423             }
33424             symbol.exports.set(prototypeSymbol.escapedName, prototypeSymbol);
33425             prototypeSymbol.parent = symbol;
33426         }
33427         function bindEnumDeclaration(node) {
33428             return ts.isEnumConst(node)
33429                 ? bindBlockScopedDeclaration(node, 128 /* ConstEnum */, 899967 /* ConstEnumExcludes */)
33430                 : bindBlockScopedDeclaration(node, 256 /* RegularEnum */, 899327 /* RegularEnumExcludes */);
33431         }
33432         function bindVariableDeclarationOrBindingElement(node) {
33433             if (inStrictMode) {
33434                 checkStrictModeEvalOrArguments(node, node.name);
33435             }
33436             if (!ts.isBindingPattern(node.name)) {
33437                 if (ts.isBlockOrCatchScoped(node)) {
33438                     bindBlockScopedDeclaration(node, 2 /* BlockScopedVariable */, 111551 /* BlockScopedVariableExcludes */);
33439                 }
33440                 else if (ts.isParameterDeclaration(node)) {
33441                     // It is safe to walk up parent chain to find whether the node is a destructuring parameter declaration
33442                     // because its parent chain has already been set up, since parents are set before descending into children.
33443                     //
33444                     // If node is a binding element in parameter declaration, we need to use ParameterExcludes.
33445                     // Using ParameterExcludes flag allows the compiler to report an error on duplicate identifiers in Parameter Declaration
33446                     // For example:
33447                     //      function foo([a,a]) {} // Duplicate Identifier error
33448                     //      function bar(a,a) {}   // Duplicate Identifier error, parameter declaration in this case is handled in bindParameter
33449                     //                             // which correctly set excluded symbols
33450                     declareSymbolAndAddToSymbolTable(node, 1 /* FunctionScopedVariable */, 111551 /* ParameterExcludes */);
33451                 }
33452                 else {
33453                     declareSymbolAndAddToSymbolTable(node, 1 /* FunctionScopedVariable */, 111550 /* FunctionScopedVariableExcludes */);
33454                 }
33455             }
33456         }
33457         function bindParameter(node) {
33458             if (node.kind === 317 /* JSDocParameterTag */ && container.kind !== 305 /* JSDocSignature */) {
33459                 return;
33460             }
33461             if (inStrictMode && !(node.flags & 8388608 /* Ambient */)) {
33462                 // It is a SyntaxError if the identifier eval or arguments appears within a FormalParameterList of a
33463                 // strict mode FunctionLikeDeclaration or FunctionExpression(13.1)
33464                 checkStrictModeEvalOrArguments(node, node.name);
33465             }
33466             if (ts.isBindingPattern(node.name)) {
33467                 bindAnonymousDeclaration(node, 1 /* FunctionScopedVariable */, "__" + node.parent.parameters.indexOf(node));
33468             }
33469             else {
33470                 declareSymbolAndAddToSymbolTable(node, 1 /* FunctionScopedVariable */, 111551 /* ParameterExcludes */);
33471             }
33472             // If this is a property-parameter, then also declare the property symbol into the
33473             // containing class.
33474             if (ts.isParameterPropertyDeclaration(node, node.parent)) {
33475                 var classDeclaration = node.parent.parent;
33476                 declareSymbol(classDeclaration.symbol.members, classDeclaration.symbol, node, 4 /* Property */ | (node.questionToken ? 16777216 /* Optional */ : 0 /* None */), 0 /* PropertyExcludes */);
33477             }
33478         }
33479         function bindFunctionDeclaration(node) {
33480             if (!file.isDeclarationFile && !(node.flags & 8388608 /* Ambient */)) {
33481                 if (ts.isAsyncFunction(node)) {
33482                     emitFlags |= 2048 /* HasAsyncFunctions */;
33483                 }
33484             }
33485             checkStrictModeFunctionName(node);
33486             if (inStrictMode) {
33487                 checkStrictModeFunctionDeclaration(node);
33488                 bindBlockScopedDeclaration(node, 16 /* Function */, 110991 /* FunctionExcludes */);
33489             }
33490             else {
33491                 declareSymbolAndAddToSymbolTable(node, 16 /* Function */, 110991 /* FunctionExcludes */);
33492             }
33493         }
33494         function bindFunctionExpression(node) {
33495             if (!file.isDeclarationFile && !(node.flags & 8388608 /* Ambient */)) {
33496                 if (ts.isAsyncFunction(node)) {
33497                     emitFlags |= 2048 /* HasAsyncFunctions */;
33498                 }
33499             }
33500             if (currentFlow) {
33501                 node.flowNode = currentFlow;
33502             }
33503             checkStrictModeFunctionName(node);
33504             var bindingName = node.name ? node.name.escapedText : "__function" /* Function */;
33505             return bindAnonymousDeclaration(node, 16 /* Function */, bindingName);
33506         }
33507         function bindPropertyOrMethodOrAccessor(node, symbolFlags, symbolExcludes) {
33508             if (!file.isDeclarationFile && !(node.flags & 8388608 /* Ambient */) && ts.isAsyncFunction(node)) {
33509                 emitFlags |= 2048 /* HasAsyncFunctions */;
33510             }
33511             if (currentFlow && ts.isObjectLiteralOrClassExpressionMethod(node)) {
33512                 node.flowNode = currentFlow;
33513             }
33514             return ts.hasDynamicName(node)
33515                 ? bindAnonymousDeclaration(node, symbolFlags, "__computed" /* Computed */)
33516                 : declareSymbolAndAddToSymbolTable(node, symbolFlags, symbolExcludes);
33517         }
33518         function getInferTypeContainer(node) {
33519             var extendsType = ts.findAncestor(node, function (n) { return n.parent && ts.isConditionalTypeNode(n.parent) && n.parent.extendsType === n; });
33520             return extendsType && extendsType.parent;
33521         }
33522         function bindTypeParameter(node) {
33523             if (ts.isJSDocTemplateTag(node.parent)) {
33524                 var container_1 = ts.find(node.parent.parent.tags, ts.isJSDocTypeAlias) || ts.getHostSignatureFromJSDoc(node.parent); // TODO: GH#18217
33525                 if (container_1) {
33526                     if (!container_1.locals) {
33527                         container_1.locals = ts.createSymbolTable();
33528                     }
33529                     declareSymbol(container_1.locals, /*parent*/ undefined, node, 262144 /* TypeParameter */, 526824 /* TypeParameterExcludes */);
33530                 }
33531                 else {
33532                     declareSymbolAndAddToSymbolTable(node, 262144 /* TypeParameter */, 526824 /* TypeParameterExcludes */);
33533                 }
33534             }
33535             else if (node.parent.kind === 181 /* InferType */) {
33536                 var container_2 = getInferTypeContainer(node.parent);
33537                 if (container_2) {
33538                     if (!container_2.locals) {
33539                         container_2.locals = ts.createSymbolTable();
33540                     }
33541                     declareSymbol(container_2.locals, /*parent*/ undefined, node, 262144 /* TypeParameter */, 526824 /* TypeParameterExcludes */);
33542                 }
33543                 else {
33544                     bindAnonymousDeclaration(node, 262144 /* TypeParameter */, getDeclarationName(node)); // TODO: GH#18217
33545                 }
33546             }
33547             else {
33548                 declareSymbolAndAddToSymbolTable(node, 262144 /* TypeParameter */, 526824 /* TypeParameterExcludes */);
33549             }
33550         }
33551         // reachability checks
33552         function shouldReportErrorOnModuleDeclaration(node) {
33553             var instanceState = getModuleInstanceState(node);
33554             return instanceState === 1 /* Instantiated */ || (instanceState === 2 /* ConstEnumOnly */ && !!options.preserveConstEnums);
33555         }
33556         function checkUnreachable(node) {
33557             if (!(currentFlow.flags & 1 /* Unreachable */)) {
33558                 return false;
33559             }
33560             if (currentFlow === unreachableFlow) {
33561                 var reportError = 
33562                 // report error on all statements except empty ones
33563                 (ts.isStatementButNotDeclaration(node) && node.kind !== 224 /* EmptyStatement */) ||
33564                     // report error on class declarations
33565                     node.kind === 245 /* ClassDeclaration */ ||
33566                     // report error on instantiated modules or const-enums only modules if preserveConstEnums is set
33567                     (node.kind === 249 /* ModuleDeclaration */ && shouldReportErrorOnModuleDeclaration(node));
33568                 if (reportError) {
33569                     currentFlow = reportedUnreachableFlow;
33570                     if (!options.allowUnreachableCode) {
33571                         // unreachable code is reported if
33572                         // - user has explicitly asked about it AND
33573                         // - statement is in not ambient context (statements in ambient context is already an error
33574                         //   so we should not report extras) AND
33575                         //   - node is not variable statement OR
33576                         //   - node is block scoped variable statement OR
33577                         //   - node is not block scoped variable statement and at least one variable declaration has initializer
33578                         //   Rationale: we don't want to report errors on non-initialized var's since they are hoisted
33579                         //   On the other side we do want to report errors on non-initialized 'lets' because of TDZ
33580                         var isError_1 = ts.unreachableCodeIsError(options) &&
33581                             !(node.flags & 8388608 /* Ambient */) &&
33582                             (!ts.isVariableStatement(node) ||
33583                                 !!(ts.getCombinedNodeFlags(node.declarationList) & 3 /* BlockScoped */) ||
33584                                 node.declarationList.declarations.some(function (d) { return !!d.initializer; }));
33585                         eachUnreachableRange(node, function (start, end) { return errorOrSuggestionOnRange(isError_1, start, end, ts.Diagnostics.Unreachable_code_detected); });
33586                     }
33587                 }
33588             }
33589             return true;
33590         }
33591     }
33592     function eachUnreachableRange(node, cb) {
33593         if (ts.isStatement(node) && isExecutableStatement(node) && ts.isBlock(node.parent)) {
33594             var statements = node.parent.statements;
33595             var slice_1 = ts.sliceAfter(statements, node);
33596             ts.getRangesWhere(slice_1, isExecutableStatement, function (start, afterEnd) { return cb(slice_1[start], slice_1[afterEnd - 1]); });
33597         }
33598         else {
33599             cb(node, node);
33600         }
33601     }
33602     // As opposed to a pure declaration like an `interface`
33603     function isExecutableStatement(s) {
33604         // Don't remove statements that can validly be used before they appear.
33605         return !ts.isFunctionDeclaration(s) && !isPurelyTypeDeclaration(s) && !ts.isEnumDeclaration(s) &&
33606             // `var x;` may declare a variable used above
33607             !(ts.isVariableStatement(s) && !(ts.getCombinedNodeFlags(s) & (1 /* Let */ | 2 /* Const */)) && s.declarationList.declarations.some(function (d) { return !d.initializer; }));
33608     }
33609     function isPurelyTypeDeclaration(s) {
33610         switch (s.kind) {
33611             case 246 /* InterfaceDeclaration */:
33612             case 247 /* TypeAliasDeclaration */:
33613                 return true;
33614             case 249 /* ModuleDeclaration */:
33615                 return getModuleInstanceState(s) !== 1 /* Instantiated */;
33616             case 248 /* EnumDeclaration */:
33617                 return ts.hasModifier(s, 2048 /* Const */);
33618             default:
33619                 return false;
33620         }
33621     }
33622     function isExportsOrModuleExportsOrAlias(sourceFile, node) {
33623         var i = 0;
33624         var q = [node];
33625         while (q.length && i < 100) {
33626             i++;
33627             node = q.shift();
33628             if (ts.isExportsIdentifier(node) || ts.isModuleExportsAccessExpression(node)) {
33629                 return true;
33630             }
33631             else if (ts.isIdentifier(node)) {
33632                 var symbol = lookupSymbolForNameWorker(sourceFile, node.escapedText);
33633                 if (!!symbol && !!symbol.valueDeclaration && ts.isVariableDeclaration(symbol.valueDeclaration) && !!symbol.valueDeclaration.initializer) {
33634                     var init = symbol.valueDeclaration.initializer;
33635                     q.push(init);
33636                     if (ts.isAssignmentExpression(init, /*excludeCompoundAssignment*/ true)) {
33637                         q.push(init.left);
33638                         q.push(init.right);
33639                     }
33640                 }
33641             }
33642         }
33643         return false;
33644     }
33645     ts.isExportsOrModuleExportsOrAlias = isExportsOrModuleExportsOrAlias;
33646     function lookupSymbolForNameWorker(container, name) {
33647         var local = container.locals && container.locals.get(name);
33648         if (local) {
33649             return local.exportSymbol || local;
33650         }
33651         if (ts.isSourceFile(container) && container.jsGlobalAugmentations && container.jsGlobalAugmentations.has(name)) {
33652             return container.jsGlobalAugmentations.get(name);
33653         }
33654         return container.symbol && container.symbol.exports && container.symbol.exports.get(name);
33655     }
33656     /**
33657      * Computes the transform flags for a node, given the transform flags of its subtree
33658      *
33659      * @param node The node to analyze
33660      * @param subtreeFlags Transform flags computed for this node's subtree
33661      */
33662     function computeTransformFlagsForNode(node, subtreeFlags) {
33663         var kind = node.kind;
33664         switch (kind) {
33665             case 196 /* CallExpression */:
33666                 return computeCallExpression(node, subtreeFlags);
33667             case 197 /* NewExpression */:
33668                 return computeNewExpression(node, subtreeFlags);
33669             case 249 /* ModuleDeclaration */:
33670                 return computeModuleDeclaration(node, subtreeFlags);
33671             case 200 /* ParenthesizedExpression */:
33672                 return computeParenthesizedExpression(node, subtreeFlags);
33673             case 209 /* BinaryExpression */:
33674                 return computeBinaryExpression(node, subtreeFlags);
33675             case 226 /* ExpressionStatement */:
33676                 return computeExpressionStatement(node, subtreeFlags);
33677             case 156 /* Parameter */:
33678                 return computeParameter(node, subtreeFlags);
33679             case 202 /* ArrowFunction */:
33680                 return computeArrowFunction(node, subtreeFlags);
33681             case 201 /* FunctionExpression */:
33682                 return computeFunctionExpression(node, subtreeFlags);
33683             case 244 /* FunctionDeclaration */:
33684                 return computeFunctionDeclaration(node, subtreeFlags);
33685             case 242 /* VariableDeclaration */:
33686                 return computeVariableDeclaration(node, subtreeFlags);
33687             case 243 /* VariableDeclarationList */:
33688                 return computeVariableDeclarationList(node, subtreeFlags);
33689             case 225 /* VariableStatement */:
33690                 return computeVariableStatement(node, subtreeFlags);
33691             case 238 /* LabeledStatement */:
33692                 return computeLabeledStatement(node, subtreeFlags);
33693             case 245 /* ClassDeclaration */:
33694                 return computeClassDeclaration(node, subtreeFlags);
33695             case 214 /* ClassExpression */:
33696                 return computeClassExpression(node, subtreeFlags);
33697             case 279 /* HeritageClause */:
33698                 return computeHeritageClause(node, subtreeFlags);
33699             case 280 /* CatchClause */:
33700                 return computeCatchClause(node, subtreeFlags);
33701             case 216 /* ExpressionWithTypeArguments */:
33702                 return computeExpressionWithTypeArguments(node, subtreeFlags);
33703             case 162 /* Constructor */:
33704                 return computeConstructor(node, subtreeFlags);
33705             case 159 /* PropertyDeclaration */:
33706                 return computePropertyDeclaration(node, subtreeFlags);
33707             case 161 /* MethodDeclaration */:
33708                 return computeMethod(node, subtreeFlags);
33709             case 163 /* GetAccessor */:
33710             case 164 /* SetAccessor */:
33711                 return computeAccessor(node, subtreeFlags);
33712             case 253 /* ImportEqualsDeclaration */:
33713                 return computeImportEquals(node, subtreeFlags);
33714             case 194 /* PropertyAccessExpression */:
33715                 return computePropertyAccess(node, subtreeFlags);
33716             case 195 /* ElementAccessExpression */:
33717                 return computeElementAccess(node, subtreeFlags);
33718             case 267 /* JsxSelfClosingElement */:
33719             case 268 /* JsxOpeningElement */:
33720                 return computeJsxOpeningLikeElement(node, subtreeFlags);
33721             default:
33722                 return computeOther(node, kind, subtreeFlags);
33723         }
33724     }
33725     ts.computeTransformFlagsForNode = computeTransformFlagsForNode;
33726     function computeCallExpression(node, subtreeFlags) {
33727         var transformFlags = subtreeFlags;
33728         var callee = ts.skipOuterExpressions(node.expression);
33729         var expression = node.expression;
33730         if (node.flags & 32 /* OptionalChain */) {
33731             transformFlags |= 8 /* ContainsES2020 */;
33732         }
33733         if (node.typeArguments) {
33734             transformFlags |= 1 /* AssertTypeScript */;
33735         }
33736         if (subtreeFlags & 8192 /* ContainsRestOrSpread */ || ts.isSuperOrSuperProperty(callee)) {
33737             // If the this node contains a SpreadExpression, or is a super call, then it is an ES6
33738             // node.
33739             transformFlags |= 256 /* AssertES2015 */;
33740             if (ts.isSuperProperty(callee)) {
33741                 transformFlags |= 4096 /* ContainsLexicalThis */;
33742             }
33743         }
33744         if (expression.kind === 96 /* ImportKeyword */) {
33745             transformFlags |= 2097152 /* ContainsDynamicImport */;
33746         }
33747         node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
33748         return transformFlags & ~536879104 /* ArrayLiteralOrCallOrNewExcludes */;
33749     }
33750     function computeNewExpression(node, subtreeFlags) {
33751         var transformFlags = subtreeFlags;
33752         if (node.typeArguments) {
33753             transformFlags |= 1 /* AssertTypeScript */;
33754         }
33755         if (subtreeFlags & 8192 /* ContainsRestOrSpread */) {
33756             // If the this node contains a SpreadElementExpression then it is an ES6
33757             // node.
33758             transformFlags |= 256 /* AssertES2015 */;
33759         }
33760         node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
33761         return transformFlags & ~536879104 /* ArrayLiteralOrCallOrNewExcludes */;
33762     }
33763     function computeJsxOpeningLikeElement(node, subtreeFlags) {
33764         var transformFlags = subtreeFlags | 2 /* AssertJsx */;
33765         if (node.typeArguments) {
33766             transformFlags |= 1 /* AssertTypeScript */;
33767         }
33768         node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
33769         return transformFlags & ~536870912 /* NodeExcludes */;
33770     }
33771     function computeBinaryExpression(node, subtreeFlags) {
33772         var transformFlags = subtreeFlags;
33773         var operatorTokenKind = node.operatorToken.kind;
33774         var leftKind = node.left.kind;
33775         if (operatorTokenKind === 60 /* QuestionQuestionToken */) {
33776             transformFlags |= 8 /* AssertES2020 */;
33777         }
33778         else if (operatorTokenKind === 62 /* EqualsToken */ && leftKind === 193 /* ObjectLiteralExpression */) {
33779             // Destructuring object assignments with are ES2015 syntax
33780             // and possibly ES2018 if they contain rest
33781             transformFlags |= 32 /* AssertES2018 */ | 256 /* AssertES2015 */ | 1024 /* AssertDestructuringAssignment */;
33782         }
33783         else if (operatorTokenKind === 62 /* EqualsToken */ && leftKind === 192 /* ArrayLiteralExpression */) {
33784             // Destructuring assignments are ES2015 syntax.
33785             transformFlags |= 256 /* AssertES2015 */ | 1024 /* AssertDestructuringAssignment */;
33786         }
33787         else if (operatorTokenKind === 42 /* AsteriskAsteriskToken */
33788             || operatorTokenKind === 66 /* AsteriskAsteriskEqualsToken */) {
33789             // Exponentiation is ES2016 syntax.
33790             transformFlags |= 128 /* AssertES2016 */;
33791         }
33792         node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
33793         return transformFlags & ~536870912 /* NodeExcludes */;
33794     }
33795     function computeParameter(node, subtreeFlags) {
33796         var transformFlags = subtreeFlags;
33797         var name = node.name;
33798         var initializer = node.initializer;
33799         var dotDotDotToken = node.dotDotDotToken;
33800         // The '?' token, type annotations, decorators, and 'this' parameters are TypeSCript
33801         // syntax.
33802         if (node.questionToken
33803             || node.type
33804             || (subtreeFlags & 2048 /* ContainsTypeScriptClassSyntax */ && ts.some(node.decorators))
33805             || ts.isThisIdentifier(name)) {
33806             transformFlags |= 1 /* AssertTypeScript */;
33807         }
33808         // If a parameter has an accessibility modifier, then it is TypeScript syntax.
33809         if (ts.hasModifier(node, 92 /* ParameterPropertyModifier */)) {
33810             transformFlags |= 1 /* AssertTypeScript */ | 2048 /* ContainsTypeScriptClassSyntax */;
33811         }
33812         // parameters with object rest destructuring are ES2018 syntax
33813         if (subtreeFlags & 16384 /* ContainsObjectRestOrSpread */) {
33814             transformFlags |= 32 /* AssertES2018 */;
33815         }
33816         // If a parameter has an initializer, a binding pattern or a dotDotDot token, then
33817         // it is ES6 syntax and its container must emit default value assignments or parameter destructuring downlevel.
33818         if (subtreeFlags & 131072 /* ContainsBindingPattern */ || initializer || dotDotDotToken) {
33819             transformFlags |= 256 /* AssertES2015 */;
33820         }
33821         node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
33822         return transformFlags & ~536870912 /* ParameterExcludes */;
33823     }
33824     function computeParenthesizedExpression(node, subtreeFlags) {
33825         var transformFlags = subtreeFlags;
33826         var expression = node.expression;
33827         var expressionKind = expression.kind;
33828         // If the node is synthesized, it means the emitter put the parentheses there,
33829         // not the user. If we didn't want them, the emitter would not have put them
33830         // there.
33831         if (expressionKind === 217 /* AsExpression */
33832             || expressionKind === 199 /* TypeAssertionExpression */) {
33833             transformFlags |= 1 /* AssertTypeScript */;
33834         }
33835         node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
33836         return transformFlags & ~536870912 /* OuterExpressionExcludes */;
33837     }
33838     function computeClassDeclaration(node, subtreeFlags) {
33839         var transformFlags;
33840         if (ts.hasModifier(node, 2 /* Ambient */)) {
33841             // An ambient declaration is TypeScript syntax.
33842             transformFlags = 1 /* AssertTypeScript */;
33843         }
33844         else {
33845             // A ClassDeclaration is ES6 syntax.
33846             transformFlags = subtreeFlags | 256 /* AssertES2015 */;
33847             // A class with a parameter property assignment or decorator is TypeScript syntax.
33848             // An exported declaration may be TypeScript syntax, but is handled by the visitor
33849             // for a namespace declaration.
33850             if ((subtreeFlags & 2048 /* ContainsTypeScriptClassSyntax */)
33851                 || node.typeParameters) {
33852                 transformFlags |= 1 /* AssertTypeScript */;
33853             }
33854         }
33855         node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
33856         return transformFlags & ~536905728 /* ClassExcludes */;
33857     }
33858     function computeClassExpression(node, subtreeFlags) {
33859         // A ClassExpression is ES6 syntax.
33860         var transformFlags = subtreeFlags | 256 /* AssertES2015 */;
33861         // A class with a parameter property assignment or decorator is TypeScript syntax.
33862         if (subtreeFlags & 2048 /* ContainsTypeScriptClassSyntax */
33863             || node.typeParameters) {
33864             transformFlags |= 1 /* AssertTypeScript */;
33865         }
33866         node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
33867         return transformFlags & ~536905728 /* ClassExcludes */;
33868     }
33869     function computeHeritageClause(node, subtreeFlags) {
33870         var transformFlags = subtreeFlags;
33871         switch (node.token) {
33872             case 90 /* ExtendsKeyword */:
33873                 // An `extends` HeritageClause is ES6 syntax.
33874                 transformFlags |= 256 /* AssertES2015 */;
33875                 break;
33876             case 113 /* ImplementsKeyword */:
33877                 // An `implements` HeritageClause is TypeScript syntax.
33878                 transformFlags |= 1 /* AssertTypeScript */;
33879                 break;
33880             default:
33881                 ts.Debug.fail("Unexpected token for heritage clause");
33882                 break;
33883         }
33884         node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
33885         return transformFlags & ~536870912 /* NodeExcludes */;
33886     }
33887     function computeCatchClause(node, subtreeFlags) {
33888         var transformFlags = subtreeFlags;
33889         if (!node.variableDeclaration) {
33890             transformFlags |= 16 /* AssertES2019 */;
33891         }
33892         else if (ts.isBindingPattern(node.variableDeclaration.name)) {
33893             transformFlags |= 256 /* AssertES2015 */;
33894         }
33895         node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
33896         return transformFlags & ~536887296 /* CatchClauseExcludes */;
33897     }
33898     function computeExpressionWithTypeArguments(node, subtreeFlags) {
33899         // An ExpressionWithTypeArguments is ES6 syntax, as it is used in the
33900         // extends clause of a class.
33901         var transformFlags = subtreeFlags | 256 /* AssertES2015 */;
33902         // If an ExpressionWithTypeArguments contains type arguments, then it
33903         // is TypeScript syntax.
33904         if (node.typeArguments) {
33905             transformFlags |= 1 /* AssertTypeScript */;
33906         }
33907         node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
33908         return transformFlags & ~536870912 /* NodeExcludes */;
33909     }
33910     function computeConstructor(node, subtreeFlags) {
33911         var transformFlags = subtreeFlags;
33912         // TypeScript-specific modifiers and overloads are TypeScript syntax
33913         if (ts.hasModifier(node, 2270 /* TypeScriptModifier */)
33914             || !node.body) {
33915             transformFlags |= 1 /* AssertTypeScript */;
33916         }
33917         // function declarations with object rest destructuring are ES2018 syntax
33918         if (subtreeFlags & 16384 /* ContainsObjectRestOrSpread */) {
33919             transformFlags |= 32 /* AssertES2018 */;
33920         }
33921         node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
33922         return transformFlags & ~538923008 /* ConstructorExcludes */;
33923     }
33924     function computeMethod(node, subtreeFlags) {
33925         // A MethodDeclaration is ES6 syntax.
33926         var transformFlags = subtreeFlags | 256 /* AssertES2015 */;
33927         // Decorators, TypeScript-specific modifiers, type parameters, type annotations, and
33928         // overloads are TypeScript syntax.
33929         if (node.decorators
33930             || ts.hasModifier(node, 2270 /* TypeScriptModifier */)
33931             || node.typeParameters
33932             || node.type
33933             || !node.body
33934             || node.questionToken) {
33935             transformFlags |= 1 /* AssertTypeScript */;
33936         }
33937         // function declarations with object rest destructuring are ES2018 syntax
33938         if (subtreeFlags & 16384 /* ContainsObjectRestOrSpread */) {
33939             transformFlags |= 32 /* AssertES2018 */;
33940         }
33941         // An async method declaration is ES2017 syntax.
33942         if (ts.hasModifier(node, 256 /* Async */)) {
33943             transformFlags |= node.asteriskToken ? 32 /* AssertES2018 */ : 64 /* AssertES2017 */;
33944         }
33945         if (node.asteriskToken) {
33946             transformFlags |= 512 /* AssertGenerator */;
33947         }
33948         node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
33949         return propagatePropertyNameFlags(node.name, transformFlags & ~538923008 /* MethodOrAccessorExcludes */);
33950     }
33951     function computeAccessor(node, subtreeFlags) {
33952         var transformFlags = subtreeFlags;
33953         // Decorators, TypeScript-specific modifiers, type annotations, and overloads are
33954         // TypeScript syntax.
33955         if (node.decorators
33956             || ts.hasModifier(node, 2270 /* TypeScriptModifier */)
33957             || node.type
33958             || !node.body) {
33959             transformFlags |= 1 /* AssertTypeScript */;
33960         }
33961         // function declarations with object rest destructuring are ES2018 syntax
33962         if (subtreeFlags & 16384 /* ContainsObjectRestOrSpread */) {
33963             transformFlags |= 32 /* AssertES2018 */;
33964         }
33965         node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
33966         return propagatePropertyNameFlags(node.name, transformFlags & ~538923008 /* MethodOrAccessorExcludes */);
33967     }
33968     function computePropertyDeclaration(node, subtreeFlags) {
33969         var transformFlags = subtreeFlags | 4194304 /* ContainsClassFields */;
33970         // Decorators, TypeScript-specific modifiers, and type annotations are TypeScript syntax.
33971         if (ts.some(node.decorators) || ts.hasModifier(node, 2270 /* TypeScriptModifier */) || node.type || node.questionToken || node.exclamationToken) {
33972             transformFlags |= 1 /* AssertTypeScript */;
33973         }
33974         // Hoisted variables related to class properties should live within the TypeScript class wrapper.
33975         if (ts.isComputedPropertyName(node.name) || (ts.hasStaticModifier(node) && node.initializer)) {
33976             transformFlags |= 2048 /* ContainsTypeScriptClassSyntax */;
33977         }
33978         node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
33979         return propagatePropertyNameFlags(node.name, transformFlags & ~536875008 /* PropertyExcludes */);
33980     }
33981     function computeFunctionDeclaration(node, subtreeFlags) {
33982         var transformFlags;
33983         var modifierFlags = ts.getModifierFlags(node);
33984         var body = node.body;
33985         if (!body || (modifierFlags & 2 /* Ambient */)) {
33986             // An ambient declaration is TypeScript syntax.
33987             // A FunctionDeclaration without a body is an overload and is TypeScript syntax.
33988             transformFlags = 1 /* AssertTypeScript */;
33989         }
33990         else {
33991             transformFlags = subtreeFlags | 1048576 /* ContainsHoistedDeclarationOrCompletion */;
33992             // TypeScript-specific modifiers, type parameters, and type annotations are TypeScript
33993             // syntax.
33994             if (modifierFlags & 2270 /* TypeScriptModifier */
33995                 || node.typeParameters
33996                 || node.type) {
33997                 transformFlags |= 1 /* AssertTypeScript */;
33998             }
33999             // An async function declaration is ES2017 syntax.
34000             if (modifierFlags & 256 /* Async */) {
34001                 transformFlags |= node.asteriskToken ? 32 /* AssertES2018 */ : 64 /* AssertES2017 */;
34002             }
34003             // function declarations with object rest destructuring are ES2018 syntax
34004             if (subtreeFlags & 16384 /* ContainsObjectRestOrSpread */) {
34005                 transformFlags |= 32 /* AssertES2018 */;
34006             }
34007             // If a FunctionDeclaration is generator function and is the body of a
34008             // transformed async function, then this node can be transformed to a
34009             // down-level generator.
34010             // Currently we do not support transforming any other generator functions
34011             // down level.
34012             if (node.asteriskToken) {
34013                 transformFlags |= 512 /* AssertGenerator */;
34014             }
34015         }
34016         node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
34017         return transformFlags & ~538925056 /* FunctionExcludes */;
34018     }
34019     function computeFunctionExpression(node, subtreeFlags) {
34020         var transformFlags = subtreeFlags;
34021         // TypeScript-specific modifiers, type parameters, and type annotations are TypeScript
34022         // syntax.
34023         if (ts.hasModifier(node, 2270 /* TypeScriptModifier */)
34024             || node.typeParameters
34025             || node.type) {
34026             transformFlags |= 1 /* AssertTypeScript */;
34027         }
34028         // An async function expression is ES2017 syntax.
34029         if (ts.hasModifier(node, 256 /* Async */)) {
34030             transformFlags |= node.asteriskToken ? 32 /* AssertES2018 */ : 64 /* AssertES2017 */;
34031         }
34032         // function expressions with object rest destructuring are ES2018 syntax
34033         if (subtreeFlags & 16384 /* ContainsObjectRestOrSpread */) {
34034             transformFlags |= 32 /* AssertES2018 */;
34035         }
34036         // If a FunctionExpression is generator function and is the body of a
34037         // transformed async function, then this node can be transformed to a
34038         // down-level generator.
34039         if (node.asteriskToken) {
34040             transformFlags |= 512 /* AssertGenerator */;
34041         }
34042         node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
34043         return transformFlags & ~538925056 /* FunctionExcludes */;
34044     }
34045     function computeArrowFunction(node, subtreeFlags) {
34046         // An ArrowFunction is ES6 syntax, and excludes markers that should not escape the scope of an ArrowFunction.
34047         var transformFlags = subtreeFlags | 256 /* AssertES2015 */;
34048         // TypeScript-specific modifiers, type parameters, and type annotations are TypeScript
34049         // syntax.
34050         if (ts.hasModifier(node, 2270 /* TypeScriptModifier */)
34051             || node.typeParameters
34052             || node.type) {
34053             transformFlags |= 1 /* AssertTypeScript */;
34054         }
34055         // An async arrow function is ES2017 syntax.
34056         if (ts.hasModifier(node, 256 /* Async */)) {
34057             transformFlags |= 64 /* AssertES2017 */;
34058         }
34059         // arrow functions 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 & ~538920960 /* ArrowFunctionExcludes */;
34065     }
34066     function computePropertyAccess(node, subtreeFlags) {
34067         var transformFlags = subtreeFlags;
34068         if (node.flags & 32 /* OptionalChain */) {
34069             transformFlags |= 8 /* ContainsES2020 */;
34070         }
34071         // If a PropertyAccessExpression starts with a super keyword, then it is
34072         // ES6 syntax, and requires a lexical `this` binding.
34073         if (node.expression.kind === 102 /* SuperKeyword */) {
34074             // super inside of an async function requires hoisting the super access (ES2017).
34075             // same for super inside of an async generator, which is ES2018.
34076             transformFlags |= 64 /* ContainsES2017 */ | 32 /* ContainsES2018 */;
34077         }
34078         node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
34079         return transformFlags & ~536870912 /* PropertyAccessExcludes */;
34080     }
34081     function computeElementAccess(node, subtreeFlags) {
34082         var transformFlags = subtreeFlags;
34083         if (node.flags & 32 /* OptionalChain */) {
34084             transformFlags |= 8 /* ContainsES2020 */;
34085         }
34086         // If an ElementAccessExpression starts with a super keyword, then it is
34087         // ES6 syntax, and requires a lexical `this` binding.
34088         if (node.expression.kind === 102 /* SuperKeyword */) {
34089             // super inside of an async function requires hoisting the super access (ES2017).
34090             // same for super inside of an async generator, which is ES2018.
34091             transformFlags |= 64 /* ContainsES2017 */ | 32 /* ContainsES2018 */;
34092         }
34093         node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
34094         return transformFlags & ~536870912 /* PropertyAccessExcludes */;
34095     }
34096     function computeVariableDeclaration(node, subtreeFlags) {
34097         var transformFlags = subtreeFlags;
34098         transformFlags |= 256 /* AssertES2015 */ | 131072 /* ContainsBindingPattern */; // TODO(rbuckton): Why are these set unconditionally?
34099         // A VariableDeclaration containing ObjectRest is ES2018 syntax
34100         if (subtreeFlags & 16384 /* ContainsObjectRestOrSpread */) {
34101             transformFlags |= 32 /* AssertES2018 */;
34102         }
34103         // Type annotations are TypeScript syntax.
34104         if (node.type || node.exclamationToken) {
34105             transformFlags |= 1 /* AssertTypeScript */;
34106         }
34107         node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
34108         return transformFlags & ~536870912 /* NodeExcludes */;
34109     }
34110     function computeVariableStatement(node, subtreeFlags) {
34111         var transformFlags;
34112         var declarationListTransformFlags = node.declarationList.transformFlags;
34113         // An ambient declaration is TypeScript syntax.
34114         if (ts.hasModifier(node, 2 /* Ambient */)) {
34115             transformFlags = 1 /* AssertTypeScript */;
34116         }
34117         else {
34118             transformFlags = subtreeFlags;
34119             if (declarationListTransformFlags & 131072 /* ContainsBindingPattern */) {
34120                 transformFlags |= 256 /* AssertES2015 */;
34121             }
34122         }
34123         node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
34124         return transformFlags & ~536870912 /* NodeExcludes */;
34125     }
34126     function computeLabeledStatement(node, subtreeFlags) {
34127         var transformFlags = subtreeFlags;
34128         // A labeled statement containing a block scoped binding *may* need to be transformed from ES6.
34129         if (subtreeFlags & 65536 /* ContainsBlockScopedBinding */
34130             && ts.isIterationStatement(node, /*lookInLabeledStatements*/ true)) {
34131             transformFlags |= 256 /* AssertES2015 */;
34132         }
34133         node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
34134         return transformFlags & ~536870912 /* NodeExcludes */;
34135     }
34136     function computeImportEquals(node, subtreeFlags) {
34137         var transformFlags = subtreeFlags;
34138         // An ImportEqualsDeclaration with a namespace reference is TypeScript.
34139         if (!ts.isExternalModuleImportEqualsDeclaration(node)) {
34140             transformFlags |= 1 /* AssertTypeScript */;
34141         }
34142         node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
34143         return transformFlags & ~536870912 /* NodeExcludes */;
34144     }
34145     function computeExpressionStatement(node, subtreeFlags) {
34146         var transformFlags = subtreeFlags;
34147         node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
34148         return transformFlags & ~536870912 /* NodeExcludes */;
34149     }
34150     function computeModuleDeclaration(node, subtreeFlags) {
34151         var transformFlags = 1 /* AssertTypeScript */;
34152         var modifierFlags = ts.getModifierFlags(node);
34153         if ((modifierFlags & 2 /* Ambient */) === 0) {
34154             transformFlags |= subtreeFlags;
34155         }
34156         node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
34157         return transformFlags & ~537991168 /* ModuleExcludes */;
34158     }
34159     function computeVariableDeclarationList(node, subtreeFlags) {
34160         var transformFlags = subtreeFlags | 1048576 /* ContainsHoistedDeclarationOrCompletion */;
34161         if (subtreeFlags & 131072 /* ContainsBindingPattern */) {
34162             transformFlags |= 256 /* AssertES2015 */;
34163         }
34164         // If a VariableDeclarationList is `let` or `const`, then it is ES6 syntax.
34165         if (node.flags & 3 /* BlockScoped */) {
34166             transformFlags |= 256 /* AssertES2015 */ | 65536 /* ContainsBlockScopedBinding */;
34167         }
34168         node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
34169         return transformFlags & ~537018368 /* VariableDeclarationListExcludes */;
34170     }
34171     function computeOther(node, kind, subtreeFlags) {
34172         // Mark transformations needed for each node
34173         var transformFlags = subtreeFlags;
34174         var excludeFlags = 536870912 /* NodeExcludes */;
34175         switch (kind) {
34176             case 126 /* AsyncKeyword */:
34177                 // async is ES2017 syntax, but may be ES2018 syntax (for async generators)
34178                 transformFlags |= 32 /* AssertES2018 */ | 64 /* AssertES2017 */;
34179                 break;
34180             case 206 /* AwaitExpression */:
34181                 // await is ES2017 syntax, but may be ES2018 syntax (for async generators)
34182                 transformFlags |= 32 /* AssertES2018 */ | 64 /* AssertES2017 */ | 524288 /* ContainsAwait */;
34183                 break;
34184             case 199 /* TypeAssertionExpression */:
34185             case 217 /* AsExpression */:
34186             case 326 /* PartiallyEmittedExpression */:
34187                 // These nodes are TypeScript syntax.
34188                 transformFlags |= 1 /* AssertTypeScript */;
34189                 excludeFlags = 536870912 /* OuterExpressionExcludes */;
34190                 break;
34191             case 119 /* PublicKeyword */:
34192             case 117 /* PrivateKeyword */:
34193             case 118 /* ProtectedKeyword */:
34194             case 122 /* AbstractKeyword */:
34195             case 130 /* DeclareKeyword */:
34196             case 81 /* ConstKeyword */:
34197             case 248 /* EnumDeclaration */:
34198             case 284 /* EnumMember */:
34199             case 218 /* NonNullExpression */:
34200             case 138 /* ReadonlyKeyword */:
34201                 // These nodes are TypeScript syntax.
34202                 transformFlags |= 1 /* AssertTypeScript */;
34203                 break;
34204             case 266 /* JsxElement */:
34205             case 11 /* JsxText */:
34206             case 269 /* JsxClosingElement */:
34207             case 270 /* JsxFragment */:
34208             case 271 /* JsxOpeningFragment */:
34209             case 272 /* JsxClosingFragment */:
34210             case 273 /* JsxAttribute */:
34211             case 274 /* JsxAttributes */:
34212             case 275 /* JsxSpreadAttribute */:
34213             case 276 /* JsxExpression */:
34214                 // These nodes are Jsx syntax.
34215                 transformFlags |= 2 /* AssertJsx */;
34216                 break;
34217             case 14 /* NoSubstitutionTemplateLiteral */:
34218             case 15 /* TemplateHead */:
34219             case 16 /* TemplateMiddle */:
34220             case 17 /* TemplateTail */:
34221                 if (node.templateFlags) {
34222                     transformFlags |= 32 /* AssertES2018 */;
34223                     break;
34224                 }
34225             // falls through
34226             case 198 /* TaggedTemplateExpression */:
34227                 if (ts.hasInvalidEscape(node.template)) {
34228                     transformFlags |= 32 /* AssertES2018 */;
34229                     break;
34230                 }
34231             // falls through
34232             case 211 /* TemplateExpression */:
34233             case 282 /* ShorthandPropertyAssignment */:
34234             case 120 /* StaticKeyword */:
34235             case 219 /* MetaProperty */:
34236                 // These nodes are ES6 syntax.
34237                 transformFlags |= 256 /* AssertES2015 */;
34238                 break;
34239             case 10 /* StringLiteral */:
34240                 if (node.hasExtendedUnicodeEscape) {
34241                     transformFlags |= 256 /* AssertES2015 */;
34242                 }
34243                 break;
34244             case 8 /* NumericLiteral */:
34245                 if (node.numericLiteralFlags & 384 /* BinaryOrOctalSpecifier */) {
34246                     transformFlags |= 256 /* AssertES2015 */;
34247                 }
34248                 break;
34249             case 9 /* BigIntLiteral */:
34250                 transformFlags |= 4 /* AssertESNext */;
34251                 break;
34252             case 232 /* ForOfStatement */:
34253                 // This node is either ES2015 syntax or ES2017 syntax (if it is a for-await-of).
34254                 if (node.awaitModifier) {
34255                     transformFlags |= 32 /* AssertES2018 */;
34256                 }
34257                 transformFlags |= 256 /* AssertES2015 */;
34258                 break;
34259             case 212 /* YieldExpression */:
34260                 // This node is either ES2015 syntax (in a generator) or ES2017 syntax (in an async
34261                 // generator).
34262                 transformFlags |= 32 /* AssertES2018 */ | 256 /* AssertES2015 */ | 262144 /* ContainsYield */;
34263                 break;
34264             case 125 /* AnyKeyword */:
34265             case 140 /* NumberKeyword */:
34266             case 151 /* BigIntKeyword */:
34267             case 137 /* NeverKeyword */:
34268             case 141 /* ObjectKeyword */:
34269             case 143 /* StringKeyword */:
34270             case 128 /* BooleanKeyword */:
34271             case 144 /* SymbolKeyword */:
34272             case 110 /* VoidKeyword */:
34273             case 155 /* TypeParameter */:
34274             case 158 /* PropertySignature */:
34275             case 160 /* MethodSignature */:
34276             case 165 /* CallSignature */:
34277             case 166 /* ConstructSignature */:
34278             case 167 /* IndexSignature */:
34279             case 168 /* TypePredicate */:
34280             case 169 /* TypeReference */:
34281             case 170 /* FunctionType */:
34282             case 171 /* ConstructorType */:
34283             case 172 /* TypeQuery */:
34284             case 173 /* TypeLiteral */:
34285             case 174 /* ArrayType */:
34286             case 175 /* TupleType */:
34287             case 176 /* OptionalType */:
34288             case 177 /* RestType */:
34289             case 178 /* UnionType */:
34290             case 179 /* IntersectionType */:
34291             case 180 /* ConditionalType */:
34292             case 181 /* InferType */:
34293             case 182 /* ParenthesizedType */:
34294             case 246 /* InterfaceDeclaration */:
34295             case 247 /* TypeAliasDeclaration */:
34296             case 183 /* ThisType */:
34297             case 184 /* TypeOperator */:
34298             case 185 /* IndexedAccessType */:
34299             case 186 /* MappedType */:
34300             case 187 /* LiteralType */:
34301             case 252 /* NamespaceExportDeclaration */:
34302                 // Types and signatures are TypeScript syntax, and exclude all other facts.
34303                 transformFlags = 1 /* AssertTypeScript */;
34304                 excludeFlags = -2 /* TypeExcludes */;
34305                 break;
34306             case 154 /* ComputedPropertyName */:
34307                 // Even though computed property names are ES6, we don't treat them as such.
34308                 // This is so that they can flow through PropertyName transforms unaffected.
34309                 // Instead, we mark the container as ES6, so that it can properly handle the transform.
34310                 transformFlags |= 32768 /* ContainsComputedPropertyName */;
34311                 break;
34312             case 213 /* SpreadElement */:
34313                 transformFlags |= 256 /* AssertES2015 */ | 8192 /* ContainsRestOrSpread */;
34314                 break;
34315             case 283 /* SpreadAssignment */:
34316                 transformFlags |= 32 /* AssertES2018 */ | 16384 /* ContainsObjectRestOrSpread */;
34317                 break;
34318             case 102 /* SuperKeyword */:
34319                 // This node is ES6 syntax.
34320                 transformFlags |= 256 /* AssertES2015 */;
34321                 excludeFlags = 536870912 /* OuterExpressionExcludes */; // must be set to persist `Super`
34322                 break;
34323             case 104 /* ThisKeyword */:
34324                 // Mark this node and its ancestors as containing a lexical `this` keyword.
34325                 transformFlags |= 4096 /* ContainsLexicalThis */;
34326                 break;
34327             case 189 /* ObjectBindingPattern */:
34328                 transformFlags |= 256 /* AssertES2015 */ | 131072 /* ContainsBindingPattern */;
34329                 if (subtreeFlags & 8192 /* ContainsRestOrSpread */) {
34330                     transformFlags |= 32 /* AssertES2018 */ | 16384 /* ContainsObjectRestOrSpread */;
34331                 }
34332                 excludeFlags = 536879104 /* BindingPatternExcludes */;
34333                 break;
34334             case 190 /* ArrayBindingPattern */:
34335                 transformFlags |= 256 /* AssertES2015 */ | 131072 /* ContainsBindingPattern */;
34336                 excludeFlags = 536879104 /* BindingPatternExcludes */;
34337                 break;
34338             case 191 /* BindingElement */:
34339                 transformFlags |= 256 /* AssertES2015 */;
34340                 if (node.dotDotDotToken) {
34341                     transformFlags |= 8192 /* ContainsRestOrSpread */;
34342                 }
34343                 break;
34344             case 157 /* Decorator */:
34345                 // This node is TypeScript syntax, and marks its container as also being TypeScript syntax.
34346                 transformFlags |= 1 /* AssertTypeScript */ | 2048 /* ContainsTypeScriptClassSyntax */;
34347                 break;
34348             case 193 /* ObjectLiteralExpression */:
34349                 excludeFlags = 536922112 /* ObjectLiteralExcludes */;
34350                 if (subtreeFlags & 32768 /* ContainsComputedPropertyName */) {
34351                     // If an ObjectLiteralExpression contains a ComputedPropertyName, then it
34352                     // is an ES6 node.
34353                     transformFlags |= 256 /* AssertES2015 */;
34354                 }
34355                 if (subtreeFlags & 16384 /* ContainsObjectRestOrSpread */) {
34356                     // If an ObjectLiteralExpression contains a spread element, then it
34357                     // is an ES2018 node.
34358                     transformFlags |= 32 /* AssertES2018 */;
34359                 }
34360                 break;
34361             case 192 /* ArrayLiteralExpression */:
34362                 excludeFlags = 536879104 /* ArrayLiteralOrCallOrNewExcludes */;
34363                 break;
34364             case 228 /* DoStatement */:
34365             case 229 /* WhileStatement */:
34366             case 230 /* ForStatement */:
34367             case 231 /* ForInStatement */:
34368                 // A loop containing a block scoped binding *may* need to be transformed from ES6.
34369                 if (subtreeFlags & 65536 /* ContainsBlockScopedBinding */) {
34370                     transformFlags |= 256 /* AssertES2015 */;
34371                 }
34372                 break;
34373             case 290 /* SourceFile */:
34374                 break;
34375             case 262 /* NamespaceExport */:
34376                 transformFlags |= 4 /* AssertESNext */;
34377                 break;
34378             case 235 /* ReturnStatement */:
34379                 // Return statements may require an `await` in ES2018.
34380                 transformFlags |= 1048576 /* ContainsHoistedDeclarationOrCompletion */ | 32 /* AssertES2018 */;
34381                 break;
34382             case 233 /* ContinueStatement */:
34383             case 234 /* BreakStatement */:
34384                 transformFlags |= 1048576 /* ContainsHoistedDeclarationOrCompletion */;
34385                 break;
34386             case 76 /* PrivateIdentifier */:
34387                 transformFlags |= 4194304 /* ContainsClassFields */;
34388                 break;
34389         }
34390         node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
34391         return transformFlags & ~excludeFlags;
34392     }
34393     function propagatePropertyNameFlags(node, transformFlags) {
34394         return transformFlags | (node.transformFlags & 4096 /* PropertyNamePropagatingFlags */);
34395     }
34396     /**
34397      * Gets the transform flags to exclude when unioning the transform flags of a subtree.
34398      *
34399      * NOTE: This needs to be kept up-to-date with the exclusions used in `computeTransformFlagsForNode`.
34400      *       For performance reasons, `computeTransformFlagsForNode` uses local constant values rather
34401      *       than calling this function.
34402      */
34403     function getTransformFlagsSubtreeExclusions(kind) {
34404         if (kind >= 168 /* FirstTypeNode */ && kind <= 188 /* LastTypeNode */) {
34405             return -2 /* TypeExcludes */;
34406         }
34407         switch (kind) {
34408             case 196 /* CallExpression */:
34409             case 197 /* NewExpression */:
34410             case 192 /* ArrayLiteralExpression */:
34411                 return 536879104 /* ArrayLiteralOrCallOrNewExcludes */;
34412             case 249 /* ModuleDeclaration */:
34413                 return 537991168 /* ModuleExcludes */;
34414             case 156 /* Parameter */:
34415                 return 536870912 /* ParameterExcludes */;
34416             case 202 /* ArrowFunction */:
34417                 return 538920960 /* ArrowFunctionExcludes */;
34418             case 201 /* FunctionExpression */:
34419             case 244 /* FunctionDeclaration */:
34420                 return 538925056 /* FunctionExcludes */;
34421             case 243 /* VariableDeclarationList */:
34422                 return 537018368 /* VariableDeclarationListExcludes */;
34423             case 245 /* ClassDeclaration */:
34424             case 214 /* ClassExpression */:
34425                 return 536905728 /* ClassExcludes */;
34426             case 162 /* Constructor */:
34427                 return 538923008 /* ConstructorExcludes */;
34428             case 161 /* MethodDeclaration */:
34429             case 163 /* GetAccessor */:
34430             case 164 /* SetAccessor */:
34431                 return 538923008 /* MethodOrAccessorExcludes */;
34432             case 125 /* AnyKeyword */:
34433             case 140 /* NumberKeyword */:
34434             case 151 /* BigIntKeyword */:
34435             case 137 /* NeverKeyword */:
34436             case 143 /* StringKeyword */:
34437             case 141 /* ObjectKeyword */:
34438             case 128 /* BooleanKeyword */:
34439             case 144 /* SymbolKeyword */:
34440             case 110 /* VoidKeyword */:
34441             case 155 /* TypeParameter */:
34442             case 158 /* PropertySignature */:
34443             case 160 /* MethodSignature */:
34444             case 165 /* CallSignature */:
34445             case 166 /* ConstructSignature */:
34446             case 167 /* IndexSignature */:
34447             case 246 /* InterfaceDeclaration */:
34448             case 247 /* TypeAliasDeclaration */:
34449                 return -2 /* TypeExcludes */;
34450             case 193 /* ObjectLiteralExpression */:
34451                 return 536922112 /* ObjectLiteralExcludes */;
34452             case 280 /* CatchClause */:
34453                 return 536887296 /* CatchClauseExcludes */;
34454             case 189 /* ObjectBindingPattern */:
34455             case 190 /* ArrayBindingPattern */:
34456                 return 536879104 /* BindingPatternExcludes */;
34457             case 199 /* TypeAssertionExpression */:
34458             case 217 /* AsExpression */:
34459             case 326 /* PartiallyEmittedExpression */:
34460             case 200 /* ParenthesizedExpression */:
34461             case 102 /* SuperKeyword */:
34462                 return 536870912 /* OuterExpressionExcludes */;
34463             case 194 /* PropertyAccessExpression */:
34464             case 195 /* ElementAccessExpression */:
34465                 return 536870912 /* PropertyAccessExcludes */;
34466             default:
34467                 return 536870912 /* NodeExcludes */;
34468         }
34469     }
34470     ts.getTransformFlagsSubtreeExclusions = getTransformFlagsSubtreeExclusions;
34471     /**
34472      * "Binds" JSDoc nodes in TypeScript code.
34473      * Since we will never create symbols for JSDoc, we just set parent pointers instead.
34474      */
34475     function setParentPointers(parent, child) {
34476         child.parent = parent;
34477         ts.forEachChild(child, function (grandchild) { return setParentPointers(child, grandchild); });
34478     }
34479 })(ts || (ts = {}));
34480 /** @internal */
34481 var ts;
34482 (function (ts) {
34483     function createGetSymbolWalker(getRestTypeOfSignature, getTypePredicateOfSignature, getReturnTypeOfSignature, getBaseTypes, resolveStructuredTypeMembers, getTypeOfSymbol, getResolvedSymbol, getIndexTypeOfStructuredType, getConstraintOfTypeParameter, getFirstIdentifier, getTypeArguments) {
34484         return getSymbolWalker;
34485         function getSymbolWalker(accept) {
34486             if (accept === void 0) { accept = function () { return true; }; }
34487             var visitedTypes = []; // Sparse array from id to type
34488             var visitedSymbols = []; // Sparse array from id to symbol
34489             return {
34490                 walkType: function (type) {
34491                     try {
34492                         visitType(type);
34493                         return { visitedTypes: ts.getOwnValues(visitedTypes), visitedSymbols: ts.getOwnValues(visitedSymbols) };
34494                     }
34495                     finally {
34496                         ts.clear(visitedTypes);
34497                         ts.clear(visitedSymbols);
34498                     }
34499                 },
34500                 walkSymbol: function (symbol) {
34501                     try {
34502                         visitSymbol(symbol);
34503                         return { visitedTypes: ts.getOwnValues(visitedTypes), visitedSymbols: ts.getOwnValues(visitedSymbols) };
34504                     }
34505                     finally {
34506                         ts.clear(visitedTypes);
34507                         ts.clear(visitedSymbols);
34508                     }
34509                 },
34510             };
34511             function visitType(type) {
34512                 if (!type) {
34513                     return;
34514                 }
34515                 if (visitedTypes[type.id]) {
34516                     return;
34517                 }
34518                 visitedTypes[type.id] = type;
34519                 // Reuse visitSymbol to visit the type's symbol,
34520                 //  but be sure to bail on recuring into the type if accept declines the symbol.
34521                 var shouldBail = visitSymbol(type.symbol);
34522                 if (shouldBail)
34523                     return;
34524                 // Visit the type's related types, if any
34525                 if (type.flags & 524288 /* Object */) {
34526                     var objectType = type;
34527                     var objectFlags = objectType.objectFlags;
34528                     if (objectFlags & 4 /* Reference */) {
34529                         visitTypeReference(type);
34530                     }
34531                     if (objectFlags & 32 /* Mapped */) {
34532                         visitMappedType(type);
34533                     }
34534                     if (objectFlags & (1 /* Class */ | 2 /* Interface */)) {
34535                         visitInterfaceType(type);
34536                     }
34537                     if (objectFlags & (8 /* Tuple */ | 16 /* Anonymous */)) {
34538                         visitObjectType(objectType);
34539                     }
34540                 }
34541                 if (type.flags & 262144 /* TypeParameter */) {
34542                     visitTypeParameter(type);
34543                 }
34544                 if (type.flags & 3145728 /* UnionOrIntersection */) {
34545                     visitUnionOrIntersectionType(type);
34546                 }
34547                 if (type.flags & 4194304 /* Index */) {
34548                     visitIndexType(type);
34549                 }
34550                 if (type.flags & 8388608 /* IndexedAccess */) {
34551                     visitIndexedAccessType(type);
34552                 }
34553             }
34554             function visitTypeReference(type) {
34555                 visitType(type.target);
34556                 ts.forEach(getTypeArguments(type), visitType);
34557             }
34558             function visitTypeParameter(type) {
34559                 visitType(getConstraintOfTypeParameter(type));
34560             }
34561             function visitUnionOrIntersectionType(type) {
34562                 ts.forEach(type.types, visitType);
34563             }
34564             function visitIndexType(type) {
34565                 visitType(type.type);
34566             }
34567             function visitIndexedAccessType(type) {
34568                 visitType(type.objectType);
34569                 visitType(type.indexType);
34570                 visitType(type.constraint);
34571             }
34572             function visitMappedType(type) {
34573                 visitType(type.typeParameter);
34574                 visitType(type.constraintType);
34575                 visitType(type.templateType);
34576                 visitType(type.modifiersType);
34577             }
34578             function visitSignature(signature) {
34579                 var typePredicate = getTypePredicateOfSignature(signature);
34580                 if (typePredicate) {
34581                     visitType(typePredicate.type);
34582                 }
34583                 ts.forEach(signature.typeParameters, visitType);
34584                 for (var _i = 0, _a = signature.parameters; _i < _a.length; _i++) {
34585                     var parameter = _a[_i];
34586                     visitSymbol(parameter);
34587                 }
34588                 visitType(getRestTypeOfSignature(signature));
34589                 visitType(getReturnTypeOfSignature(signature));
34590             }
34591             function visitInterfaceType(interfaceT) {
34592                 visitObjectType(interfaceT);
34593                 ts.forEach(interfaceT.typeParameters, visitType);
34594                 ts.forEach(getBaseTypes(interfaceT), visitType);
34595                 visitType(interfaceT.thisType);
34596             }
34597             function visitObjectType(type) {
34598                 var stringIndexType = getIndexTypeOfStructuredType(type, 0 /* String */);
34599                 visitType(stringIndexType);
34600                 var numberIndexType = getIndexTypeOfStructuredType(type, 1 /* Number */);
34601                 visitType(numberIndexType);
34602                 // The two checks above *should* have already resolved the type (if needed), so this should be cached
34603                 var resolved = resolveStructuredTypeMembers(type);
34604                 for (var _i = 0, _a = resolved.callSignatures; _i < _a.length; _i++) {
34605                     var signature = _a[_i];
34606                     visitSignature(signature);
34607                 }
34608                 for (var _b = 0, _c = resolved.constructSignatures; _b < _c.length; _b++) {
34609                     var signature = _c[_b];
34610                     visitSignature(signature);
34611                 }
34612                 for (var _d = 0, _e = resolved.properties; _d < _e.length; _d++) {
34613                     var p = _e[_d];
34614                     visitSymbol(p);
34615                 }
34616             }
34617             function visitSymbol(symbol) {
34618                 if (!symbol) {
34619                     return false;
34620                 }
34621                 var symbolId = ts.getSymbolId(symbol);
34622                 if (visitedSymbols[symbolId]) {
34623                     return false;
34624                 }
34625                 visitedSymbols[symbolId] = symbol;
34626                 if (!accept(symbol)) {
34627                     return true;
34628                 }
34629                 var t = getTypeOfSymbol(symbol);
34630                 visitType(t); // Should handle members on classes and such
34631                 if (symbol.exports) {
34632                     symbol.exports.forEach(visitSymbol);
34633                 }
34634                 ts.forEach(symbol.declarations, function (d) {
34635                     // Type queries are too far resolved when we just visit the symbol's type
34636                     //  (their type resolved directly to the member deeply referenced)
34637                     // So to get the intervening symbols, we need to check if there's a type
34638                     // query node on any of the symbol's declarations and get symbols there
34639                     if (d.type && d.type.kind === 172 /* TypeQuery */) {
34640                         var query = d.type;
34641                         var entity = getResolvedSymbol(getFirstIdentifier(query.exprName));
34642                         visitSymbol(entity);
34643                     }
34644                 });
34645                 return false;
34646             }
34647         }
34648     }
34649     ts.createGetSymbolWalker = createGetSymbolWalker;
34650 })(ts || (ts = {}));
34651 /* @internal */
34652 var ts;
34653 (function (ts) {
34654     var ambientModuleSymbolRegex = /^".+"$/;
34655     var anon = "(anonymous)";
34656     var nextSymbolId = 1;
34657     var nextNodeId = 1;
34658     var nextMergeId = 1;
34659     var nextFlowId = 1;
34660     var IterationUse;
34661     (function (IterationUse) {
34662         IterationUse[IterationUse["AllowsSyncIterablesFlag"] = 1] = "AllowsSyncIterablesFlag";
34663         IterationUse[IterationUse["AllowsAsyncIterablesFlag"] = 2] = "AllowsAsyncIterablesFlag";
34664         IterationUse[IterationUse["AllowsStringInputFlag"] = 4] = "AllowsStringInputFlag";
34665         IterationUse[IterationUse["ForOfFlag"] = 8] = "ForOfFlag";
34666         IterationUse[IterationUse["YieldStarFlag"] = 16] = "YieldStarFlag";
34667         IterationUse[IterationUse["SpreadFlag"] = 32] = "SpreadFlag";
34668         IterationUse[IterationUse["DestructuringFlag"] = 64] = "DestructuringFlag";
34669         // Spread, Destructuring, Array element assignment
34670         IterationUse[IterationUse["Element"] = 1] = "Element";
34671         IterationUse[IterationUse["Spread"] = 33] = "Spread";
34672         IterationUse[IterationUse["Destructuring"] = 65] = "Destructuring";
34673         IterationUse[IterationUse["ForOf"] = 13] = "ForOf";
34674         IterationUse[IterationUse["ForAwaitOf"] = 15] = "ForAwaitOf";
34675         IterationUse[IterationUse["YieldStar"] = 17] = "YieldStar";
34676         IterationUse[IterationUse["AsyncYieldStar"] = 19] = "AsyncYieldStar";
34677         IterationUse[IterationUse["GeneratorReturnType"] = 1] = "GeneratorReturnType";
34678         IterationUse[IterationUse["AsyncGeneratorReturnType"] = 2] = "AsyncGeneratorReturnType";
34679     })(IterationUse || (IterationUse = {}));
34680     var IterationTypeKind;
34681     (function (IterationTypeKind) {
34682         IterationTypeKind[IterationTypeKind["Yield"] = 0] = "Yield";
34683         IterationTypeKind[IterationTypeKind["Return"] = 1] = "Return";
34684         IterationTypeKind[IterationTypeKind["Next"] = 2] = "Next";
34685     })(IterationTypeKind || (IterationTypeKind = {}));
34686     var WideningKind;
34687     (function (WideningKind) {
34688         WideningKind[WideningKind["Normal"] = 0] = "Normal";
34689         WideningKind[WideningKind["FunctionReturn"] = 1] = "FunctionReturn";
34690         WideningKind[WideningKind["GeneratorNext"] = 2] = "GeneratorNext";
34691         WideningKind[WideningKind["GeneratorYield"] = 3] = "GeneratorYield";
34692     })(WideningKind || (WideningKind = {}));
34693     var TypeFacts;
34694     (function (TypeFacts) {
34695         TypeFacts[TypeFacts["None"] = 0] = "None";
34696         TypeFacts[TypeFacts["TypeofEQString"] = 1] = "TypeofEQString";
34697         TypeFacts[TypeFacts["TypeofEQNumber"] = 2] = "TypeofEQNumber";
34698         TypeFacts[TypeFacts["TypeofEQBigInt"] = 4] = "TypeofEQBigInt";
34699         TypeFacts[TypeFacts["TypeofEQBoolean"] = 8] = "TypeofEQBoolean";
34700         TypeFacts[TypeFacts["TypeofEQSymbol"] = 16] = "TypeofEQSymbol";
34701         TypeFacts[TypeFacts["TypeofEQObject"] = 32] = "TypeofEQObject";
34702         TypeFacts[TypeFacts["TypeofEQFunction"] = 64] = "TypeofEQFunction";
34703         TypeFacts[TypeFacts["TypeofEQHostObject"] = 128] = "TypeofEQHostObject";
34704         TypeFacts[TypeFacts["TypeofNEString"] = 256] = "TypeofNEString";
34705         TypeFacts[TypeFacts["TypeofNENumber"] = 512] = "TypeofNENumber";
34706         TypeFacts[TypeFacts["TypeofNEBigInt"] = 1024] = "TypeofNEBigInt";
34707         TypeFacts[TypeFacts["TypeofNEBoolean"] = 2048] = "TypeofNEBoolean";
34708         TypeFacts[TypeFacts["TypeofNESymbol"] = 4096] = "TypeofNESymbol";
34709         TypeFacts[TypeFacts["TypeofNEObject"] = 8192] = "TypeofNEObject";
34710         TypeFacts[TypeFacts["TypeofNEFunction"] = 16384] = "TypeofNEFunction";
34711         TypeFacts[TypeFacts["TypeofNEHostObject"] = 32768] = "TypeofNEHostObject";
34712         TypeFacts[TypeFacts["EQUndefined"] = 65536] = "EQUndefined";
34713         TypeFacts[TypeFacts["EQNull"] = 131072] = "EQNull";
34714         TypeFacts[TypeFacts["EQUndefinedOrNull"] = 262144] = "EQUndefinedOrNull";
34715         TypeFacts[TypeFacts["NEUndefined"] = 524288] = "NEUndefined";
34716         TypeFacts[TypeFacts["NENull"] = 1048576] = "NENull";
34717         TypeFacts[TypeFacts["NEUndefinedOrNull"] = 2097152] = "NEUndefinedOrNull";
34718         TypeFacts[TypeFacts["Truthy"] = 4194304] = "Truthy";
34719         TypeFacts[TypeFacts["Falsy"] = 8388608] = "Falsy";
34720         TypeFacts[TypeFacts["All"] = 16777215] = "All";
34721         // The following members encode facts about particular kinds of types for use in the getTypeFacts function.
34722         // The presence of a particular fact means that the given test is true for some (and possibly all) values
34723         // of that kind of type.
34724         TypeFacts[TypeFacts["BaseStringStrictFacts"] = 3735041] = "BaseStringStrictFacts";
34725         TypeFacts[TypeFacts["BaseStringFacts"] = 12582401] = "BaseStringFacts";
34726         TypeFacts[TypeFacts["StringStrictFacts"] = 16317953] = "StringStrictFacts";
34727         TypeFacts[TypeFacts["StringFacts"] = 16776705] = "StringFacts";
34728         TypeFacts[TypeFacts["EmptyStringStrictFacts"] = 12123649] = "EmptyStringStrictFacts";
34729         TypeFacts[TypeFacts["EmptyStringFacts"] = 12582401] = "EmptyStringFacts";
34730         TypeFacts[TypeFacts["NonEmptyStringStrictFacts"] = 7929345] = "NonEmptyStringStrictFacts";
34731         TypeFacts[TypeFacts["NonEmptyStringFacts"] = 16776705] = "NonEmptyStringFacts";
34732         TypeFacts[TypeFacts["BaseNumberStrictFacts"] = 3734786] = "BaseNumberStrictFacts";
34733         TypeFacts[TypeFacts["BaseNumberFacts"] = 12582146] = "BaseNumberFacts";
34734         TypeFacts[TypeFacts["NumberStrictFacts"] = 16317698] = "NumberStrictFacts";
34735         TypeFacts[TypeFacts["NumberFacts"] = 16776450] = "NumberFacts";
34736         TypeFacts[TypeFacts["ZeroNumberStrictFacts"] = 12123394] = "ZeroNumberStrictFacts";
34737         TypeFacts[TypeFacts["ZeroNumberFacts"] = 12582146] = "ZeroNumberFacts";
34738         TypeFacts[TypeFacts["NonZeroNumberStrictFacts"] = 7929090] = "NonZeroNumberStrictFacts";
34739         TypeFacts[TypeFacts["NonZeroNumberFacts"] = 16776450] = "NonZeroNumberFacts";
34740         TypeFacts[TypeFacts["BaseBigIntStrictFacts"] = 3734276] = "BaseBigIntStrictFacts";
34741         TypeFacts[TypeFacts["BaseBigIntFacts"] = 12581636] = "BaseBigIntFacts";
34742         TypeFacts[TypeFacts["BigIntStrictFacts"] = 16317188] = "BigIntStrictFacts";
34743         TypeFacts[TypeFacts["BigIntFacts"] = 16775940] = "BigIntFacts";
34744         TypeFacts[TypeFacts["ZeroBigIntStrictFacts"] = 12122884] = "ZeroBigIntStrictFacts";
34745         TypeFacts[TypeFacts["ZeroBigIntFacts"] = 12581636] = "ZeroBigIntFacts";
34746         TypeFacts[TypeFacts["NonZeroBigIntStrictFacts"] = 7928580] = "NonZeroBigIntStrictFacts";
34747         TypeFacts[TypeFacts["NonZeroBigIntFacts"] = 16775940] = "NonZeroBigIntFacts";
34748         TypeFacts[TypeFacts["BaseBooleanStrictFacts"] = 3733256] = "BaseBooleanStrictFacts";
34749         TypeFacts[TypeFacts["BaseBooleanFacts"] = 12580616] = "BaseBooleanFacts";
34750         TypeFacts[TypeFacts["BooleanStrictFacts"] = 16316168] = "BooleanStrictFacts";
34751         TypeFacts[TypeFacts["BooleanFacts"] = 16774920] = "BooleanFacts";
34752         TypeFacts[TypeFacts["FalseStrictFacts"] = 12121864] = "FalseStrictFacts";
34753         TypeFacts[TypeFacts["FalseFacts"] = 12580616] = "FalseFacts";
34754         TypeFacts[TypeFacts["TrueStrictFacts"] = 7927560] = "TrueStrictFacts";
34755         TypeFacts[TypeFacts["TrueFacts"] = 16774920] = "TrueFacts";
34756         TypeFacts[TypeFacts["SymbolStrictFacts"] = 7925520] = "SymbolStrictFacts";
34757         TypeFacts[TypeFacts["SymbolFacts"] = 16772880] = "SymbolFacts";
34758         TypeFacts[TypeFacts["ObjectStrictFacts"] = 7888800] = "ObjectStrictFacts";
34759         TypeFacts[TypeFacts["ObjectFacts"] = 16736160] = "ObjectFacts";
34760         TypeFacts[TypeFacts["FunctionStrictFacts"] = 7880640] = "FunctionStrictFacts";
34761         TypeFacts[TypeFacts["FunctionFacts"] = 16728000] = "FunctionFacts";
34762         TypeFacts[TypeFacts["UndefinedFacts"] = 9830144] = "UndefinedFacts";
34763         TypeFacts[TypeFacts["NullFacts"] = 9363232] = "NullFacts";
34764         TypeFacts[TypeFacts["EmptyObjectStrictFacts"] = 16318463] = "EmptyObjectStrictFacts";
34765         TypeFacts[TypeFacts["EmptyObjectFacts"] = 16777215] = "EmptyObjectFacts";
34766     })(TypeFacts || (TypeFacts = {}));
34767     var typeofEQFacts = ts.createMapFromTemplate({
34768         string: 1 /* TypeofEQString */,
34769         number: 2 /* TypeofEQNumber */,
34770         bigint: 4 /* TypeofEQBigInt */,
34771         boolean: 8 /* TypeofEQBoolean */,
34772         symbol: 16 /* TypeofEQSymbol */,
34773         undefined: 65536 /* EQUndefined */,
34774         object: 32 /* TypeofEQObject */,
34775         function: 64 /* TypeofEQFunction */
34776     });
34777     var typeofNEFacts = ts.createMapFromTemplate({
34778         string: 256 /* TypeofNEString */,
34779         number: 512 /* TypeofNENumber */,
34780         bigint: 1024 /* TypeofNEBigInt */,
34781         boolean: 2048 /* TypeofNEBoolean */,
34782         symbol: 4096 /* TypeofNESymbol */,
34783         undefined: 524288 /* NEUndefined */,
34784         object: 8192 /* TypeofNEObject */,
34785         function: 16384 /* TypeofNEFunction */
34786     });
34787     var TypeSystemPropertyName;
34788     (function (TypeSystemPropertyName) {
34789         TypeSystemPropertyName[TypeSystemPropertyName["Type"] = 0] = "Type";
34790         TypeSystemPropertyName[TypeSystemPropertyName["ResolvedBaseConstructorType"] = 1] = "ResolvedBaseConstructorType";
34791         TypeSystemPropertyName[TypeSystemPropertyName["DeclaredType"] = 2] = "DeclaredType";
34792         TypeSystemPropertyName[TypeSystemPropertyName["ResolvedReturnType"] = 3] = "ResolvedReturnType";
34793         TypeSystemPropertyName[TypeSystemPropertyName["ImmediateBaseConstraint"] = 4] = "ImmediateBaseConstraint";
34794         TypeSystemPropertyName[TypeSystemPropertyName["EnumTagType"] = 5] = "EnumTagType";
34795         TypeSystemPropertyName[TypeSystemPropertyName["ResolvedTypeArguments"] = 6] = "ResolvedTypeArguments";
34796     })(TypeSystemPropertyName || (TypeSystemPropertyName = {}));
34797     var CheckMode;
34798     (function (CheckMode) {
34799         CheckMode[CheckMode["Normal"] = 0] = "Normal";
34800         CheckMode[CheckMode["Contextual"] = 1] = "Contextual";
34801         CheckMode[CheckMode["Inferential"] = 2] = "Inferential";
34802         CheckMode[CheckMode["SkipContextSensitive"] = 4] = "SkipContextSensitive";
34803         CheckMode[CheckMode["SkipGenericFunctions"] = 8] = "SkipGenericFunctions";
34804         CheckMode[CheckMode["IsForSignatureHelp"] = 16] = "IsForSignatureHelp";
34805     })(CheckMode || (CheckMode = {}));
34806     var AccessFlags;
34807     (function (AccessFlags) {
34808         AccessFlags[AccessFlags["None"] = 0] = "None";
34809         AccessFlags[AccessFlags["NoIndexSignatures"] = 1] = "NoIndexSignatures";
34810         AccessFlags[AccessFlags["Writing"] = 2] = "Writing";
34811         AccessFlags[AccessFlags["CacheSymbol"] = 4] = "CacheSymbol";
34812         AccessFlags[AccessFlags["NoTupleBoundsCheck"] = 8] = "NoTupleBoundsCheck";
34813     })(AccessFlags || (AccessFlags = {}));
34814     var SignatureCheckMode;
34815     (function (SignatureCheckMode) {
34816         SignatureCheckMode[SignatureCheckMode["BivariantCallback"] = 1] = "BivariantCallback";
34817         SignatureCheckMode[SignatureCheckMode["StrictCallback"] = 2] = "StrictCallback";
34818         SignatureCheckMode[SignatureCheckMode["IgnoreReturnTypes"] = 4] = "IgnoreReturnTypes";
34819         SignatureCheckMode[SignatureCheckMode["StrictArity"] = 8] = "StrictArity";
34820         SignatureCheckMode[SignatureCheckMode["Callback"] = 3] = "Callback";
34821     })(SignatureCheckMode || (SignatureCheckMode = {}));
34822     var IntersectionState;
34823     (function (IntersectionState) {
34824         IntersectionState[IntersectionState["None"] = 0] = "None";
34825         IntersectionState[IntersectionState["Source"] = 1] = "Source";
34826         IntersectionState[IntersectionState["Target"] = 2] = "Target";
34827         IntersectionState[IntersectionState["PropertyCheck"] = 4] = "PropertyCheck";
34828         IntersectionState[IntersectionState["InPropertyCheck"] = 8] = "InPropertyCheck";
34829     })(IntersectionState || (IntersectionState = {}));
34830     var MappedTypeModifiers;
34831     (function (MappedTypeModifiers) {
34832         MappedTypeModifiers[MappedTypeModifiers["IncludeReadonly"] = 1] = "IncludeReadonly";
34833         MappedTypeModifiers[MappedTypeModifiers["ExcludeReadonly"] = 2] = "ExcludeReadonly";
34834         MappedTypeModifiers[MappedTypeModifiers["IncludeOptional"] = 4] = "IncludeOptional";
34835         MappedTypeModifiers[MappedTypeModifiers["ExcludeOptional"] = 8] = "ExcludeOptional";
34836     })(MappedTypeModifiers || (MappedTypeModifiers = {}));
34837     var ExpandingFlags;
34838     (function (ExpandingFlags) {
34839         ExpandingFlags[ExpandingFlags["None"] = 0] = "None";
34840         ExpandingFlags[ExpandingFlags["Source"] = 1] = "Source";
34841         ExpandingFlags[ExpandingFlags["Target"] = 2] = "Target";
34842         ExpandingFlags[ExpandingFlags["Both"] = 3] = "Both";
34843     })(ExpandingFlags || (ExpandingFlags = {}));
34844     var MembersOrExportsResolutionKind;
34845     (function (MembersOrExportsResolutionKind) {
34846         MembersOrExportsResolutionKind["resolvedExports"] = "resolvedExports";
34847         MembersOrExportsResolutionKind["resolvedMembers"] = "resolvedMembers";
34848     })(MembersOrExportsResolutionKind || (MembersOrExportsResolutionKind = {}));
34849     var UnusedKind;
34850     (function (UnusedKind) {
34851         UnusedKind[UnusedKind["Local"] = 0] = "Local";
34852         UnusedKind[UnusedKind["Parameter"] = 1] = "Parameter";
34853     })(UnusedKind || (UnusedKind = {}));
34854     var isNotOverloadAndNotAccessor = ts.and(isNotOverload, isNotAccessor);
34855     var DeclarationMeaning;
34856     (function (DeclarationMeaning) {
34857         DeclarationMeaning[DeclarationMeaning["GetAccessor"] = 1] = "GetAccessor";
34858         DeclarationMeaning[DeclarationMeaning["SetAccessor"] = 2] = "SetAccessor";
34859         DeclarationMeaning[DeclarationMeaning["PropertyAssignment"] = 4] = "PropertyAssignment";
34860         DeclarationMeaning[DeclarationMeaning["Method"] = 8] = "Method";
34861         DeclarationMeaning[DeclarationMeaning["GetOrSetAccessor"] = 3] = "GetOrSetAccessor";
34862         DeclarationMeaning[DeclarationMeaning["PropertyAssignmentOrMethod"] = 12] = "PropertyAssignmentOrMethod";
34863     })(DeclarationMeaning || (DeclarationMeaning = {}));
34864     var DeclarationSpaces;
34865     (function (DeclarationSpaces) {
34866         DeclarationSpaces[DeclarationSpaces["None"] = 0] = "None";
34867         DeclarationSpaces[DeclarationSpaces["ExportValue"] = 1] = "ExportValue";
34868         DeclarationSpaces[DeclarationSpaces["ExportType"] = 2] = "ExportType";
34869         DeclarationSpaces[DeclarationSpaces["ExportNamespace"] = 4] = "ExportNamespace";
34870     })(DeclarationSpaces || (DeclarationSpaces = {}));
34871     function SymbolLinks() {
34872     }
34873     function NodeLinks() {
34874         this.flags = 0;
34875     }
34876     function getNodeId(node) {
34877         if (!node.id) {
34878             node.id = nextNodeId;
34879             nextNodeId++;
34880         }
34881         return node.id;
34882     }
34883     ts.getNodeId = getNodeId;
34884     function getSymbolId(symbol) {
34885         if (!symbol.id) {
34886             symbol.id = nextSymbolId;
34887             nextSymbolId++;
34888         }
34889         return symbol.id;
34890     }
34891     ts.getSymbolId = getSymbolId;
34892     function isInstantiatedModule(node, preserveConstEnums) {
34893         var moduleState = ts.getModuleInstanceState(node);
34894         return moduleState === 1 /* Instantiated */ ||
34895             (preserveConstEnums && moduleState === 2 /* ConstEnumOnly */);
34896     }
34897     ts.isInstantiatedModule = isInstantiatedModule;
34898     function createTypeChecker(host, produceDiagnostics) {
34899         var getPackagesSet = ts.memoize(function () {
34900             var set = ts.createMap();
34901             host.getSourceFiles().forEach(function (sf) {
34902                 if (!sf.resolvedModules)
34903                     return;
34904                 ts.forEachEntry(sf.resolvedModules, function (r) {
34905                     if (r && r.packageId)
34906                         set.set(r.packageId.name, true);
34907                 });
34908             });
34909             return set;
34910         });
34911         // Cancellation that controls whether or not we can cancel in the middle of type checking.
34912         // In general cancelling is *not* safe for the type checker.  We might be in the middle of
34913         // computing something, and we will leave our internals in an inconsistent state.  Callers
34914         // who set the cancellation token should catch if a cancellation exception occurs, and
34915         // should throw away and create a new TypeChecker.
34916         //
34917         // Currently we only support setting the cancellation token when getting diagnostics.  This
34918         // is because diagnostics can be quite expensive, and we want to allow hosts to bail out if
34919         // they no longer need the information (for example, if the user started editing again).
34920         var cancellationToken;
34921         var requestedExternalEmitHelpers;
34922         var externalHelpersModule;
34923         var Symbol = ts.objectAllocator.getSymbolConstructor();
34924         var Type = ts.objectAllocator.getTypeConstructor();
34925         var Signature = ts.objectAllocator.getSignatureConstructor();
34926         var typeCount = 0;
34927         var symbolCount = 0;
34928         var enumCount = 0;
34929         var totalInstantiationCount = 0;
34930         var instantiationCount = 0;
34931         var instantiationDepth = 0;
34932         var constraintDepth = 0;
34933         var currentNode;
34934         var emptySymbols = ts.createSymbolTable();
34935         var arrayVariances = [1 /* Covariant */];
34936         var compilerOptions = host.getCompilerOptions();
34937         var languageVersion = ts.getEmitScriptTarget(compilerOptions);
34938         var moduleKind = ts.getEmitModuleKind(compilerOptions);
34939         var allowSyntheticDefaultImports = ts.getAllowSyntheticDefaultImports(compilerOptions);
34940         var strictNullChecks = ts.getStrictOptionValue(compilerOptions, "strictNullChecks");
34941         var strictFunctionTypes = ts.getStrictOptionValue(compilerOptions, "strictFunctionTypes");
34942         var strictBindCallApply = ts.getStrictOptionValue(compilerOptions, "strictBindCallApply");
34943         var strictPropertyInitialization = ts.getStrictOptionValue(compilerOptions, "strictPropertyInitialization");
34944         var noImplicitAny = ts.getStrictOptionValue(compilerOptions, "noImplicitAny");
34945         var noImplicitThis = ts.getStrictOptionValue(compilerOptions, "noImplicitThis");
34946         var keyofStringsOnly = !!compilerOptions.keyofStringsOnly;
34947         var freshObjectLiteralFlag = compilerOptions.suppressExcessPropertyErrors ? 0 : 32768 /* FreshLiteral */;
34948         var emitResolver = createResolver();
34949         var nodeBuilder = createNodeBuilder();
34950         var globals = ts.createSymbolTable();
34951         var undefinedSymbol = createSymbol(4 /* Property */, "undefined");
34952         undefinedSymbol.declarations = [];
34953         var globalThisSymbol = createSymbol(1536 /* Module */, "globalThis", 8 /* Readonly */);
34954         globalThisSymbol.exports = globals;
34955         globalThisSymbol.declarations = [];
34956         globals.set(globalThisSymbol.escapedName, globalThisSymbol);
34957         var argumentsSymbol = createSymbol(4 /* Property */, "arguments");
34958         var requireSymbol = createSymbol(4 /* Property */, "require");
34959         /** This will be set during calls to `getResolvedSignature` where services determines an apparent number of arguments greater than what is actually provided. */
34960         var apparentArgumentCount;
34961         // for public members that accept a Node or one of its subtypes, we must guard against
34962         // synthetic nodes created during transformations by calling `getParseTreeNode`.
34963         // for most of these, we perform the guard only on `checker` to avoid any possible
34964         // extra cost of calling `getParseTreeNode` when calling these functions from inside the
34965         // checker.
34966         var checker = {
34967             getNodeCount: function () { return ts.sum(host.getSourceFiles(), "nodeCount"); },
34968             getIdentifierCount: function () { return ts.sum(host.getSourceFiles(), "identifierCount"); },
34969             getSymbolCount: function () { return ts.sum(host.getSourceFiles(), "symbolCount") + symbolCount; },
34970             getTypeCount: function () { return typeCount; },
34971             getInstantiationCount: function () { return totalInstantiationCount; },
34972             getRelationCacheSizes: function () { return ({
34973                 assignable: assignableRelation.size,
34974                 identity: identityRelation.size,
34975                 subtype: subtypeRelation.size,
34976                 strictSubtype: strictSubtypeRelation.size,
34977             }); },
34978             isUndefinedSymbol: function (symbol) { return symbol === undefinedSymbol; },
34979             isArgumentsSymbol: function (symbol) { return symbol === argumentsSymbol; },
34980             isUnknownSymbol: function (symbol) { return symbol === unknownSymbol; },
34981             getMergedSymbol: getMergedSymbol,
34982             getDiagnostics: getDiagnostics,
34983             getGlobalDiagnostics: getGlobalDiagnostics,
34984             getTypeOfSymbolAtLocation: function (symbol, location) {
34985                 location = ts.getParseTreeNode(location);
34986                 return location ? getTypeOfSymbolAtLocation(symbol, location) : errorType;
34987             },
34988             getSymbolsOfParameterPropertyDeclaration: function (parameterIn, parameterName) {
34989                 var parameter = ts.getParseTreeNode(parameterIn, ts.isParameter);
34990                 if (parameter === undefined)
34991                     return ts.Debug.fail("Cannot get symbols of a synthetic parameter that cannot be resolved to a parse-tree node.");
34992                 return getSymbolsOfParameterPropertyDeclaration(parameter, ts.escapeLeadingUnderscores(parameterName));
34993             },
34994             getDeclaredTypeOfSymbol: getDeclaredTypeOfSymbol,
34995             getPropertiesOfType: getPropertiesOfType,
34996             getPropertyOfType: function (type, name) { return getPropertyOfType(type, ts.escapeLeadingUnderscores(name)); },
34997             getPrivateIdentifierPropertyOfType: function (leftType, name, location) {
34998                 var node = ts.getParseTreeNode(location);
34999                 if (!node) {
35000                     return undefined;
35001                 }
35002                 var propName = ts.escapeLeadingUnderscores(name);
35003                 var lexicallyScopedIdentifier = lookupSymbolForPrivateIdentifierDeclaration(propName, node);
35004                 return lexicallyScopedIdentifier ? getPrivateIdentifierPropertyOfType(leftType, lexicallyScopedIdentifier) : undefined;
35005             },
35006             getTypeOfPropertyOfType: function (type, name) { return getTypeOfPropertyOfType(type, ts.escapeLeadingUnderscores(name)); },
35007             getIndexInfoOfType: getIndexInfoOfType,
35008             getSignaturesOfType: getSignaturesOfType,
35009             getIndexTypeOfType: getIndexTypeOfType,
35010             getBaseTypes: getBaseTypes,
35011             getBaseTypeOfLiteralType: getBaseTypeOfLiteralType,
35012             getWidenedType: getWidenedType,
35013             getTypeFromTypeNode: function (nodeIn) {
35014                 var node = ts.getParseTreeNode(nodeIn, ts.isTypeNode);
35015                 return node ? getTypeFromTypeNode(node) : errorType;
35016             },
35017             getParameterType: getTypeAtPosition,
35018             getPromisedTypeOfPromise: getPromisedTypeOfPromise,
35019             getReturnTypeOfSignature: getReturnTypeOfSignature,
35020             isNullableType: isNullableType,
35021             getNullableType: getNullableType,
35022             getNonNullableType: getNonNullableType,
35023             getNonOptionalType: removeOptionalTypeMarker,
35024             getTypeArguments: getTypeArguments,
35025             typeToTypeNode: nodeBuilder.typeToTypeNode,
35026             indexInfoToIndexSignatureDeclaration: nodeBuilder.indexInfoToIndexSignatureDeclaration,
35027             signatureToSignatureDeclaration: nodeBuilder.signatureToSignatureDeclaration,
35028             symbolToEntityName: nodeBuilder.symbolToEntityName,
35029             symbolToExpression: nodeBuilder.symbolToExpression,
35030             symbolToTypeParameterDeclarations: nodeBuilder.symbolToTypeParameterDeclarations,
35031             symbolToParameterDeclaration: nodeBuilder.symbolToParameterDeclaration,
35032             typeParameterToDeclaration: nodeBuilder.typeParameterToDeclaration,
35033             getSymbolsInScope: function (location, meaning) {
35034                 location = ts.getParseTreeNode(location);
35035                 return location ? getSymbolsInScope(location, meaning) : [];
35036             },
35037             getSymbolAtLocation: function (node) {
35038                 node = ts.getParseTreeNode(node);
35039                 // set ignoreErrors: true because any lookups invoked by the API shouldn't cause any new errors
35040                 return node ? getSymbolAtLocation(node, /*ignoreErrors*/ true) : undefined;
35041             },
35042             getShorthandAssignmentValueSymbol: function (node) {
35043                 node = ts.getParseTreeNode(node);
35044                 return node ? getShorthandAssignmentValueSymbol(node) : undefined;
35045             },
35046             getExportSpecifierLocalTargetSymbol: function (nodeIn) {
35047                 var node = ts.getParseTreeNode(nodeIn, ts.isExportSpecifier);
35048                 return node ? getExportSpecifierLocalTargetSymbol(node) : undefined;
35049             },
35050             getExportSymbolOfSymbol: function (symbol) {
35051                 return getMergedSymbol(symbol.exportSymbol || symbol);
35052             },
35053             getTypeAtLocation: function (node) {
35054                 node = ts.getParseTreeNode(node);
35055                 return node ? getTypeOfNode(node) : errorType;
35056             },
35057             getTypeOfAssignmentPattern: function (nodeIn) {
35058                 var node = ts.getParseTreeNode(nodeIn, ts.isAssignmentPattern);
35059                 return node && getTypeOfAssignmentPattern(node) || errorType;
35060             },
35061             getPropertySymbolOfDestructuringAssignment: function (locationIn) {
35062                 var location = ts.getParseTreeNode(locationIn, ts.isIdentifier);
35063                 return location ? getPropertySymbolOfDestructuringAssignment(location) : undefined;
35064             },
35065             signatureToString: function (signature, enclosingDeclaration, flags, kind) {
35066                 return signatureToString(signature, ts.getParseTreeNode(enclosingDeclaration), flags, kind);
35067             },
35068             typeToString: function (type, enclosingDeclaration, flags) {
35069                 return typeToString(type, ts.getParseTreeNode(enclosingDeclaration), flags);
35070             },
35071             symbolToString: function (symbol, enclosingDeclaration, meaning, flags) {
35072                 return symbolToString(symbol, ts.getParseTreeNode(enclosingDeclaration), meaning, flags);
35073             },
35074             typePredicateToString: function (predicate, enclosingDeclaration, flags) {
35075                 return typePredicateToString(predicate, ts.getParseTreeNode(enclosingDeclaration), flags);
35076             },
35077             writeSignature: function (signature, enclosingDeclaration, flags, kind, writer) {
35078                 return signatureToString(signature, ts.getParseTreeNode(enclosingDeclaration), flags, kind, writer);
35079             },
35080             writeType: function (type, enclosingDeclaration, flags, writer) {
35081                 return typeToString(type, ts.getParseTreeNode(enclosingDeclaration), flags, writer);
35082             },
35083             writeSymbol: function (symbol, enclosingDeclaration, meaning, flags, writer) {
35084                 return symbolToString(symbol, ts.getParseTreeNode(enclosingDeclaration), meaning, flags, writer);
35085             },
35086             writeTypePredicate: function (predicate, enclosingDeclaration, flags, writer) {
35087                 return typePredicateToString(predicate, ts.getParseTreeNode(enclosingDeclaration), flags, writer);
35088             },
35089             getAugmentedPropertiesOfType: getAugmentedPropertiesOfType,
35090             getRootSymbols: getRootSymbols,
35091             getContextualType: function (nodeIn, contextFlags) {
35092                 var node = ts.getParseTreeNode(nodeIn, ts.isExpression);
35093                 if (!node) {
35094                     return undefined;
35095                 }
35096                 var containingCall = ts.findAncestor(node, ts.isCallLikeExpression);
35097                 var containingCallResolvedSignature = containingCall && getNodeLinks(containingCall).resolvedSignature;
35098                 if (contextFlags & 4 /* Completions */ && containingCall) {
35099                     var toMarkSkip = node;
35100                     do {
35101                         getNodeLinks(toMarkSkip).skipDirectInference = true;
35102                         toMarkSkip = toMarkSkip.parent;
35103                     } while (toMarkSkip && toMarkSkip !== containingCall);
35104                     getNodeLinks(containingCall).resolvedSignature = undefined;
35105                 }
35106                 var result = getContextualType(node, contextFlags);
35107                 if (contextFlags & 4 /* Completions */ && containingCall) {
35108                     var toMarkSkip = node;
35109                     do {
35110                         getNodeLinks(toMarkSkip).skipDirectInference = undefined;
35111                         toMarkSkip = toMarkSkip.parent;
35112                     } while (toMarkSkip && toMarkSkip !== containingCall);
35113                     getNodeLinks(containingCall).resolvedSignature = containingCallResolvedSignature;
35114                 }
35115                 return result;
35116             },
35117             getContextualTypeForObjectLiteralElement: function (nodeIn) {
35118                 var node = ts.getParseTreeNode(nodeIn, ts.isObjectLiteralElementLike);
35119                 return node ? getContextualTypeForObjectLiteralElement(node) : undefined;
35120             },
35121             getContextualTypeForArgumentAtIndex: function (nodeIn, argIndex) {
35122                 var node = ts.getParseTreeNode(nodeIn, ts.isCallLikeExpression);
35123                 return node && getContextualTypeForArgumentAtIndex(node, argIndex);
35124             },
35125             getContextualTypeForJsxAttribute: function (nodeIn) {
35126                 var node = ts.getParseTreeNode(nodeIn, ts.isJsxAttributeLike);
35127                 return node && getContextualTypeForJsxAttribute(node);
35128             },
35129             isContextSensitive: isContextSensitive,
35130             getFullyQualifiedName: getFullyQualifiedName,
35131             getResolvedSignature: function (node, candidatesOutArray, argumentCount) {
35132                 return getResolvedSignatureWorker(node, candidatesOutArray, argumentCount, 0 /* Normal */);
35133             },
35134             getResolvedSignatureForSignatureHelp: function (node, candidatesOutArray, argumentCount) {
35135                 return getResolvedSignatureWorker(node, candidatesOutArray, argumentCount, 16 /* IsForSignatureHelp */);
35136             },
35137             getExpandedParameters: getExpandedParameters,
35138             hasEffectiveRestParameter: hasEffectiveRestParameter,
35139             getConstantValue: function (nodeIn) {
35140                 var node = ts.getParseTreeNode(nodeIn, canHaveConstantValue);
35141                 return node ? getConstantValue(node) : undefined;
35142             },
35143             isValidPropertyAccess: function (nodeIn, propertyName) {
35144                 var node = ts.getParseTreeNode(nodeIn, ts.isPropertyAccessOrQualifiedNameOrImportTypeNode);
35145                 return !!node && isValidPropertyAccess(node, ts.escapeLeadingUnderscores(propertyName));
35146             },
35147             isValidPropertyAccessForCompletions: function (nodeIn, type, property) {
35148                 var node = ts.getParseTreeNode(nodeIn, ts.isPropertyAccessExpression);
35149                 return !!node && isValidPropertyAccessForCompletions(node, type, property);
35150             },
35151             getSignatureFromDeclaration: function (declarationIn) {
35152                 var declaration = ts.getParseTreeNode(declarationIn, ts.isFunctionLike);
35153                 return declaration ? getSignatureFromDeclaration(declaration) : undefined;
35154             },
35155             isImplementationOfOverload: function (node) {
35156                 var parsed = ts.getParseTreeNode(node, ts.isFunctionLike);
35157                 return parsed ? isImplementationOfOverload(parsed) : undefined;
35158             },
35159             getImmediateAliasedSymbol: getImmediateAliasedSymbol,
35160             getAliasedSymbol: resolveAlias,
35161             getEmitResolver: getEmitResolver,
35162             getExportsOfModule: getExportsOfModuleAsArray,
35163             getExportsAndPropertiesOfModule: getExportsAndPropertiesOfModule,
35164             getSymbolWalker: ts.createGetSymbolWalker(getRestTypeOfSignature, getTypePredicateOfSignature, getReturnTypeOfSignature, getBaseTypes, resolveStructuredTypeMembers, getTypeOfSymbol, getResolvedSymbol, getIndexTypeOfStructuredType, getConstraintOfTypeParameter, ts.getFirstIdentifier, getTypeArguments),
35165             getAmbientModules: getAmbientModules,
35166             getJsxIntrinsicTagNamesAt: getJsxIntrinsicTagNamesAt,
35167             isOptionalParameter: function (nodeIn) {
35168                 var node = ts.getParseTreeNode(nodeIn, ts.isParameter);
35169                 return node ? isOptionalParameter(node) : false;
35170             },
35171             tryGetMemberInModuleExports: function (name, symbol) { return tryGetMemberInModuleExports(ts.escapeLeadingUnderscores(name), symbol); },
35172             tryGetMemberInModuleExportsAndProperties: function (name, symbol) { return tryGetMemberInModuleExportsAndProperties(ts.escapeLeadingUnderscores(name), symbol); },
35173             tryFindAmbientModuleWithoutAugmentations: function (moduleName) {
35174                 // we deliberately exclude augmentations
35175                 // since we are only interested in declarations of the module itself
35176                 return tryFindAmbientModule(moduleName, /*withAugmentations*/ false);
35177             },
35178             getApparentType: getApparentType,
35179             getUnionType: getUnionType,
35180             isTypeAssignableTo: isTypeAssignableTo,
35181             createAnonymousType: createAnonymousType,
35182             createSignature: createSignature,
35183             createSymbol: createSymbol,
35184             createIndexInfo: createIndexInfo,
35185             getAnyType: function () { return anyType; },
35186             getStringType: function () { return stringType; },
35187             getNumberType: function () { return numberType; },
35188             createPromiseType: createPromiseType,
35189             createArrayType: createArrayType,
35190             getElementTypeOfArrayType: getElementTypeOfArrayType,
35191             getBooleanType: function () { return booleanType; },
35192             getFalseType: function (fresh) { return fresh ? falseType : regularFalseType; },
35193             getTrueType: function (fresh) { return fresh ? trueType : regularTrueType; },
35194             getVoidType: function () { return voidType; },
35195             getUndefinedType: function () { return undefinedType; },
35196             getNullType: function () { return nullType; },
35197             getESSymbolType: function () { return esSymbolType; },
35198             getNeverType: function () { return neverType; },
35199             getOptionalType: function () { return optionalType; },
35200             isSymbolAccessible: isSymbolAccessible,
35201             isArrayType: isArrayType,
35202             isTupleType: isTupleType,
35203             isArrayLikeType: isArrayLikeType,
35204             isTypeInvalidDueToUnionDiscriminant: isTypeInvalidDueToUnionDiscriminant,
35205             getAllPossiblePropertiesOfTypes: getAllPossiblePropertiesOfTypes,
35206             getSuggestedSymbolForNonexistentProperty: getSuggestedSymbolForNonexistentProperty,
35207             getSuggestionForNonexistentProperty: getSuggestionForNonexistentProperty,
35208             getSuggestedSymbolForNonexistentSymbol: function (location, name, meaning) { return getSuggestedSymbolForNonexistentSymbol(location, ts.escapeLeadingUnderscores(name), meaning); },
35209             getSuggestionForNonexistentSymbol: function (location, name, meaning) { return getSuggestionForNonexistentSymbol(location, ts.escapeLeadingUnderscores(name), meaning); },
35210             getSuggestedSymbolForNonexistentModule: getSuggestedSymbolForNonexistentModule,
35211             getSuggestionForNonexistentExport: getSuggestionForNonexistentExport,
35212             getBaseConstraintOfType: getBaseConstraintOfType,
35213             getDefaultFromTypeParameter: function (type) { return type && type.flags & 262144 /* TypeParameter */ ? getDefaultFromTypeParameter(type) : undefined; },
35214             resolveName: function (name, location, meaning, excludeGlobals) {
35215                 return resolveName(location, ts.escapeLeadingUnderscores(name), meaning, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false, excludeGlobals);
35216             },
35217             getJsxNamespace: function (n) { return ts.unescapeLeadingUnderscores(getJsxNamespace(n)); },
35218             getAccessibleSymbolChain: getAccessibleSymbolChain,
35219             getTypePredicateOfSignature: getTypePredicateOfSignature,
35220             resolveExternalModuleName: function (moduleSpecifier) {
35221                 return resolveExternalModuleName(moduleSpecifier, moduleSpecifier, /*ignoreErrors*/ true);
35222             },
35223             resolveExternalModuleSymbol: resolveExternalModuleSymbol,
35224             tryGetThisTypeAt: function (node, includeGlobalThis) {
35225                 node = ts.getParseTreeNode(node);
35226                 return node && tryGetThisTypeAt(node, includeGlobalThis);
35227             },
35228             getTypeArgumentConstraint: function (nodeIn) {
35229                 var node = ts.getParseTreeNode(nodeIn, ts.isTypeNode);
35230                 return node && getTypeArgumentConstraint(node);
35231             },
35232             getSuggestionDiagnostics: function (file, ct) {
35233                 if (ts.skipTypeChecking(file, compilerOptions, host)) {
35234                     return ts.emptyArray;
35235                 }
35236                 var diagnostics;
35237                 try {
35238                     // Record the cancellation token so it can be checked later on during checkSourceElement.
35239                     // Do this in a finally block so we can ensure that it gets reset back to nothing after
35240                     // this call is done.
35241                     cancellationToken = ct;
35242                     // Ensure file is type checked
35243                     checkSourceFile(file);
35244                     ts.Debug.assert(!!(getNodeLinks(file).flags & 1 /* TypeChecked */));
35245                     diagnostics = ts.addRange(diagnostics, suggestionDiagnostics.getDiagnostics(file.fileName));
35246                     checkUnusedIdentifiers(getPotentiallyUnusedIdentifiers(file), function (containingNode, kind, diag) {
35247                         if (!ts.containsParseError(containingNode) && !unusedIsError(kind, !!(containingNode.flags & 8388608 /* Ambient */))) {
35248                             (diagnostics || (diagnostics = [])).push(__assign(__assign({}, diag), { category: ts.DiagnosticCategory.Suggestion }));
35249                         }
35250                     });
35251                     return diagnostics || ts.emptyArray;
35252                 }
35253                 finally {
35254                     cancellationToken = undefined;
35255                 }
35256             },
35257             runWithCancellationToken: function (token, callback) {
35258                 try {
35259                     cancellationToken = token;
35260                     return callback(checker);
35261                 }
35262                 finally {
35263                     cancellationToken = undefined;
35264                 }
35265             },
35266             getLocalTypeParametersOfClassOrInterfaceOrTypeAlias: getLocalTypeParametersOfClassOrInterfaceOrTypeAlias,
35267             isDeclarationVisible: isDeclarationVisible,
35268         };
35269         function getResolvedSignatureWorker(nodeIn, candidatesOutArray, argumentCount, checkMode) {
35270             var node = ts.getParseTreeNode(nodeIn, ts.isCallLikeExpression);
35271             apparentArgumentCount = argumentCount;
35272             var res = node ? getResolvedSignature(node, candidatesOutArray, checkMode) : undefined;
35273             apparentArgumentCount = undefined;
35274             return res;
35275         }
35276         var tupleTypes = ts.createMap();
35277         var unionTypes = ts.createMap();
35278         var intersectionTypes = ts.createMap();
35279         var literalTypes = ts.createMap();
35280         var indexedAccessTypes = ts.createMap();
35281         var substitutionTypes = ts.createMap();
35282         var evolvingArrayTypes = [];
35283         var undefinedProperties = ts.createMap();
35284         var unknownSymbol = createSymbol(4 /* Property */, "unknown");
35285         var resolvingSymbol = createSymbol(0, "__resolving__" /* Resolving */);
35286         var anyType = createIntrinsicType(1 /* Any */, "any");
35287         var autoType = createIntrinsicType(1 /* Any */, "any");
35288         var wildcardType = createIntrinsicType(1 /* Any */, "any");
35289         var errorType = createIntrinsicType(1 /* Any */, "error");
35290         var nonInferrableAnyType = createIntrinsicType(1 /* Any */, "any", 524288 /* ContainsWideningType */);
35291         var unknownType = createIntrinsicType(2 /* Unknown */, "unknown");
35292         var undefinedType = createIntrinsicType(32768 /* Undefined */, "undefined");
35293         var undefinedWideningType = strictNullChecks ? undefinedType : createIntrinsicType(32768 /* Undefined */, "undefined", 524288 /* ContainsWideningType */);
35294         var optionalType = createIntrinsicType(32768 /* Undefined */, "undefined");
35295         var nullType = createIntrinsicType(65536 /* Null */, "null");
35296         var nullWideningType = strictNullChecks ? nullType : createIntrinsicType(65536 /* Null */, "null", 524288 /* ContainsWideningType */);
35297         var stringType = createIntrinsicType(4 /* String */, "string");
35298         var numberType = createIntrinsicType(8 /* Number */, "number");
35299         var bigintType = createIntrinsicType(64 /* BigInt */, "bigint");
35300         var falseType = createIntrinsicType(512 /* BooleanLiteral */, "false");
35301         var regularFalseType = createIntrinsicType(512 /* BooleanLiteral */, "false");
35302         var trueType = createIntrinsicType(512 /* BooleanLiteral */, "true");
35303         var regularTrueType = createIntrinsicType(512 /* BooleanLiteral */, "true");
35304         trueType.regularType = regularTrueType;
35305         trueType.freshType = trueType;
35306         regularTrueType.regularType = regularTrueType;
35307         regularTrueType.freshType = trueType;
35308         falseType.regularType = regularFalseType;
35309         falseType.freshType = falseType;
35310         regularFalseType.regularType = regularFalseType;
35311         regularFalseType.freshType = falseType;
35312         var booleanType = createBooleanType([regularFalseType, regularTrueType]);
35313         // Also mark all combinations of fresh/regular booleans as "Boolean" so they print as `boolean` instead of `true | false`
35314         // (The union is cached, so simply doing the marking here is sufficient)
35315         createBooleanType([regularFalseType, trueType]);
35316         createBooleanType([falseType, regularTrueType]);
35317         createBooleanType([falseType, trueType]);
35318         var esSymbolType = createIntrinsicType(4096 /* ESSymbol */, "symbol");
35319         var voidType = createIntrinsicType(16384 /* Void */, "void");
35320         var neverType = createIntrinsicType(131072 /* Never */, "never");
35321         var silentNeverType = createIntrinsicType(131072 /* Never */, "never");
35322         var nonInferrableType = createIntrinsicType(131072 /* Never */, "never", 2097152 /* NonInferrableType */);
35323         var implicitNeverType = createIntrinsicType(131072 /* Never */, "never");
35324         var unreachableNeverType = createIntrinsicType(131072 /* Never */, "never");
35325         var nonPrimitiveType = createIntrinsicType(67108864 /* NonPrimitive */, "object");
35326         var stringNumberSymbolType = getUnionType([stringType, numberType, esSymbolType]);
35327         var keyofConstraintType = keyofStringsOnly ? stringType : stringNumberSymbolType;
35328         var numberOrBigIntType = getUnionType([numberType, bigintType]);
35329         var restrictiveMapper = makeFunctionTypeMapper(function (t) { return t.flags & 262144 /* TypeParameter */ ? getRestrictiveTypeParameter(t) : t; });
35330         var permissiveMapper = makeFunctionTypeMapper(function (t) { return t.flags & 262144 /* TypeParameter */ ? wildcardType : t; });
35331         var emptyObjectType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined);
35332         var emptyJsxObjectType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined);
35333         emptyJsxObjectType.objectFlags |= 4096 /* JsxAttributes */;
35334         var emptyTypeLiteralSymbol = createSymbol(2048 /* TypeLiteral */, "__type" /* Type */);
35335         emptyTypeLiteralSymbol.members = ts.createSymbolTable();
35336         var emptyTypeLiteralType = createAnonymousType(emptyTypeLiteralSymbol, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined);
35337         var emptyGenericType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined);
35338         emptyGenericType.instantiations = ts.createMap();
35339         var anyFunctionType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined);
35340         // The anyFunctionType contains the anyFunctionType by definition. The flag is further propagated
35341         // in getPropagatingFlagsOfTypes, and it is checked in inferFromTypes.
35342         anyFunctionType.objectFlags |= 2097152 /* NonInferrableType */;
35343         var noConstraintType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined);
35344         var circularConstraintType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined);
35345         var resolvingDefaultType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined);
35346         var markerSuperType = createTypeParameter();
35347         var markerSubType = createTypeParameter();
35348         markerSubType.constraint = markerSuperType;
35349         var markerOtherType = createTypeParameter();
35350         var noTypePredicate = createTypePredicate(1 /* Identifier */, "<<unresolved>>", 0, anyType);
35351         var anySignature = createSignature(undefined, undefined, undefined, ts.emptyArray, anyType, /*resolvedTypePredicate*/ undefined, 0, 0 /* None */);
35352         var unknownSignature = createSignature(undefined, undefined, undefined, ts.emptyArray, errorType, /*resolvedTypePredicate*/ undefined, 0, 0 /* None */);
35353         var resolvingSignature = createSignature(undefined, undefined, undefined, ts.emptyArray, anyType, /*resolvedTypePredicate*/ undefined, 0, 0 /* None */);
35354         var silentNeverSignature = createSignature(undefined, undefined, undefined, ts.emptyArray, silentNeverType, /*resolvedTypePredicate*/ undefined, 0, 0 /* None */);
35355         var enumNumberIndexInfo = createIndexInfo(stringType, /*isReadonly*/ true);
35356         var iterationTypesCache = ts.createMap(); // cache for common IterationTypes instances
35357         var noIterationTypes = {
35358             get yieldType() { return ts.Debug.fail("Not supported"); },
35359             get returnType() { return ts.Debug.fail("Not supported"); },
35360             get nextType() { return ts.Debug.fail("Not supported"); },
35361         };
35362         var anyIterationTypes = createIterationTypes(anyType, anyType, anyType);
35363         var anyIterationTypesExceptNext = createIterationTypes(anyType, anyType, unknownType);
35364         var defaultIterationTypes = createIterationTypes(neverType, anyType, undefinedType); // default iteration types for `Iterator`.
35365         var asyncIterationTypesResolver = {
35366             iterableCacheKey: "iterationTypesOfAsyncIterable",
35367             iteratorCacheKey: "iterationTypesOfAsyncIterator",
35368             iteratorSymbolName: "asyncIterator",
35369             getGlobalIteratorType: getGlobalAsyncIteratorType,
35370             getGlobalIterableType: getGlobalAsyncIterableType,
35371             getGlobalIterableIteratorType: getGlobalAsyncIterableIteratorType,
35372             getGlobalGeneratorType: getGlobalAsyncGeneratorType,
35373             resolveIterationType: getAwaitedType,
35374             mustHaveANextMethodDiagnostic: ts.Diagnostics.An_async_iterator_must_have_a_next_method,
35375             mustBeAMethodDiagnostic: ts.Diagnostics.The_0_property_of_an_async_iterator_must_be_a_method,
35376             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,
35377         };
35378         var syncIterationTypesResolver = {
35379             iterableCacheKey: "iterationTypesOfIterable",
35380             iteratorCacheKey: "iterationTypesOfIterator",
35381             iteratorSymbolName: "iterator",
35382             getGlobalIteratorType: getGlobalIteratorType,
35383             getGlobalIterableType: getGlobalIterableType,
35384             getGlobalIterableIteratorType: getGlobalIterableIteratorType,
35385             getGlobalGeneratorType: getGlobalGeneratorType,
35386             resolveIterationType: function (type, _errorNode) { return type; },
35387             mustHaveANextMethodDiagnostic: ts.Diagnostics.An_iterator_must_have_a_next_method,
35388             mustBeAMethodDiagnostic: ts.Diagnostics.The_0_property_of_an_iterator_must_be_a_method,
35389             mustHaveAValueDiagnostic: ts.Diagnostics.The_type_returned_by_the_0_method_of_an_iterator_must_have_a_value_property,
35390         };
35391         /** Key is "/path/to/a.ts|/path/to/b.ts". */
35392         var amalgamatedDuplicates;
35393         var reverseMappedCache = ts.createMap();
35394         var ambientModulesCache;
35395         /**
35396          * List of every ambient module with a "*" wildcard.
35397          * Unlike other ambient modules, these can't be stored in `globals` because symbol tables only deal with exact matches.
35398          * This is only used if there is no exact match.
35399          */
35400         var patternAmbientModules;
35401         var patternAmbientModuleAugmentations;
35402         var globalObjectType;
35403         var globalFunctionType;
35404         var globalCallableFunctionType;
35405         var globalNewableFunctionType;
35406         var globalArrayType;
35407         var globalReadonlyArrayType;
35408         var globalStringType;
35409         var globalNumberType;
35410         var globalBooleanType;
35411         var globalRegExpType;
35412         var globalThisType;
35413         var anyArrayType;
35414         var autoArrayType;
35415         var anyReadonlyArrayType;
35416         var deferredGlobalNonNullableTypeAlias;
35417         // The library files are only loaded when the feature is used.
35418         // This allows users to just specify library files they want to used through --lib
35419         // and they will not get an error from not having unrelated library files
35420         var deferredGlobalESSymbolConstructorSymbol;
35421         var deferredGlobalESSymbolType;
35422         var deferredGlobalTypedPropertyDescriptorType;
35423         var deferredGlobalPromiseType;
35424         var deferredGlobalPromiseLikeType;
35425         var deferredGlobalPromiseConstructorSymbol;
35426         var deferredGlobalPromiseConstructorLikeType;
35427         var deferredGlobalIterableType;
35428         var deferredGlobalIteratorType;
35429         var deferredGlobalIterableIteratorType;
35430         var deferredGlobalGeneratorType;
35431         var deferredGlobalIteratorYieldResultType;
35432         var deferredGlobalIteratorReturnResultType;
35433         var deferredGlobalAsyncIterableType;
35434         var deferredGlobalAsyncIteratorType;
35435         var deferredGlobalAsyncIterableIteratorType;
35436         var deferredGlobalAsyncGeneratorType;
35437         var deferredGlobalTemplateStringsArrayType;
35438         var deferredGlobalImportMetaType;
35439         var deferredGlobalExtractSymbol;
35440         var deferredGlobalOmitSymbol;
35441         var deferredGlobalBigIntType;
35442         var allPotentiallyUnusedIdentifiers = ts.createMap(); // key is file name
35443         var flowLoopStart = 0;
35444         var flowLoopCount = 0;
35445         var sharedFlowCount = 0;
35446         var flowAnalysisDisabled = false;
35447         var flowInvocationCount = 0;
35448         var lastFlowNode;
35449         var lastFlowNodeReachable;
35450         var flowTypeCache;
35451         var emptyStringType = getLiteralType("");
35452         var zeroType = getLiteralType(0);
35453         var zeroBigIntType = getLiteralType({ negative: false, base10Value: "0" });
35454         var resolutionTargets = [];
35455         var resolutionResults = [];
35456         var resolutionPropertyNames = [];
35457         var suggestionCount = 0;
35458         var maximumSuggestionCount = 10;
35459         var mergedSymbols = [];
35460         var symbolLinks = [];
35461         var nodeLinks = [];
35462         var flowLoopCaches = [];
35463         var flowLoopNodes = [];
35464         var flowLoopKeys = [];
35465         var flowLoopTypes = [];
35466         var sharedFlowNodes = [];
35467         var sharedFlowTypes = [];
35468         var flowNodeReachable = [];
35469         var potentialThisCollisions = [];
35470         var potentialNewTargetCollisions = [];
35471         var potentialWeakMapCollisions = [];
35472         var awaitedTypeStack = [];
35473         var diagnostics = ts.createDiagnosticCollection();
35474         var suggestionDiagnostics = ts.createDiagnosticCollection();
35475         var typeofTypesByName = ts.createMapFromTemplate({
35476             string: stringType,
35477             number: numberType,
35478             bigint: bigintType,
35479             boolean: booleanType,
35480             symbol: esSymbolType,
35481             undefined: undefinedType
35482         });
35483         var typeofType = createTypeofType();
35484         var _jsxNamespace;
35485         var _jsxFactoryEntity;
35486         var outofbandVarianceMarkerHandler;
35487         var subtypeRelation = ts.createMap();
35488         var strictSubtypeRelation = ts.createMap();
35489         var assignableRelation = ts.createMap();
35490         var comparableRelation = ts.createMap();
35491         var identityRelation = ts.createMap();
35492         var enumRelation = ts.createMap();
35493         var builtinGlobals = ts.createSymbolTable();
35494         builtinGlobals.set(undefinedSymbol.escapedName, undefinedSymbol);
35495         initializeTypeChecker();
35496         return checker;
35497         function getJsxNamespace(location) {
35498             if (location) {
35499                 var file = ts.getSourceFileOfNode(location);
35500                 if (file) {
35501                     if (file.localJsxNamespace) {
35502                         return file.localJsxNamespace;
35503                     }
35504                     var jsxPragma = file.pragmas.get("jsx");
35505                     if (jsxPragma) {
35506                         var chosenpragma = ts.isArray(jsxPragma) ? jsxPragma[0] : jsxPragma;
35507                         file.localJsxFactory = ts.parseIsolatedEntityName(chosenpragma.arguments.factory, languageVersion);
35508                         ts.visitNode(file.localJsxFactory, markAsSynthetic);
35509                         if (file.localJsxFactory) {
35510                             return file.localJsxNamespace = ts.getFirstIdentifier(file.localJsxFactory).escapedText;
35511                         }
35512                     }
35513                 }
35514             }
35515             if (!_jsxNamespace) {
35516                 _jsxNamespace = "React";
35517                 if (compilerOptions.jsxFactory) {
35518                     _jsxFactoryEntity = ts.parseIsolatedEntityName(compilerOptions.jsxFactory, languageVersion);
35519                     ts.visitNode(_jsxFactoryEntity, markAsSynthetic);
35520                     if (_jsxFactoryEntity) {
35521                         _jsxNamespace = ts.getFirstIdentifier(_jsxFactoryEntity).escapedText;
35522                     }
35523                 }
35524                 else if (compilerOptions.reactNamespace) {
35525                     _jsxNamespace = ts.escapeLeadingUnderscores(compilerOptions.reactNamespace);
35526                 }
35527             }
35528             if (!_jsxFactoryEntity) {
35529                 _jsxFactoryEntity = ts.createQualifiedName(ts.createIdentifier(ts.unescapeLeadingUnderscores(_jsxNamespace)), "createElement");
35530             }
35531             return _jsxNamespace;
35532             function markAsSynthetic(node) {
35533                 node.pos = -1;
35534                 node.end = -1;
35535                 return ts.visitEachChild(node, markAsSynthetic, ts.nullTransformationContext);
35536             }
35537         }
35538         function getEmitResolver(sourceFile, cancellationToken) {
35539             // Ensure we have all the type information in place for this file so that all the
35540             // emitter questions of this resolver will return the right information.
35541             getDiagnostics(sourceFile, cancellationToken);
35542             return emitResolver;
35543         }
35544         function lookupOrIssueError(location, message, arg0, arg1, arg2, arg3) {
35545             var diagnostic = location
35546                 ? ts.createDiagnosticForNode(location, message, arg0, arg1, arg2, arg3)
35547                 : ts.createCompilerDiagnostic(message, arg0, arg1, arg2, arg3);
35548             var existing = diagnostics.lookup(diagnostic);
35549             if (existing) {
35550                 return existing;
35551             }
35552             else {
35553                 diagnostics.add(diagnostic);
35554                 return diagnostic;
35555             }
35556         }
35557         function error(location, message, arg0, arg1, arg2, arg3) {
35558             var diagnostic = location
35559                 ? ts.createDiagnosticForNode(location, message, arg0, arg1, arg2, arg3)
35560                 : ts.createCompilerDiagnostic(message, arg0, arg1, arg2, arg3);
35561             diagnostics.add(diagnostic);
35562             return diagnostic;
35563         }
35564         function addErrorOrSuggestion(isError, diagnostic) {
35565             if (isError) {
35566                 diagnostics.add(diagnostic);
35567             }
35568             else {
35569                 suggestionDiagnostics.add(__assign(__assign({}, diagnostic), { category: ts.DiagnosticCategory.Suggestion }));
35570             }
35571         }
35572         function errorOrSuggestion(isError, location, message, arg0, arg1, arg2, arg3) {
35573             addErrorOrSuggestion(isError, "message" in message ? ts.createDiagnosticForNode(location, message, arg0, arg1, arg2, arg3) : ts.createDiagnosticForNodeFromMessageChain(location, message)); // eslint-disable-line no-in-operator
35574         }
35575         function errorAndMaybeSuggestAwait(location, maybeMissingAwait, message, arg0, arg1, arg2, arg3) {
35576             var diagnostic = error(location, message, arg0, arg1, arg2, arg3);
35577             if (maybeMissingAwait) {
35578                 var related = ts.createDiagnosticForNode(location, ts.Diagnostics.Did_you_forget_to_use_await);
35579                 ts.addRelatedInfo(diagnostic, related);
35580             }
35581             return diagnostic;
35582         }
35583         function createSymbol(flags, name, checkFlags) {
35584             symbolCount++;
35585             var symbol = (new Symbol(flags | 33554432 /* Transient */, name));
35586             symbol.checkFlags = checkFlags || 0;
35587             return symbol;
35588         }
35589         function getExcludedSymbolFlags(flags) {
35590             var result = 0;
35591             if (flags & 2 /* BlockScopedVariable */)
35592                 result |= 111551 /* BlockScopedVariableExcludes */;
35593             if (flags & 1 /* FunctionScopedVariable */)
35594                 result |= 111550 /* FunctionScopedVariableExcludes */;
35595             if (flags & 4 /* Property */)
35596                 result |= 0 /* PropertyExcludes */;
35597             if (flags & 8 /* EnumMember */)
35598                 result |= 900095 /* EnumMemberExcludes */;
35599             if (flags & 16 /* Function */)
35600                 result |= 110991 /* FunctionExcludes */;
35601             if (flags & 32 /* Class */)
35602                 result |= 899503 /* ClassExcludes */;
35603             if (flags & 64 /* Interface */)
35604                 result |= 788872 /* InterfaceExcludes */;
35605             if (flags & 256 /* RegularEnum */)
35606                 result |= 899327 /* RegularEnumExcludes */;
35607             if (flags & 128 /* ConstEnum */)
35608                 result |= 899967 /* ConstEnumExcludes */;
35609             if (flags & 512 /* ValueModule */)
35610                 result |= 110735 /* ValueModuleExcludes */;
35611             if (flags & 8192 /* Method */)
35612                 result |= 103359 /* MethodExcludes */;
35613             if (flags & 32768 /* GetAccessor */)
35614                 result |= 46015 /* GetAccessorExcludes */;
35615             if (flags & 65536 /* SetAccessor */)
35616                 result |= 78783 /* SetAccessorExcludes */;
35617             if (flags & 262144 /* TypeParameter */)
35618                 result |= 526824 /* TypeParameterExcludes */;
35619             if (flags & 524288 /* TypeAlias */)
35620                 result |= 788968 /* TypeAliasExcludes */;
35621             if (flags & 2097152 /* Alias */)
35622                 result |= 2097152 /* AliasExcludes */;
35623             return result;
35624         }
35625         function recordMergedSymbol(target, source) {
35626             if (!source.mergeId) {
35627                 source.mergeId = nextMergeId;
35628                 nextMergeId++;
35629             }
35630             mergedSymbols[source.mergeId] = target;
35631         }
35632         function cloneSymbol(symbol) {
35633             var result = createSymbol(symbol.flags, symbol.escapedName);
35634             result.declarations = symbol.declarations ? symbol.declarations.slice() : [];
35635             result.parent = symbol.parent;
35636             if (symbol.valueDeclaration)
35637                 result.valueDeclaration = symbol.valueDeclaration;
35638             if (symbol.constEnumOnlyModule)
35639                 result.constEnumOnlyModule = true;
35640             if (symbol.members)
35641                 result.members = ts.cloneMap(symbol.members);
35642             if (symbol.exports)
35643                 result.exports = ts.cloneMap(symbol.exports);
35644             recordMergedSymbol(result, symbol);
35645             return result;
35646         }
35647         /**
35648          * Note: if target is transient, then it is mutable, and mergeSymbol with both mutate and return it.
35649          * If target is not transient, mergeSymbol will produce a transient clone, mutate that and return it.
35650          */
35651         function mergeSymbol(target, source, unidirectional) {
35652             if (unidirectional === void 0) { unidirectional = false; }
35653             if (!(target.flags & getExcludedSymbolFlags(source.flags)) ||
35654                 (source.flags | target.flags) & 67108864 /* Assignment */) {
35655                 if (source === target) {
35656                     // This can happen when an export assigned namespace exports something also erroneously exported at the top level
35657                     // See `declarationFileNoCrashOnExtraExportModifier` for an example
35658                     return target;
35659                 }
35660                 if (!(target.flags & 33554432 /* Transient */)) {
35661                     var resolvedTarget = resolveSymbol(target);
35662                     if (resolvedTarget === unknownSymbol) {
35663                         return source;
35664                     }
35665                     target = cloneSymbol(resolvedTarget);
35666                 }
35667                 // Javascript static-property-assignment declarations always merge, even though they are also values
35668                 if (source.flags & 512 /* ValueModule */ && target.flags & 512 /* ValueModule */ && target.constEnumOnlyModule && !source.constEnumOnlyModule) {
35669                     // reset flag when merging instantiated module into value module that has only const enums
35670                     target.constEnumOnlyModule = false;
35671                 }
35672                 target.flags |= source.flags;
35673                 if (source.valueDeclaration) {
35674                     ts.setValueDeclaration(target, source.valueDeclaration);
35675                 }
35676                 ts.addRange(target.declarations, source.declarations);
35677                 if (source.members) {
35678                     if (!target.members)
35679                         target.members = ts.createSymbolTable();
35680                     mergeSymbolTable(target.members, source.members, unidirectional);
35681                 }
35682                 if (source.exports) {
35683                     if (!target.exports)
35684                         target.exports = ts.createSymbolTable();
35685                     mergeSymbolTable(target.exports, source.exports, unidirectional);
35686                 }
35687                 if (!unidirectional) {
35688                     recordMergedSymbol(target, source);
35689                 }
35690             }
35691             else if (target.flags & 1024 /* NamespaceModule */) {
35692                 // Do not report an error when merging `var globalThis` with the built-in `globalThis`,
35693                 // as we will already report a "Declaration name conflicts..." error, and this error
35694                 // won't make much sense.
35695                 if (target !== globalThisSymbol) {
35696                     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));
35697                 }
35698             }
35699             else { // error
35700                 var isEitherEnum = !!(target.flags & 384 /* Enum */ || source.flags & 384 /* Enum */);
35701                 var isEitherBlockScoped_1 = !!(target.flags & 2 /* BlockScopedVariable */ || source.flags & 2 /* BlockScopedVariable */);
35702                 var message = isEitherEnum
35703                     ? ts.Diagnostics.Enum_declarations_can_only_merge_with_namespace_or_other_enum_declarations
35704                     : isEitherBlockScoped_1
35705                         ? ts.Diagnostics.Cannot_redeclare_block_scoped_variable_0
35706                         : ts.Diagnostics.Duplicate_identifier_0;
35707                 var sourceSymbolFile = source.declarations && ts.getSourceFileOfNode(source.declarations[0]);
35708                 var targetSymbolFile = target.declarations && ts.getSourceFileOfNode(target.declarations[0]);
35709                 var symbolName_1 = symbolToString(source);
35710                 // Collect top-level duplicate identifier errors into one mapping, so we can then merge their diagnostics if there are a bunch
35711                 if (sourceSymbolFile && targetSymbolFile && amalgamatedDuplicates && !isEitherEnum && sourceSymbolFile !== targetSymbolFile) {
35712                     var firstFile_1 = ts.comparePaths(sourceSymbolFile.path, targetSymbolFile.path) === -1 /* LessThan */ ? sourceSymbolFile : targetSymbolFile;
35713                     var secondFile_1 = firstFile_1 === sourceSymbolFile ? targetSymbolFile : sourceSymbolFile;
35714                     var filesDuplicates = ts.getOrUpdate(amalgamatedDuplicates, firstFile_1.path + "|" + secondFile_1.path, function () {
35715                         return ({ firstFile: firstFile_1, secondFile: secondFile_1, conflictingSymbols: ts.createMap() });
35716                     });
35717                     var conflictingSymbolInfo = ts.getOrUpdate(filesDuplicates.conflictingSymbols, symbolName_1, function () {
35718                         return ({ isBlockScoped: isEitherBlockScoped_1, firstFileLocations: [], secondFileLocations: [] });
35719                     });
35720                     addDuplicateLocations(conflictingSymbolInfo.firstFileLocations, source);
35721                     addDuplicateLocations(conflictingSymbolInfo.secondFileLocations, target);
35722                 }
35723                 else {
35724                     addDuplicateDeclarationErrorsForSymbols(source, message, symbolName_1, target);
35725                     addDuplicateDeclarationErrorsForSymbols(target, message, symbolName_1, source);
35726                 }
35727             }
35728             return target;
35729             function addDuplicateLocations(locs, symbol) {
35730                 for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) {
35731                     var decl = _a[_i];
35732                     ts.pushIfUnique(locs, decl);
35733                 }
35734             }
35735         }
35736         function addDuplicateDeclarationErrorsForSymbols(target, message, symbolName, source) {
35737             ts.forEach(target.declarations, function (node) {
35738                 addDuplicateDeclarationError(node, message, symbolName, source.declarations);
35739             });
35740         }
35741         function addDuplicateDeclarationError(node, message, symbolName, relatedNodes) {
35742             var errorNode = (ts.getExpandoInitializer(node, /*isPrototypeAssignment*/ false) ? ts.getNameOfExpando(node) : ts.getNameOfDeclaration(node)) || node;
35743             var err = lookupOrIssueError(errorNode, message, symbolName);
35744             var _loop_6 = function (relatedNode) {
35745                 var adjustedNode = (ts.getExpandoInitializer(relatedNode, /*isPrototypeAssignment*/ false) ? ts.getNameOfExpando(relatedNode) : ts.getNameOfDeclaration(relatedNode)) || relatedNode;
35746                 if (adjustedNode === errorNode)
35747                     return "continue";
35748                 err.relatedInformation = err.relatedInformation || [];
35749                 var leadingMessage = ts.createDiagnosticForNode(adjustedNode, ts.Diagnostics._0_was_also_declared_here, symbolName);
35750                 var followOnMessage = ts.createDiagnosticForNode(adjustedNode, ts.Diagnostics.and_here);
35751                 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 */; }))
35752                     return "continue";
35753                 ts.addRelatedInfo(err, !ts.length(err.relatedInformation) ? leadingMessage : followOnMessage);
35754             };
35755             for (var _i = 0, _a = relatedNodes || ts.emptyArray; _i < _a.length; _i++) {
35756                 var relatedNode = _a[_i];
35757                 _loop_6(relatedNode);
35758             }
35759         }
35760         function combineSymbolTables(first, second) {
35761             if (!ts.hasEntries(first))
35762                 return second;
35763             if (!ts.hasEntries(second))
35764                 return first;
35765             var combined = ts.createSymbolTable();
35766             mergeSymbolTable(combined, first);
35767             mergeSymbolTable(combined, second);
35768             return combined;
35769         }
35770         function mergeSymbolTable(target, source, unidirectional) {
35771             if (unidirectional === void 0) { unidirectional = false; }
35772             source.forEach(function (sourceSymbol, id) {
35773                 var targetSymbol = target.get(id);
35774                 target.set(id, targetSymbol ? mergeSymbol(targetSymbol, sourceSymbol, unidirectional) : sourceSymbol);
35775             });
35776         }
35777         function mergeModuleAugmentation(moduleName) {
35778             var _a, _b;
35779             var moduleAugmentation = moduleName.parent;
35780             if (moduleAugmentation.symbol.declarations[0] !== moduleAugmentation) {
35781                 // this is a combined symbol for multiple augmentations within the same file.
35782                 // its symbol already has accumulated information for all declarations
35783                 // so we need to add it just once - do the work only for first declaration
35784                 ts.Debug.assert(moduleAugmentation.symbol.declarations.length > 1);
35785                 return;
35786             }
35787             if (ts.isGlobalScopeAugmentation(moduleAugmentation)) {
35788                 mergeSymbolTable(globals, moduleAugmentation.symbol.exports);
35789             }
35790             else {
35791                 // find a module that about to be augmented
35792                 // do not validate names of augmentations that are defined in ambient context
35793                 var moduleNotFoundError = !(moduleName.parent.parent.flags & 8388608 /* Ambient */)
35794                     ? ts.Diagnostics.Invalid_module_name_in_augmentation_module_0_cannot_be_found
35795                     : undefined;
35796                 var mainModule_1 = resolveExternalModuleNameWorker(moduleName, moduleName, moduleNotFoundError, /*isForAugmentation*/ true);
35797                 if (!mainModule_1) {
35798                     return;
35799                 }
35800                 // obtain item referenced by 'export='
35801                 mainModule_1 = resolveExternalModuleSymbol(mainModule_1);
35802                 if (mainModule_1.flags & 1920 /* Namespace */) {
35803                     // If we're merging an augmentation to a pattern ambient module, we want to
35804                     // perform the merge unidirectionally from the augmentation ('a.foo') to
35805                     // the pattern ('*.foo'), so that 'getMergedSymbol()' on a.foo gives you
35806                     // all the exports both from the pattern and from the augmentation, but
35807                     // 'getMergedSymbol()' on *.foo only gives you exports from *.foo.
35808                     if (ts.some(patternAmbientModules, function (module) { return mainModule_1 === module.symbol; })) {
35809                         var merged = mergeSymbol(moduleAugmentation.symbol, mainModule_1, /*unidirectional*/ true);
35810                         if (!patternAmbientModuleAugmentations) {
35811                             patternAmbientModuleAugmentations = ts.createMap();
35812                         }
35813                         // moduleName will be a StringLiteral since this is not `declare global`.
35814                         patternAmbientModuleAugmentations.set(moduleName.text, merged);
35815                     }
35816                     else {
35817                         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)) {
35818                             // We may need to merge the module augmentation's exports into the target symbols of the resolved exports
35819                             var resolvedExports = getResolvedMembersOrExportsOfSymbol(mainModule_1, "resolvedExports" /* resolvedExports */);
35820                             for (var _i = 0, _c = ts.arrayFrom(moduleAugmentation.symbol.exports.entries()); _i < _c.length; _i++) {
35821                                 var _d = _c[_i], key = _d[0], value = _d[1];
35822                                 if (resolvedExports.has(key) && !mainModule_1.exports.has(key)) {
35823                                     mergeSymbol(resolvedExports.get(key), value);
35824                                 }
35825                             }
35826                         }
35827                         mergeSymbol(mainModule_1, moduleAugmentation.symbol);
35828                     }
35829                 }
35830                 else {
35831                     // moduleName will be a StringLiteral since this is not `declare global`.
35832                     error(moduleName, ts.Diagnostics.Cannot_augment_module_0_because_it_resolves_to_a_non_module_entity, moduleName.text);
35833                 }
35834             }
35835         }
35836         function addToSymbolTable(target, source, message) {
35837             source.forEach(function (sourceSymbol, id) {
35838                 var targetSymbol = target.get(id);
35839                 if (targetSymbol) {
35840                     // Error on redeclarations
35841                     ts.forEach(targetSymbol.declarations, addDeclarationDiagnostic(ts.unescapeLeadingUnderscores(id), message));
35842                 }
35843                 else {
35844                     target.set(id, sourceSymbol);
35845                 }
35846             });
35847             function addDeclarationDiagnostic(id, message) {
35848                 return function (declaration) { return diagnostics.add(ts.createDiagnosticForNode(declaration, message, id)); };
35849             }
35850         }
35851         function getSymbolLinks(symbol) {
35852             if (symbol.flags & 33554432 /* Transient */)
35853                 return symbol;
35854             var id = getSymbolId(symbol);
35855             return symbolLinks[id] || (symbolLinks[id] = new SymbolLinks());
35856         }
35857         function getNodeLinks(node) {
35858             var nodeId = getNodeId(node);
35859             return nodeLinks[nodeId] || (nodeLinks[nodeId] = new NodeLinks());
35860         }
35861         function isGlobalSourceFile(node) {
35862             return node.kind === 290 /* SourceFile */ && !ts.isExternalOrCommonJsModule(node);
35863         }
35864         function getSymbol(symbols, name, meaning) {
35865             if (meaning) {
35866                 var symbol = getMergedSymbol(symbols.get(name));
35867                 if (symbol) {
35868                     ts.Debug.assert((ts.getCheckFlags(symbol) & 1 /* Instantiated */) === 0, "Should never get an instantiated symbol here.");
35869                     if (symbol.flags & meaning) {
35870                         return symbol;
35871                     }
35872                     if (symbol.flags & 2097152 /* Alias */) {
35873                         var target = resolveAlias(symbol);
35874                         // Unknown symbol means an error occurred in alias resolution, treat it as positive answer to avoid cascading errors
35875                         if (target === unknownSymbol || target.flags & meaning) {
35876                             return symbol;
35877                         }
35878                     }
35879                 }
35880             }
35881             // return undefined if we can't find a symbol.
35882         }
35883         /**
35884          * Get symbols that represent parameter-property-declaration as parameter and as property declaration
35885          * @param parameter a parameterDeclaration node
35886          * @param parameterName a name of the parameter to get the symbols for.
35887          * @return a tuple of two symbols
35888          */
35889         function getSymbolsOfParameterPropertyDeclaration(parameter, parameterName) {
35890             var constructorDeclaration = parameter.parent;
35891             var classDeclaration = parameter.parent.parent;
35892             var parameterSymbol = getSymbol(constructorDeclaration.locals, parameterName, 111551 /* Value */);
35893             var propertySymbol = getSymbol(getMembersOfSymbol(classDeclaration.symbol), parameterName, 111551 /* Value */);
35894             if (parameterSymbol && propertySymbol) {
35895                 return [parameterSymbol, propertySymbol];
35896             }
35897             return ts.Debug.fail("There should exist two symbols, one as property declaration and one as parameter declaration");
35898         }
35899         function isBlockScopedNameDeclaredBeforeUse(declaration, usage) {
35900             var declarationFile = ts.getSourceFileOfNode(declaration);
35901             var useFile = ts.getSourceFileOfNode(usage);
35902             var declContainer = ts.getEnclosingBlockScopeContainer(declaration);
35903             if (declarationFile !== useFile) {
35904                 if ((moduleKind && (declarationFile.externalModuleIndicator || useFile.externalModuleIndicator)) ||
35905                     (!compilerOptions.outFile && !compilerOptions.out) ||
35906                     isInTypeQuery(usage) ||
35907                     declaration.flags & 8388608 /* Ambient */) {
35908                     // nodes are in different files and order cannot be determined
35909                     return true;
35910                 }
35911                 // declaration is after usage
35912                 // can be legal if usage is deferred (i.e. inside function or in initializer of instance property)
35913                 if (isUsedInFunctionOrInstanceProperty(usage, declaration)) {
35914                     return true;
35915                 }
35916                 var sourceFiles = host.getSourceFiles();
35917                 return sourceFiles.indexOf(declarationFile) <= sourceFiles.indexOf(useFile);
35918             }
35919             if (declaration.pos <= usage.pos) {
35920                 // declaration is before usage
35921                 if (declaration.kind === 191 /* BindingElement */) {
35922                     // still might be illegal if declaration and usage are both binding elements (eg var [a = b, b = b] = [1, 2])
35923                     var errorBindingElement = ts.getAncestor(usage, 191 /* BindingElement */);
35924                     if (errorBindingElement) {
35925                         return ts.findAncestor(errorBindingElement, ts.isBindingElement) !== ts.findAncestor(declaration, ts.isBindingElement) ||
35926                             declaration.pos < errorBindingElement.pos;
35927                     }
35928                     // or it might be illegal if usage happens before parent variable is declared (eg var [a] = a)
35929                     return isBlockScopedNameDeclaredBeforeUse(ts.getAncestor(declaration, 242 /* VariableDeclaration */), usage);
35930                 }
35931                 else if (declaration.kind === 242 /* VariableDeclaration */) {
35932                     // still might be illegal if usage is in the initializer of the variable declaration (eg var a = a)
35933                     return !isImmediatelyUsedInInitializerOfBlockScopedVariable(declaration, usage);
35934                 }
35935                 else if (ts.isClassDeclaration(declaration)) {
35936                     // still might be illegal if the usage is within a computed property name in the class (eg class A { static p = "a"; [A.p]() {} })
35937                     return !ts.findAncestor(usage, function (n) { return ts.isComputedPropertyName(n) && n.parent.parent === declaration; });
35938                 }
35939                 else if (ts.isPropertyDeclaration(declaration)) {
35940                     // still might be illegal if a self-referencing property initializer (eg private x = this.x)
35941                     return !isPropertyImmediatelyReferencedWithinDeclaration(declaration, usage, /*stopAtAnyPropertyDeclaration*/ false);
35942                 }
35943                 else if (ts.isParameterPropertyDeclaration(declaration, declaration.parent)) {
35944                     // foo = this.bar is illegal in esnext+useDefineForClassFields when bar is a parameter property
35945                     return !(compilerOptions.target === 99 /* ESNext */ && !!compilerOptions.useDefineForClassFields
35946                         && ts.getContainingClass(declaration) === ts.getContainingClass(usage)
35947                         && isUsedInFunctionOrInstanceProperty(usage, declaration));
35948                 }
35949                 return true;
35950             }
35951             // declaration is after usage, but it can still be legal if usage is deferred:
35952             // 1. inside an export specifier
35953             // 2. inside a function
35954             // 3. inside an instance property initializer, a reference to a non-instance property
35955             //    (except when target: "esnext" and useDefineForClassFields: true and the reference is to a parameter property)
35956             // 4. inside a static property initializer, a reference to a static method in the same class
35957             // 5. inside a TS export= declaration (since we will move the export statement during emit to avoid TDZ)
35958             // or if usage is in a type context:
35959             // 1. inside a type query (typeof in type position)
35960             // 2. inside a jsdoc comment
35961             if (usage.parent.kind === 263 /* ExportSpecifier */ || (usage.parent.kind === 259 /* ExportAssignment */ && usage.parent.isExportEquals)) {
35962                 // export specifiers do not use the variable, they only make it available for use
35963                 return true;
35964             }
35965             // When resolving symbols for exports, the `usage` location passed in can be the export site directly
35966             if (usage.kind === 259 /* ExportAssignment */ && usage.isExportEquals) {
35967                 return true;
35968             }
35969             if (!!(usage.flags & 4194304 /* JSDoc */) || isInTypeQuery(usage) || usageInTypeDeclaration()) {
35970                 return true;
35971             }
35972             if (isUsedInFunctionOrInstanceProperty(usage, declaration)) {
35973                 if (compilerOptions.target === 99 /* ESNext */ && !!compilerOptions.useDefineForClassFields
35974                     && ts.getContainingClass(declaration)
35975                     && (ts.isPropertyDeclaration(declaration) || ts.isParameterPropertyDeclaration(declaration, declaration.parent))) {
35976                     return !isPropertyImmediatelyReferencedWithinDeclaration(declaration, usage, /*stopAtAnyPropertyDeclaration*/ true);
35977                 }
35978                 else {
35979                     return true;
35980                 }
35981             }
35982             return false;
35983             function usageInTypeDeclaration() {
35984                 return !!ts.findAncestor(usage, function (node) { return ts.isInterfaceDeclaration(node) || ts.isTypeAliasDeclaration(node); });
35985             }
35986             function isImmediatelyUsedInInitializerOfBlockScopedVariable(declaration, usage) {
35987                 switch (declaration.parent.parent.kind) {
35988                     case 225 /* VariableStatement */:
35989                     case 230 /* ForStatement */:
35990                     case 232 /* ForOfStatement */:
35991                         // variable statement/for/for-of statement case,
35992                         // use site should not be inside variable declaration (initializer of declaration or binding element)
35993                         if (isSameScopeDescendentOf(usage, declaration, declContainer)) {
35994                             return true;
35995                         }
35996                         break;
35997                 }
35998                 // ForIn/ForOf case - use site should not be used in expression part
35999                 var grandparent = declaration.parent.parent;
36000                 return ts.isForInOrOfStatement(grandparent) && isSameScopeDescendentOf(usage, grandparent.expression, declContainer);
36001             }
36002             function isUsedInFunctionOrInstanceProperty(usage, declaration) {
36003                 return !!ts.findAncestor(usage, function (current) {
36004                     if (current === declContainer) {
36005                         return "quit";
36006                     }
36007                     if (ts.isFunctionLike(current)) {
36008                         return true;
36009                     }
36010                     var initializerOfProperty = current.parent &&
36011                         current.parent.kind === 159 /* PropertyDeclaration */ &&
36012                         current.parent.initializer === current;
36013                     if (initializerOfProperty) {
36014                         if (ts.hasModifier(current.parent, 32 /* Static */)) {
36015                             if (declaration.kind === 161 /* MethodDeclaration */) {
36016                                 return true;
36017                             }
36018                         }
36019                         else {
36020                             var isDeclarationInstanceProperty = declaration.kind === 159 /* PropertyDeclaration */ && !ts.hasModifier(declaration, 32 /* Static */);
36021                             if (!isDeclarationInstanceProperty || ts.getContainingClass(usage) !== ts.getContainingClass(declaration)) {
36022                                 return true;
36023                             }
36024                         }
36025                     }
36026                     return false;
36027                 });
36028             }
36029             /** stopAtAnyPropertyDeclaration is used for detecting ES-standard class field use-before-def errors */
36030             function isPropertyImmediatelyReferencedWithinDeclaration(declaration, usage, stopAtAnyPropertyDeclaration) {
36031                 // always legal if usage is after declaration
36032                 if (usage.end > declaration.end) {
36033                     return false;
36034                 }
36035                 // still might be legal if usage is deferred (e.g. x: any = () => this.x)
36036                 // otherwise illegal if immediately referenced within the declaration (e.g. x: any = this.x)
36037                 var ancestorChangingReferenceScope = ts.findAncestor(usage, function (node) {
36038                     if (node === declaration) {
36039                         return "quit";
36040                     }
36041                     switch (node.kind) {
36042                         case 202 /* ArrowFunction */:
36043                             return true;
36044                         case 159 /* PropertyDeclaration */:
36045                             // even when stopping at any property declaration, they need to come from the same class
36046                             return stopAtAnyPropertyDeclaration &&
36047                                 (ts.isPropertyDeclaration(declaration) && node.parent === declaration.parent
36048                                     || ts.isParameterPropertyDeclaration(declaration, declaration.parent) && node.parent === declaration.parent.parent)
36049                                 ? "quit" : true;
36050                         case 223 /* Block */:
36051                             switch (node.parent.kind) {
36052                                 case 163 /* GetAccessor */:
36053                                 case 161 /* MethodDeclaration */:
36054                                 case 164 /* SetAccessor */:
36055                                     return true;
36056                                 default:
36057                                     return false;
36058                             }
36059                         default:
36060                             return false;
36061                     }
36062                 });
36063                 return ancestorChangingReferenceScope === undefined;
36064             }
36065         }
36066         function useOuterVariableScopeInParameter(result, location, lastLocation) {
36067             var target = ts.getEmitScriptTarget(compilerOptions);
36068             var functionLocation = location;
36069             if (ts.isParameter(lastLocation) && functionLocation.body && result.valueDeclaration.pos >= functionLocation.body.pos && result.valueDeclaration.end <= functionLocation.body.end) {
36070                 // check for several cases where we introduce temporaries that require moving the name/initializer of the parameter to the body
36071                 // - static field in a class expression
36072                 // - optional chaining pre-es2020
36073                 // - nullish coalesce pre-es2020
36074                 // - spread assignment in binding pattern pre-es2017
36075                 if (target >= 2 /* ES2015 */) {
36076                     var links = getNodeLinks(functionLocation);
36077                     if (links.declarationRequiresScopeChange === undefined) {
36078                         links.declarationRequiresScopeChange = ts.forEach(functionLocation.parameters, requiresScopeChange) || false;
36079                     }
36080                     return !links.declarationRequiresScopeChange;
36081                 }
36082             }
36083             return false;
36084             function requiresScopeChange(node) {
36085                 return requiresScopeChangeWorker(node.name)
36086                     || !!node.initializer && requiresScopeChangeWorker(node.initializer);
36087             }
36088             function requiresScopeChangeWorker(node) {
36089                 switch (node.kind) {
36090                     case 202 /* ArrowFunction */:
36091                     case 201 /* FunctionExpression */:
36092                     case 244 /* FunctionDeclaration */:
36093                     case 162 /* Constructor */:
36094                         // do not descend into these
36095                         return false;
36096                     case 161 /* MethodDeclaration */:
36097                     case 163 /* GetAccessor */:
36098                     case 164 /* SetAccessor */:
36099                     case 281 /* PropertyAssignment */:
36100                         return requiresScopeChangeWorker(node.name);
36101                     case 159 /* PropertyDeclaration */:
36102                         // static properties in classes introduce temporary variables
36103                         if (ts.hasStaticModifier(node)) {
36104                             return target < 99 /* ESNext */ || !compilerOptions.useDefineForClassFields;
36105                         }
36106                         return requiresScopeChangeWorker(node.name);
36107                     default:
36108                         // null coalesce and optional chain pre-es2020 produce temporary variables
36109                         if (ts.isNullishCoalesce(node) || ts.isOptionalChain(node)) {
36110                             return target < 7 /* ES2020 */;
36111                         }
36112                         if (ts.isBindingElement(node) && node.dotDotDotToken && ts.isObjectBindingPattern(node.parent)) {
36113                             return target < 4 /* ES2017 */;
36114                         }
36115                         if (ts.isTypeNode(node))
36116                             return false;
36117                         return ts.forEachChild(node, requiresScopeChangeWorker) || false;
36118                 }
36119             }
36120         }
36121         /**
36122          * Resolve a given name for a given meaning at a given location. An error is reported if the name was not found and
36123          * the nameNotFoundMessage argument is not undefined. Returns the resolved symbol, or undefined if no symbol with
36124          * the given name can be found.
36125          *
36126          * @param isUse If true, this will count towards --noUnusedLocals / --noUnusedParameters.
36127          */
36128         function resolveName(location, name, meaning, nameNotFoundMessage, nameArg, isUse, excludeGlobals, suggestedNameNotFoundMessage) {
36129             if (excludeGlobals === void 0) { excludeGlobals = false; }
36130             return resolveNameHelper(location, name, meaning, nameNotFoundMessage, nameArg, isUse, excludeGlobals, getSymbol, suggestedNameNotFoundMessage);
36131         }
36132         function resolveNameHelper(location, name, meaning, nameNotFoundMessage, nameArg, isUse, excludeGlobals, lookup, suggestedNameNotFoundMessage) {
36133             var originalLocation = location; // needed for did-you-mean error reporting, which gathers candidates starting from the original location
36134             var result;
36135             var lastLocation;
36136             var lastSelfReferenceLocation;
36137             var propertyWithInvalidInitializer;
36138             var associatedDeclarationForContainingInitializerOrBindingName;
36139             var withinDeferredContext = false;
36140             var errorLocation = location;
36141             var grandparent;
36142             var isInExternalModule = false;
36143             loop: while (location) {
36144                 // Locals of a source file are not in scope (because they get merged into the global symbol table)
36145                 if (location.locals && !isGlobalSourceFile(location)) {
36146                     if (result = lookup(location.locals, name, meaning)) {
36147                         var useResult = true;
36148                         if (ts.isFunctionLike(location) && lastLocation && lastLocation !== location.body) {
36149                             // symbol lookup restrictions for function-like declarations
36150                             // - Type parameters of a function are in scope in the entire function declaration, including the parameter
36151                             //   list and return type. However, local types are only in scope in the function body.
36152                             // - parameters are only in the scope of function body
36153                             // This restriction does not apply to JSDoc comment types because they are parented
36154                             // at a higher level than type parameters would normally be
36155                             if (meaning & result.flags & 788968 /* Type */ && lastLocation.kind !== 303 /* JSDocComment */) {
36156                                 useResult = result.flags & 262144 /* TypeParameter */
36157                                     // type parameters are visible in parameter list, return type and type parameter list
36158                                     ? lastLocation === location.type ||
36159                                         lastLocation.kind === 156 /* Parameter */ ||
36160                                         lastLocation.kind === 155 /* TypeParameter */
36161                                     // local types not visible outside the function body
36162                                     : false;
36163                             }
36164                             if (meaning & result.flags & 3 /* Variable */) {
36165                                 // expression inside parameter will lookup as normal variable scope when targeting es2015+
36166                                 if (useOuterVariableScopeInParameter(result, location, lastLocation)) {
36167                                     useResult = false;
36168                                 }
36169                                 else if (result.flags & 1 /* FunctionScopedVariable */) {
36170                                     // parameters are visible only inside function body, parameter list and return type
36171                                     // technically for parameter list case here we might mix parameters and variables declared in function,
36172                                     // however it is detected separately when checking initializers of parameters
36173                                     // to make sure that they reference no variables declared after them.
36174                                     useResult =
36175                                         lastLocation.kind === 156 /* Parameter */ ||
36176                                             (lastLocation === location.type &&
36177                                                 !!ts.findAncestor(result.valueDeclaration, ts.isParameter));
36178                                 }
36179                             }
36180                         }
36181                         else if (location.kind === 180 /* ConditionalType */) {
36182                             // A type parameter declared using 'infer T' in a conditional type is visible only in
36183                             // the true branch of the conditional type.
36184                             useResult = lastLocation === location.trueType;
36185                         }
36186                         if (useResult) {
36187                             break loop;
36188                         }
36189                         else {
36190                             result = undefined;
36191                         }
36192                     }
36193                 }
36194                 withinDeferredContext = withinDeferredContext || getIsDeferredContext(location, lastLocation);
36195                 switch (location.kind) {
36196                     case 290 /* SourceFile */:
36197                         if (!ts.isExternalOrCommonJsModule(location))
36198                             break;
36199                         isInExternalModule = true;
36200                     // falls through
36201                     case 249 /* ModuleDeclaration */:
36202                         var moduleExports = getSymbolOfNode(location).exports || emptySymbols;
36203                         if (location.kind === 290 /* SourceFile */ || (ts.isModuleDeclaration(location) && location.flags & 8388608 /* Ambient */ && !ts.isGlobalScopeAugmentation(location))) {
36204                             // It's an external module. First see if the module has an export default and if the local
36205                             // name of that export default matches.
36206                             if (result = moduleExports.get("default" /* Default */)) {
36207                                 var localSymbol = ts.getLocalSymbolForExportDefault(result);
36208                                 if (localSymbol && (result.flags & meaning) && localSymbol.escapedName === name) {
36209                                     break loop;
36210                                 }
36211                                 result = undefined;
36212                             }
36213                             // Because of module/namespace merging, a module's exports are in scope,
36214                             // yet we never want to treat an export specifier as putting a member in scope.
36215                             // Therefore, if the name we find is purely an export specifier, it is not actually considered in scope.
36216                             // Two things to note about this:
36217                             //     1. We have to check this without calling getSymbol. The problem with calling getSymbol
36218                             //        on an export specifier is that it might find the export specifier itself, and try to
36219                             //        resolve it as an alias. This will cause the checker to consider the export specifier
36220                             //        a circular alias reference when it might not be.
36221                             //     2. We check === SymbolFlags.Alias in order to check that the symbol is *purely*
36222                             //        an alias. If we used &, we'd be throwing out symbols that have non alias aspects,
36223                             //        which is not the desired behavior.
36224                             var moduleExport = moduleExports.get(name);
36225                             if (moduleExport &&
36226                                 moduleExport.flags === 2097152 /* Alias */ &&
36227                                 (ts.getDeclarationOfKind(moduleExport, 263 /* ExportSpecifier */) || ts.getDeclarationOfKind(moduleExport, 262 /* NamespaceExport */))) {
36228                                 break;
36229                             }
36230                         }
36231                         // ES6 exports are also visible locally (except for 'default'), but commonjs exports are not (except typedefs)
36232                         if (name !== "default" /* Default */ && (result = lookup(moduleExports, name, meaning & 2623475 /* ModuleMember */))) {
36233                             if (ts.isSourceFile(location) && location.commonJsModuleIndicator && !result.declarations.some(ts.isJSDocTypeAlias)) {
36234                                 result = undefined;
36235                             }
36236                             else {
36237                                 break loop;
36238                             }
36239                         }
36240                         break;
36241                     case 248 /* EnumDeclaration */:
36242                         if (result = lookup(getSymbolOfNode(location).exports, name, meaning & 8 /* EnumMember */)) {
36243                             break loop;
36244                         }
36245                         break;
36246                     case 159 /* PropertyDeclaration */:
36247                         // TypeScript 1.0 spec (April 2014): 8.4.1
36248                         // Initializer expressions for instance member variables are evaluated in the scope
36249                         // of the class constructor body but are not permitted to reference parameters or
36250                         // local variables of the constructor. This effectively means that entities from outer scopes
36251                         // by the same name as a constructor parameter or local variable are inaccessible
36252                         // in initializer expressions for instance member variables.
36253                         if (!ts.hasModifier(location, 32 /* Static */)) {
36254                             var ctor = findConstructorDeclaration(location.parent);
36255                             if (ctor && ctor.locals) {
36256                                 if (lookup(ctor.locals, name, meaning & 111551 /* Value */)) {
36257                                     // Remember the property node, it will be used later to report appropriate error
36258                                     propertyWithInvalidInitializer = location;
36259                                 }
36260                             }
36261                         }
36262                         break;
36263                     case 245 /* ClassDeclaration */:
36264                     case 214 /* ClassExpression */:
36265                     case 246 /* InterfaceDeclaration */:
36266                         // The below is used to lookup type parameters within a class or interface, as they are added to the class/interface locals
36267                         // These can never be latebound, so the symbol's raw members are sufficient. `getMembersOfNode` cannot be used, as it would
36268                         // trigger resolving late-bound names, which we may already be in the process of doing while we're here!
36269                         if (result = lookup(getSymbolOfNode(location).members || emptySymbols, name, meaning & 788968 /* Type */)) {
36270                             if (!isTypeParameterSymbolDeclaredInContainer(result, location)) {
36271                                 // ignore type parameters not declared in this container
36272                                 result = undefined;
36273                                 break;
36274                             }
36275                             if (lastLocation && ts.hasModifier(lastLocation, 32 /* Static */)) {
36276                                 // TypeScript 1.0 spec (April 2014): 3.4.1
36277                                 // The scope of a type parameter extends over the entire declaration with which the type
36278                                 // parameter list is associated, with the exception of static member declarations in classes.
36279                                 error(errorLocation, ts.Diagnostics.Static_members_cannot_reference_class_type_parameters);
36280                                 return undefined;
36281                             }
36282                             break loop;
36283                         }
36284                         if (location.kind === 214 /* ClassExpression */ && meaning & 32 /* Class */) {
36285                             var className = location.name;
36286                             if (className && name === className.escapedText) {
36287                                 result = location.symbol;
36288                                 break loop;
36289                             }
36290                         }
36291                         break;
36292                     case 216 /* ExpressionWithTypeArguments */:
36293                         // The type parameters of a class are not in scope in the base class expression.
36294                         if (lastLocation === location.expression && location.parent.token === 90 /* ExtendsKeyword */) {
36295                             var container = location.parent.parent;
36296                             if (ts.isClassLike(container) && (result = lookup(getSymbolOfNode(container).members, name, meaning & 788968 /* Type */))) {
36297                                 if (nameNotFoundMessage) {
36298                                     error(errorLocation, ts.Diagnostics.Base_class_expressions_cannot_reference_class_type_parameters);
36299                                 }
36300                                 return undefined;
36301                             }
36302                         }
36303                         break;
36304                     // It is not legal to reference a class's own type parameters from a computed property name that
36305                     // belongs to the class. For example:
36306                     //
36307                     //   function foo<T>() { return '' }
36308                     //   class C<T> { // <-- Class's own type parameter T
36309                     //       [foo<T>()]() { } // <-- Reference to T from class's own computed property
36310                     //   }
36311                     //
36312                     case 154 /* ComputedPropertyName */:
36313                         grandparent = location.parent.parent;
36314                         if (ts.isClassLike(grandparent) || grandparent.kind === 246 /* InterfaceDeclaration */) {
36315                             // A reference to this grandparent's type parameters would be an error
36316                             if (result = lookup(getSymbolOfNode(grandparent).members, name, meaning & 788968 /* Type */)) {
36317                                 error(errorLocation, ts.Diagnostics.A_computed_property_name_cannot_reference_a_type_parameter_from_its_containing_type);
36318                                 return undefined;
36319                             }
36320                         }
36321                         break;
36322                     case 202 /* ArrowFunction */:
36323                         // when targeting ES6 or higher there is no 'arguments' in an arrow function
36324                         // for lower compile targets the resolved symbol is used to emit an error
36325                         if (compilerOptions.target >= 2 /* ES2015 */) {
36326                             break;
36327                         }
36328                     // falls through
36329                     case 161 /* MethodDeclaration */:
36330                     case 162 /* Constructor */:
36331                     case 163 /* GetAccessor */:
36332                     case 164 /* SetAccessor */:
36333                     case 244 /* FunctionDeclaration */:
36334                         if (meaning & 3 /* Variable */ && name === "arguments") {
36335                             result = argumentsSymbol;
36336                             break loop;
36337                         }
36338                         break;
36339                     case 201 /* FunctionExpression */:
36340                         if (meaning & 3 /* Variable */ && name === "arguments") {
36341                             result = argumentsSymbol;
36342                             break loop;
36343                         }
36344                         if (meaning & 16 /* Function */) {
36345                             var functionName = location.name;
36346                             if (functionName && name === functionName.escapedText) {
36347                                 result = location.symbol;
36348                                 break loop;
36349                             }
36350                         }
36351                         break;
36352                     case 157 /* Decorator */:
36353                         // Decorators are resolved at the class declaration. Resolving at the parameter
36354                         // or member would result in looking up locals in the method.
36355                         //
36356                         //   function y() {}
36357                         //   class C {
36358                         //       method(@y x, y) {} // <-- decorator y should be resolved at the class declaration, not the parameter.
36359                         //   }
36360                         //
36361                         if (location.parent && location.parent.kind === 156 /* Parameter */) {
36362                             location = location.parent;
36363                         }
36364                         //
36365                         //   function y() {}
36366                         //   class C {
36367                         //       @y method(x, y) {} // <-- decorator y should be resolved at the class declaration, not the method.
36368                         //   }
36369                         //
36370                         // class Decorators are resolved outside of the class to avoid referencing type parameters of that class.
36371                         //
36372                         //   type T = number;
36373                         //   declare function y(x: T): any;
36374                         //   @param(1 as T) // <-- T should resolve to the type alias outside of class C
36375                         //   class C<T> {}
36376                         if (location.parent && (ts.isClassElement(location.parent) || location.parent.kind === 245 /* ClassDeclaration */)) {
36377                             location = location.parent;
36378                         }
36379                         break;
36380                     case 322 /* JSDocTypedefTag */:
36381                     case 315 /* JSDocCallbackTag */:
36382                     case 316 /* JSDocEnumTag */:
36383                         // js type aliases do not resolve names from their host, so skip past it
36384                         location = ts.getJSDocHost(location);
36385                         break;
36386                     case 156 /* Parameter */:
36387                         if (lastLocation && (lastLocation === location.initializer ||
36388                             lastLocation === location.name && ts.isBindingPattern(lastLocation))) {
36389                             if (!associatedDeclarationForContainingInitializerOrBindingName) {
36390                                 associatedDeclarationForContainingInitializerOrBindingName = location;
36391                             }
36392                         }
36393                         break;
36394                     case 191 /* BindingElement */:
36395                         if (lastLocation && (lastLocation === location.initializer ||
36396                             lastLocation === location.name && ts.isBindingPattern(lastLocation))) {
36397                             var root = ts.getRootDeclaration(location);
36398                             if (root.kind === 156 /* Parameter */) {
36399                                 if (!associatedDeclarationForContainingInitializerOrBindingName) {
36400                                     associatedDeclarationForContainingInitializerOrBindingName = location;
36401                                 }
36402                             }
36403                         }
36404                         break;
36405                 }
36406                 if (isSelfReferenceLocation(location)) {
36407                     lastSelfReferenceLocation = location;
36408                 }
36409                 lastLocation = location;
36410                 location = location.parent;
36411             }
36412             // We just climbed up parents looking for the name, meaning that we started in a descendant node of `lastLocation`.
36413             // If `result === lastSelfReferenceLocation.symbol`, that means that we are somewhere inside `lastSelfReferenceLocation` looking up a name, and resolving to `lastLocation` itself.
36414             // That means that this is a self-reference of `lastLocation`, and shouldn't count this when considering whether `lastLocation` is used.
36415             if (isUse && result && (!lastSelfReferenceLocation || result !== lastSelfReferenceLocation.symbol)) {
36416                 result.isReferenced |= meaning;
36417             }
36418             if (!result) {
36419                 if (lastLocation) {
36420                     ts.Debug.assert(lastLocation.kind === 290 /* SourceFile */);
36421                     if (lastLocation.commonJsModuleIndicator && name === "exports" && meaning & lastLocation.symbol.flags) {
36422                         return lastLocation.symbol;
36423                     }
36424                 }
36425                 if (!excludeGlobals) {
36426                     result = lookup(globals, name, meaning);
36427                 }
36428             }
36429             if (!result) {
36430                 if (originalLocation && ts.isInJSFile(originalLocation) && originalLocation.parent) {
36431                     if (ts.isRequireCall(originalLocation.parent, /*checkArgumentIsStringLiteralLike*/ false)) {
36432                         return requireSymbol;
36433                     }
36434                 }
36435             }
36436             if (!result) {
36437                 if (nameNotFoundMessage) {
36438                     if (!errorLocation ||
36439                         !checkAndReportErrorForMissingPrefix(errorLocation, name, nameArg) && // TODO: GH#18217
36440                             !checkAndReportErrorForExtendingInterface(errorLocation) &&
36441                             !checkAndReportErrorForUsingTypeAsNamespace(errorLocation, name, meaning) &&
36442                             !checkAndReportErrorForExportingPrimitiveType(errorLocation, name) &&
36443                             !checkAndReportErrorForUsingTypeAsValue(errorLocation, name, meaning) &&
36444                             !checkAndReportErrorForUsingNamespaceModuleAsValue(errorLocation, name, meaning) &&
36445                             !checkAndReportErrorForUsingValueAsType(errorLocation, name, meaning)) {
36446                         var suggestion = void 0;
36447                         if (suggestedNameNotFoundMessage && suggestionCount < maximumSuggestionCount) {
36448                             suggestion = getSuggestedSymbolForNonexistentSymbol(originalLocation, name, meaning);
36449                             if (suggestion) {
36450                                 var suggestionName = symbolToString(suggestion);
36451                                 var diagnostic = error(errorLocation, suggestedNameNotFoundMessage, diagnosticName(nameArg), suggestionName);
36452                                 if (suggestion.valueDeclaration) {
36453                                     ts.addRelatedInfo(diagnostic, ts.createDiagnosticForNode(suggestion.valueDeclaration, ts.Diagnostics._0_is_declared_here, suggestionName));
36454                                 }
36455                             }
36456                         }
36457                         if (!suggestion) {
36458                             error(errorLocation, nameNotFoundMessage, diagnosticName(nameArg));
36459                         }
36460                         suggestionCount++;
36461                     }
36462                 }
36463                 return undefined;
36464             }
36465             // Perform extra checks only if error reporting was requested
36466             if (nameNotFoundMessage) {
36467                 if (propertyWithInvalidInitializer && !(compilerOptions.target === 99 /* ESNext */ && compilerOptions.useDefineForClassFields)) {
36468                     // We have a match, but the reference occurred within a property initializer and the identifier also binds
36469                     // to a local variable in the constructor where the code will be emitted. Note that this is actually allowed
36470                     // with ESNext+useDefineForClassFields because the scope semantics are different.
36471                     var propertyName = propertyWithInvalidInitializer.name;
36472                     error(errorLocation, ts.Diagnostics.Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor, ts.declarationNameToString(propertyName), diagnosticName(nameArg));
36473                     return undefined;
36474                 }
36475                 // Only check for block-scoped variable if we have an error location and are looking for the
36476                 // name with variable meaning
36477                 //      For example,
36478                 //          declare module foo {
36479                 //              interface bar {}
36480                 //          }
36481                 //      const foo/*1*/: foo/*2*/.bar;
36482                 // The foo at /*1*/ and /*2*/ will share same symbol with two meanings:
36483                 // block-scoped variable and namespace module. However, only when we
36484                 // try to resolve name in /*1*/ which is used in variable position,
36485                 // we want to check for block-scoped
36486                 if (errorLocation &&
36487                     (meaning & 2 /* BlockScopedVariable */ ||
36488                         ((meaning & 32 /* Class */ || meaning & 384 /* Enum */) && (meaning & 111551 /* Value */) === 111551 /* Value */))) {
36489                     var exportOrLocalSymbol = getExportSymbolOfValueSymbolIfExported(result);
36490                     if (exportOrLocalSymbol.flags & 2 /* BlockScopedVariable */ || exportOrLocalSymbol.flags & 32 /* Class */ || exportOrLocalSymbol.flags & 384 /* Enum */) {
36491                         checkResolvedBlockScopedVariable(exportOrLocalSymbol, errorLocation);
36492                     }
36493                 }
36494                 // If we're in an external module, we can't reference value symbols created from UMD export declarations
36495                 if (result && isInExternalModule && (meaning & 111551 /* Value */) === 111551 /* Value */ && !(originalLocation.flags & 4194304 /* JSDoc */)) {
36496                     var merged = getMergedSymbol(result);
36497                     if (ts.length(merged.declarations) && ts.every(merged.declarations, function (d) { return ts.isNamespaceExportDeclaration(d) || ts.isSourceFile(d) && !!d.symbol.globalExports; })) {
36498                         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));
36499                     }
36500                 }
36501                 // 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
36502                 if (result && associatedDeclarationForContainingInitializerOrBindingName && !withinDeferredContext && (meaning & 111551 /* Value */) === 111551 /* Value */) {
36503                     var candidate = getMergedSymbol(getLateBoundSymbol(result));
36504                     var root = ts.getRootDeclaration(associatedDeclarationForContainingInitializerOrBindingName);
36505                     // A parameter initializer or binding pattern initializer within a parameter cannot refer to itself
36506                     if (candidate === getSymbolOfNode(associatedDeclarationForContainingInitializerOrBindingName)) {
36507                         error(errorLocation, ts.Diagnostics.Parameter_0_cannot_reference_itself, ts.declarationNameToString(associatedDeclarationForContainingInitializerOrBindingName.name));
36508                     }
36509                     // And it cannot refer to any declarations which come after it
36510                     else if (candidate.valueDeclaration && candidate.valueDeclaration.pos > associatedDeclarationForContainingInitializerOrBindingName.pos && root.parent.locals && lookup(root.parent.locals, candidate.escapedName, meaning) === candidate) {
36511                         error(errorLocation, ts.Diagnostics.Parameter_0_cannot_reference_identifier_1_declared_after_it, ts.declarationNameToString(associatedDeclarationForContainingInitializerOrBindingName.name), ts.declarationNameToString(errorLocation));
36512                     }
36513                 }
36514                 if (result && errorLocation && meaning & 111551 /* Value */ && result.flags & 2097152 /* Alias */) {
36515                     checkSymbolUsageInExpressionContext(result, name, errorLocation);
36516                 }
36517             }
36518             return result;
36519         }
36520         function checkSymbolUsageInExpressionContext(symbol, name, useSite) {
36521             if (!ts.isValidTypeOnlyAliasUseSite(useSite)) {
36522                 var typeOnlyDeclaration = getTypeOnlyAliasDeclaration(symbol);
36523                 if (typeOnlyDeclaration) {
36524                     var isExport = ts.typeOnlyDeclarationIsExport(typeOnlyDeclaration);
36525                     var message = isExport
36526                         ? ts.Diagnostics._0_cannot_be_used_as_a_value_because_it_was_exported_using_export_type
36527                         : ts.Diagnostics._0_cannot_be_used_as_a_value_because_it_was_imported_using_import_type;
36528                     var relatedMessage = isExport
36529                         ? ts.Diagnostics._0_was_exported_here
36530                         : ts.Diagnostics._0_was_imported_here;
36531                     var unescapedName = ts.unescapeLeadingUnderscores(name);
36532                     ts.addRelatedInfo(error(useSite, message, unescapedName), ts.createDiagnosticForNode(typeOnlyDeclaration, relatedMessage, unescapedName));
36533                 }
36534             }
36535         }
36536         function getIsDeferredContext(location, lastLocation) {
36537             if (location.kind !== 202 /* ArrowFunction */ && location.kind !== 201 /* FunctionExpression */) {
36538                 // initializers in instance property declaration of class like entities are executed in constructor and thus deferred
36539                 return ts.isTypeQueryNode(location) || ((ts.isFunctionLikeDeclaration(location) ||
36540                     (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
36541             }
36542             if (lastLocation && lastLocation === location.name) {
36543                 return false;
36544             }
36545             // generator functions and async functions are not inlined in control flow when immediately invoked
36546             if (location.asteriskToken || ts.hasModifier(location, 256 /* Async */)) {
36547                 return true;
36548             }
36549             return !ts.getImmediatelyInvokedFunctionExpression(location);
36550         }
36551         function isSelfReferenceLocation(node) {
36552             switch (node.kind) {
36553                 case 244 /* FunctionDeclaration */:
36554                 case 245 /* ClassDeclaration */:
36555                 case 246 /* InterfaceDeclaration */:
36556                 case 248 /* EnumDeclaration */:
36557                 case 247 /* TypeAliasDeclaration */:
36558                 case 249 /* ModuleDeclaration */: // For `namespace N { N; }`
36559                     return true;
36560                 default:
36561                     return false;
36562             }
36563         }
36564         function diagnosticName(nameArg) {
36565             return ts.isString(nameArg) ? ts.unescapeLeadingUnderscores(nameArg) : ts.declarationNameToString(nameArg);
36566         }
36567         function isTypeParameterSymbolDeclaredInContainer(symbol, container) {
36568             for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) {
36569                 var decl = _a[_i];
36570                 if (decl.kind === 155 /* TypeParameter */) {
36571                     var parent = ts.isJSDocTemplateTag(decl.parent) ? ts.getJSDocHost(decl.parent) : decl.parent;
36572                     if (parent === container) {
36573                         return !(ts.isJSDocTemplateTag(decl.parent) && ts.find(decl.parent.parent.tags, ts.isJSDocTypeAlias)); // TODO: GH#18217
36574                     }
36575                 }
36576             }
36577             return false;
36578         }
36579         function checkAndReportErrorForMissingPrefix(errorLocation, name, nameArg) {
36580             if (!ts.isIdentifier(errorLocation) || errorLocation.escapedText !== name || isTypeReferenceIdentifier(errorLocation) || isInTypeQuery(errorLocation)) {
36581                 return false;
36582             }
36583             var container = ts.getThisContainer(errorLocation, /*includeArrowFunctions*/ false);
36584             var location = container;
36585             while (location) {
36586                 if (ts.isClassLike(location.parent)) {
36587                     var classSymbol = getSymbolOfNode(location.parent);
36588                     if (!classSymbol) {
36589                         break;
36590                     }
36591                     // Check to see if a static member exists.
36592                     var constructorType = getTypeOfSymbol(classSymbol);
36593                     if (getPropertyOfType(constructorType, name)) {
36594                         error(errorLocation, ts.Diagnostics.Cannot_find_name_0_Did_you_mean_the_static_member_1_0, diagnosticName(nameArg), symbolToString(classSymbol));
36595                         return true;
36596                     }
36597                     // No static member is present.
36598                     // Check if we're in an instance method and look for a relevant instance member.
36599                     if (location === container && !ts.hasModifier(location, 32 /* Static */)) {
36600                         var instanceType = getDeclaredTypeOfSymbol(classSymbol).thisType; // TODO: GH#18217
36601                         if (getPropertyOfType(instanceType, name)) {
36602                             error(errorLocation, ts.Diagnostics.Cannot_find_name_0_Did_you_mean_the_instance_member_this_0, diagnosticName(nameArg));
36603                             return true;
36604                         }
36605                     }
36606                 }
36607                 location = location.parent;
36608             }
36609             return false;
36610         }
36611         function checkAndReportErrorForExtendingInterface(errorLocation) {
36612             var expression = getEntityNameForExtendingInterface(errorLocation);
36613             if (expression && resolveEntityName(expression, 64 /* Interface */, /*ignoreErrors*/ true)) {
36614                 error(errorLocation, ts.Diagnostics.Cannot_extend_an_interface_0_Did_you_mean_implements, ts.getTextOfNode(expression));
36615                 return true;
36616             }
36617             return false;
36618         }
36619         /**
36620          * Climbs up parents to an ExpressionWithTypeArguments, and returns its expression,
36621          * but returns undefined if that expression is not an EntityNameExpression.
36622          */
36623         function getEntityNameForExtendingInterface(node) {
36624             switch (node.kind) {
36625                 case 75 /* Identifier */:
36626                 case 194 /* PropertyAccessExpression */:
36627                     return node.parent ? getEntityNameForExtendingInterface(node.parent) : undefined;
36628                 case 216 /* ExpressionWithTypeArguments */:
36629                     if (ts.isEntityNameExpression(node.expression)) {
36630                         return node.expression;
36631                     }
36632                 // falls through
36633                 default:
36634                     return undefined;
36635             }
36636         }
36637         function checkAndReportErrorForUsingTypeAsNamespace(errorLocation, name, meaning) {
36638             var namespaceMeaning = 1920 /* Namespace */ | (ts.isInJSFile(errorLocation) ? 111551 /* Value */ : 0);
36639             if (meaning === namespaceMeaning) {
36640                 var symbol = resolveSymbol(resolveName(errorLocation, name, 788968 /* Type */ & ~namespaceMeaning, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false));
36641                 var parent = errorLocation.parent;
36642                 if (symbol) {
36643                     if (ts.isQualifiedName(parent)) {
36644                         ts.Debug.assert(parent.left === errorLocation, "Should only be resolving left side of qualified name as a namespace");
36645                         var propName = parent.right.escapedText;
36646                         var propType = getPropertyOfType(getDeclaredTypeOfSymbol(symbol), propName);
36647                         if (propType) {
36648                             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));
36649                             return true;
36650                         }
36651                     }
36652                     error(errorLocation, ts.Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_namespace_here, ts.unescapeLeadingUnderscores(name));
36653                     return true;
36654                 }
36655             }
36656             return false;
36657         }
36658         function checkAndReportErrorForUsingValueAsType(errorLocation, name, meaning) {
36659             if (meaning & (788968 /* Type */ & ~1920 /* Namespace */)) {
36660                 var symbol = resolveSymbol(resolveName(errorLocation, name, ~788968 /* Type */ & 111551 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false));
36661                 if (symbol && !(symbol.flags & 1920 /* Namespace */)) {
36662                     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));
36663                     return true;
36664                 }
36665             }
36666             return false;
36667         }
36668         function isPrimitiveTypeName(name) {
36669             return name === "any" || name === "string" || name === "number" || name === "boolean" || name === "never" || name === "unknown";
36670         }
36671         function checkAndReportErrorForExportingPrimitiveType(errorLocation, name) {
36672             if (isPrimitiveTypeName(name) && errorLocation.parent.kind === 263 /* ExportSpecifier */) {
36673                 error(errorLocation, ts.Diagnostics.Cannot_export_0_Only_local_declarations_can_be_exported_from_a_module, name);
36674                 return true;
36675             }
36676             return false;
36677         }
36678         function checkAndReportErrorForUsingTypeAsValue(errorLocation, name, meaning) {
36679             if (meaning & (111551 /* Value */ & ~1024 /* NamespaceModule */)) {
36680                 if (isPrimitiveTypeName(name)) {
36681                     error(errorLocation, ts.Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_value_here, ts.unescapeLeadingUnderscores(name));
36682                     return true;
36683                 }
36684                 var symbol = resolveSymbol(resolveName(errorLocation, name, 788968 /* Type */ & ~111551 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false));
36685                 if (symbol && !(symbol.flags & 1024 /* NamespaceModule */)) {
36686                     var message = isES2015OrLaterConstructorName(name)
36687                         ? 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
36688                         : ts.Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_value_here;
36689                     error(errorLocation, message, ts.unescapeLeadingUnderscores(name));
36690                     return true;
36691                 }
36692             }
36693             return false;
36694         }
36695         function isES2015OrLaterConstructorName(n) {
36696             switch (n) {
36697                 case "Promise":
36698                 case "Symbol":
36699                 case "Map":
36700                 case "WeakMap":
36701                 case "Set":
36702                 case "WeakSet":
36703                     return true;
36704             }
36705             return false;
36706         }
36707         function checkAndReportErrorForUsingNamespaceModuleAsValue(errorLocation, name, meaning) {
36708             if (meaning & (111551 /* Value */ & ~1024 /* NamespaceModule */ & ~788968 /* Type */)) {
36709                 var symbol = resolveSymbol(resolveName(errorLocation, name, 1024 /* NamespaceModule */ & ~111551 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false));
36710                 if (symbol) {
36711                     error(errorLocation, ts.Diagnostics.Cannot_use_namespace_0_as_a_value, ts.unescapeLeadingUnderscores(name));
36712                     return true;
36713                 }
36714             }
36715             else if (meaning & (788968 /* Type */ & ~1024 /* NamespaceModule */ & ~111551 /* Value */)) {
36716                 var symbol = resolveSymbol(resolveName(errorLocation, name, (512 /* ValueModule */ | 1024 /* NamespaceModule */) & ~788968 /* Type */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false));
36717                 if (symbol) {
36718                     error(errorLocation, ts.Diagnostics.Cannot_use_namespace_0_as_a_type, ts.unescapeLeadingUnderscores(name));
36719                     return true;
36720                 }
36721             }
36722             return false;
36723         }
36724         function checkResolvedBlockScopedVariable(result, errorLocation) {
36725             ts.Debug.assert(!!(result.flags & 2 /* BlockScopedVariable */ || result.flags & 32 /* Class */ || result.flags & 384 /* Enum */));
36726             if (result.flags & (16 /* Function */ | 1 /* FunctionScopedVariable */ | 67108864 /* Assignment */) && result.flags & 32 /* Class */) {
36727                 // constructor functions aren't block scoped
36728                 return;
36729             }
36730             // Block-scoped variables cannot be used before their definition
36731             var declaration = ts.find(result.declarations, function (d) { return ts.isBlockOrCatchScoped(d) || ts.isClassLike(d) || (d.kind === 248 /* EnumDeclaration */); });
36732             if (declaration === undefined)
36733                 return ts.Debug.fail("checkResolvedBlockScopedVariable could not find block-scoped declaration");
36734             if (!(declaration.flags & 8388608 /* Ambient */) && !isBlockScopedNameDeclaredBeforeUse(declaration, errorLocation)) {
36735                 var diagnosticMessage = void 0;
36736                 var declarationName = ts.declarationNameToString(ts.getNameOfDeclaration(declaration));
36737                 if (result.flags & 2 /* BlockScopedVariable */) {
36738                     diagnosticMessage = error(errorLocation, ts.Diagnostics.Block_scoped_variable_0_used_before_its_declaration, declarationName);
36739                 }
36740                 else if (result.flags & 32 /* Class */) {
36741                     diagnosticMessage = error(errorLocation, ts.Diagnostics.Class_0_used_before_its_declaration, declarationName);
36742                 }
36743                 else if (result.flags & 256 /* RegularEnum */) {
36744                     diagnosticMessage = error(errorLocation, ts.Diagnostics.Enum_0_used_before_its_declaration, declarationName);
36745                 }
36746                 else {
36747                     ts.Debug.assert(!!(result.flags & 128 /* ConstEnum */));
36748                     if (compilerOptions.preserveConstEnums) {
36749                         diagnosticMessage = error(errorLocation, ts.Diagnostics.Class_0_used_before_its_declaration, declarationName);
36750                     }
36751                 }
36752                 if (diagnosticMessage) {
36753                     ts.addRelatedInfo(diagnosticMessage, ts.createDiagnosticForNode(declaration, ts.Diagnostics._0_is_declared_here, declarationName));
36754                 }
36755             }
36756         }
36757         /* Starting from 'initial' node walk up the parent chain until 'stopAt' node is reached.
36758          * If at any point current node is equal to 'parent' node - return true.
36759          * Return false if 'stopAt' node is reached or isFunctionLike(current) === true.
36760          */
36761         function isSameScopeDescendentOf(initial, parent, stopAt) {
36762             return !!parent && !!ts.findAncestor(initial, function (n) { return n === stopAt || ts.isFunctionLike(n) ? "quit" : n === parent; });
36763         }
36764         function getAnyImportSyntax(node) {
36765             switch (node.kind) {
36766                 case 253 /* ImportEqualsDeclaration */:
36767                     return node;
36768                 case 255 /* ImportClause */:
36769                     return node.parent;
36770                 case 256 /* NamespaceImport */:
36771                     return node.parent.parent;
36772                 case 258 /* ImportSpecifier */:
36773                     return node.parent.parent.parent;
36774                 default:
36775                     return undefined;
36776             }
36777         }
36778         function getDeclarationOfAliasSymbol(symbol) {
36779             return ts.find(symbol.declarations, isAliasSymbolDeclaration);
36780         }
36781         /**
36782          * An alias symbol is created by one of the following declarations:
36783          * import <symbol> = ...
36784          * import <symbol> from ...
36785          * import * as <symbol> from ...
36786          * import { x as <symbol> } from ...
36787          * export { x as <symbol> } from ...
36788          * export * as ns <symbol> from ...
36789          * export = <EntityNameExpression>
36790          * export default <EntityNameExpression>
36791          * module.exports = <EntityNameExpression>
36792          * {<Identifier>}
36793          * {name: <EntityNameExpression>}
36794          */
36795         function isAliasSymbolDeclaration(node) {
36796             return node.kind === 253 /* ImportEqualsDeclaration */ ||
36797                 node.kind === 252 /* NamespaceExportDeclaration */ ||
36798                 node.kind === 255 /* ImportClause */ && !!node.name ||
36799                 node.kind === 256 /* NamespaceImport */ ||
36800                 node.kind === 262 /* NamespaceExport */ ||
36801                 node.kind === 258 /* ImportSpecifier */ ||
36802                 node.kind === 263 /* ExportSpecifier */ ||
36803                 node.kind === 259 /* ExportAssignment */ && ts.exportAssignmentIsAlias(node) ||
36804                 ts.isBinaryExpression(node) && ts.getAssignmentDeclarationKind(node) === 2 /* ModuleExports */ && ts.exportAssignmentIsAlias(node) ||
36805                 ts.isPropertyAccessExpression(node)
36806                     && ts.isBinaryExpression(node.parent)
36807                     && node.parent.left === node
36808                     && node.parent.operatorToken.kind === 62 /* EqualsToken */
36809                     && isAliasableOrJsExpression(node.parent.right) ||
36810                 node.kind === 282 /* ShorthandPropertyAssignment */ ||
36811                 node.kind === 281 /* PropertyAssignment */ && isAliasableOrJsExpression(node.initializer);
36812         }
36813         function isAliasableOrJsExpression(e) {
36814             return ts.isAliasableExpression(e) || ts.isFunctionExpression(e) && isJSConstructor(e);
36815         }
36816         function getTargetOfImportEqualsDeclaration(node, dontResolveAlias) {
36817             if (node.moduleReference.kind === 265 /* ExternalModuleReference */) {
36818                 var immediate = resolveExternalModuleName(node, ts.getExternalModuleImportEqualsDeclarationExpression(node));
36819                 var resolved_4 = resolveExternalModuleSymbol(immediate);
36820                 markSymbolOfAliasDeclarationIfTypeOnly(node, immediate, resolved_4, /*overwriteEmpty*/ false);
36821                 return resolved_4;
36822             }
36823             var resolved = getSymbolOfPartOfRightHandSideOfImportEquals(node.moduleReference, dontResolveAlias);
36824             checkAndReportErrorForResolvingImportAliasToTypeOnlySymbol(node, resolved);
36825             return resolved;
36826         }
36827         function checkAndReportErrorForResolvingImportAliasToTypeOnlySymbol(node, resolved) {
36828             if (markSymbolOfAliasDeclarationIfTypeOnly(node, /*immediateTarget*/ undefined, resolved, /*overwriteEmpty*/ false)) {
36829                 var typeOnlyDeclaration = getTypeOnlyAliasDeclaration(getSymbolOfNode(node));
36830                 var isExport = ts.typeOnlyDeclarationIsExport(typeOnlyDeclaration);
36831                 var message = isExport
36832                     ? ts.Diagnostics.An_import_alias_cannot_reference_a_declaration_that_was_exported_using_export_type
36833                     : ts.Diagnostics.An_import_alias_cannot_reference_a_declaration_that_was_imported_using_import_type;
36834                 var relatedMessage = isExport
36835                     ? ts.Diagnostics._0_was_exported_here
36836                     : ts.Diagnostics._0_was_imported_here;
36837                 // Non-null assertion is safe because the optionality comes from ImportClause,
36838                 // but if an ImportClause was the typeOnlyDeclaration, it had to have a `name`.
36839                 var name = ts.unescapeLeadingUnderscores(typeOnlyDeclaration.name.escapedText);
36840                 ts.addRelatedInfo(error(node.moduleReference, message), ts.createDiagnosticForNode(typeOnlyDeclaration, relatedMessage, name));
36841             }
36842         }
36843         function resolveExportByName(moduleSymbol, name, sourceNode, dontResolveAlias) {
36844             var exportValue = moduleSymbol.exports.get("export=" /* ExportEquals */);
36845             if (exportValue) {
36846                 return getPropertyOfType(getTypeOfSymbol(exportValue), name);
36847             }
36848             var exportSymbol = moduleSymbol.exports.get(name);
36849             var resolved = resolveSymbol(exportSymbol, dontResolveAlias);
36850             markSymbolOfAliasDeclarationIfTypeOnly(sourceNode, exportSymbol, resolved, /*overwriteEmpty*/ false);
36851             return resolved;
36852         }
36853         function isSyntacticDefault(node) {
36854             return ((ts.isExportAssignment(node) && !node.isExportEquals) || ts.hasModifier(node, 512 /* Default */) || ts.isExportSpecifier(node));
36855         }
36856         function canHaveSyntheticDefault(file, moduleSymbol, dontResolveAlias) {
36857             if (!allowSyntheticDefaultImports) {
36858                 return false;
36859             }
36860             // Declaration files (and ambient modules)
36861             if (!file || file.isDeclarationFile) {
36862                 // Definitely cannot have a synthetic default if they have a syntactic default member specified
36863                 var defaultExportSymbol = resolveExportByName(moduleSymbol, "default" /* Default */, /*sourceNode*/ undefined, /*dontResolveAlias*/ true); // Dont resolve alias because we want the immediately exported symbol's declaration
36864                 if (defaultExportSymbol && ts.some(defaultExportSymbol.declarations, isSyntacticDefault)) {
36865                     return false;
36866                 }
36867                 // It _might_ still be incorrect to assume there is no __esModule marker on the import at runtime, even if there is no `default` member
36868                 // So we check a bit more,
36869                 if (resolveExportByName(moduleSymbol, ts.escapeLeadingUnderscores("__esModule"), /*sourceNode*/ undefined, dontResolveAlias)) {
36870                     // If there is an `__esModule` specified in the declaration (meaning someone explicitly added it or wrote it in their code),
36871                     // it definitely is a module and does not have a synthetic default
36872                     return false;
36873                 }
36874                 // There are _many_ declaration files not written with esmodules in mind that still get compiled into a format with __esModule set
36875                 // Meaning there may be no default at runtime - however to be on the permissive side, we allow access to a synthetic default member
36876                 // as there is no marker to indicate if the accompanying JS has `__esModule` or not, or is even native esm
36877                 return true;
36878             }
36879             // TypeScript files never have a synthetic default (as they are always emitted with an __esModule marker) _unless_ they contain an export= statement
36880             if (!ts.isSourceFileJS(file)) {
36881                 return hasExportAssignmentSymbol(moduleSymbol);
36882             }
36883             // 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
36884             return !file.externalModuleIndicator && !resolveExportByName(moduleSymbol, ts.escapeLeadingUnderscores("__esModule"), /*sourceNode*/ undefined, dontResolveAlias);
36885         }
36886         function getTargetOfImportClause(node, dontResolveAlias) {
36887             var moduleSymbol = resolveExternalModuleName(node, node.parent.moduleSpecifier);
36888             if (moduleSymbol) {
36889                 var exportDefaultSymbol = void 0;
36890                 if (ts.isShorthandAmbientModuleSymbol(moduleSymbol)) {
36891                     exportDefaultSymbol = moduleSymbol;
36892                 }
36893                 else {
36894                     exportDefaultSymbol = resolveExportByName(moduleSymbol, "default" /* Default */, node, dontResolveAlias);
36895                 }
36896                 var file = ts.find(moduleSymbol.declarations, ts.isSourceFile);
36897                 var hasSyntheticDefault = canHaveSyntheticDefault(file, moduleSymbol, dontResolveAlias);
36898                 if (!exportDefaultSymbol && !hasSyntheticDefault) {
36899                     if (hasExportAssignmentSymbol(moduleSymbol)) {
36900                         var compilerOptionName = moduleKind >= ts.ModuleKind.ES2015 ? "allowSyntheticDefaultImports" : "esModuleInterop";
36901                         var exportEqualsSymbol = moduleSymbol.exports.get("export=" /* ExportEquals */);
36902                         var exportAssignment = exportEqualsSymbol.valueDeclaration;
36903                         var err = error(node.name, ts.Diagnostics.Module_0_can_only_be_default_imported_using_the_1_flag, symbolToString(moduleSymbol), compilerOptionName);
36904                         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));
36905                     }
36906                     else {
36907                         reportNonDefaultExport(moduleSymbol, node);
36908                     }
36909                 }
36910                 else if (hasSyntheticDefault) {
36911                     // per emit behavior, a synthetic default overrides a "real" .default member if `__esModule` is not present
36912                     var resolved = resolveExternalModuleSymbol(moduleSymbol, dontResolveAlias) || resolveSymbol(moduleSymbol, dontResolveAlias);
36913                     markSymbolOfAliasDeclarationIfTypeOnly(node, moduleSymbol, resolved, /*overwriteTypeOnly*/ false);
36914                     return resolved;
36915                 }
36916                 markSymbolOfAliasDeclarationIfTypeOnly(node, exportDefaultSymbol, /*finalTarget*/ undefined, /*overwriteTypeOnly*/ false);
36917                 return exportDefaultSymbol;
36918             }
36919         }
36920         function reportNonDefaultExport(moduleSymbol, node) {
36921             var _a, _b;
36922             if ((_a = moduleSymbol.exports) === null || _a === void 0 ? void 0 : _a.has(node.symbol.escapedName)) {
36923                 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));
36924             }
36925             else {
36926                 var diagnostic = error(node.name, ts.Diagnostics.Module_0_has_no_default_export, symbolToString(moduleSymbol));
36927                 var exportStar = (_b = moduleSymbol.exports) === null || _b === void 0 ? void 0 : _b.get("__export" /* ExportStar */);
36928                 if (exportStar) {
36929                     var defaultExport = ts.find(exportStar.declarations, function (decl) {
36930                         var _a, _b;
36931                         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 */)));
36932                     });
36933                     if (defaultExport) {
36934                         ts.addRelatedInfo(diagnostic, ts.createDiagnosticForNode(defaultExport, ts.Diagnostics.export_Asterisk_does_not_re_export_a_default));
36935                     }
36936                 }
36937             }
36938         }
36939         function getTargetOfNamespaceImport(node, dontResolveAlias) {
36940             var moduleSpecifier = node.parent.parent.moduleSpecifier;
36941             var immediate = resolveExternalModuleName(node, moduleSpecifier);
36942             var resolved = resolveESModuleSymbol(immediate, moduleSpecifier, dontResolveAlias, /*suppressUsageError*/ false);
36943             markSymbolOfAliasDeclarationIfTypeOnly(node, immediate, resolved, /*overwriteEmpty*/ false);
36944             return resolved;
36945         }
36946         function getTargetOfNamespaceExport(node, dontResolveAlias) {
36947             var moduleSpecifier = node.parent.moduleSpecifier;
36948             var immediate = moduleSpecifier && resolveExternalModuleName(node, moduleSpecifier);
36949             var resolved = moduleSpecifier && resolveESModuleSymbol(immediate, moduleSpecifier, dontResolveAlias, /*suppressUsageError*/ false);
36950             markSymbolOfAliasDeclarationIfTypeOnly(node, immediate, resolved, /*overwriteEmpty*/ false);
36951             return resolved;
36952         }
36953         // This function creates a synthetic symbol that combines the value side of one symbol with the
36954         // type/namespace side of another symbol. Consider this example:
36955         //
36956         //   declare module graphics {
36957         //       interface Point {
36958         //           x: number;
36959         //           y: number;
36960         //       }
36961         //   }
36962         //   declare var graphics: {
36963         //       Point: new (x: number, y: number) => graphics.Point;
36964         //   }
36965         //   declare module "graphics" {
36966         //       export = graphics;
36967         //   }
36968         //
36969         // An 'import { Point } from "graphics"' needs to create a symbol that combines the value side 'Point'
36970         // property with the type/namespace side interface 'Point'.
36971         function combineValueAndTypeSymbols(valueSymbol, typeSymbol) {
36972             if (valueSymbol === unknownSymbol && typeSymbol === unknownSymbol) {
36973                 return unknownSymbol;
36974             }
36975             if (valueSymbol.flags & (788968 /* Type */ | 1920 /* Namespace */)) {
36976                 return valueSymbol;
36977             }
36978             var result = createSymbol(valueSymbol.flags | typeSymbol.flags, valueSymbol.escapedName);
36979             result.declarations = ts.deduplicate(ts.concatenate(valueSymbol.declarations, typeSymbol.declarations), ts.equateValues);
36980             result.parent = valueSymbol.parent || typeSymbol.parent;
36981             if (valueSymbol.valueDeclaration)
36982                 result.valueDeclaration = valueSymbol.valueDeclaration;
36983             if (typeSymbol.members)
36984                 result.members = ts.cloneMap(typeSymbol.members);
36985             if (valueSymbol.exports)
36986                 result.exports = ts.cloneMap(valueSymbol.exports);
36987             return result;
36988         }
36989         function getExportOfModule(symbol, specifier, dontResolveAlias) {
36990             var _a;
36991             if (symbol.flags & 1536 /* Module */) {
36992                 var name = ((_a = specifier.propertyName) !== null && _a !== void 0 ? _a : specifier.name).escapedText;
36993                 var exportSymbol = getExportsOfSymbol(symbol).get(name);
36994                 var resolved = resolveSymbol(exportSymbol, dontResolveAlias);
36995                 markSymbolOfAliasDeclarationIfTypeOnly(specifier, exportSymbol, resolved, /*overwriteEmpty*/ false);
36996                 return resolved;
36997             }
36998         }
36999         function getPropertyOfVariable(symbol, name) {
37000             if (symbol.flags & 3 /* Variable */) {
37001                 var typeAnnotation = symbol.valueDeclaration.type;
37002                 if (typeAnnotation) {
37003                     return resolveSymbol(getPropertyOfType(getTypeFromTypeNode(typeAnnotation), name));
37004                 }
37005             }
37006         }
37007         function getExternalModuleMember(node, specifier, dontResolveAlias) {
37008             var _a;
37009             if (dontResolveAlias === void 0) { dontResolveAlias = false; }
37010             var moduleSymbol = resolveExternalModuleName(node, node.moduleSpecifier); // TODO: GH#18217
37011             var name = specifier.propertyName || specifier.name;
37012             var suppressInteropError = name.escapedText === "default" /* Default */ && !!(compilerOptions.allowSyntheticDefaultImports || compilerOptions.esModuleInterop);
37013             var targetSymbol = resolveESModuleSymbol(moduleSymbol, node.moduleSpecifier, dontResolveAlias, suppressInteropError);
37014             if (targetSymbol) {
37015                 if (name.escapedText) {
37016                     if (ts.isShorthandAmbientModuleSymbol(moduleSymbol)) {
37017                         return moduleSymbol;
37018                     }
37019                     var symbolFromVariable = void 0;
37020                     // First check if module was specified with "export=". If so, get the member from the resolved type
37021                     if (moduleSymbol && moduleSymbol.exports && moduleSymbol.exports.get("export=" /* ExportEquals */)) {
37022                         symbolFromVariable = getPropertyOfType(getTypeOfSymbol(targetSymbol), name.escapedText);
37023                     }
37024                     else {
37025                         symbolFromVariable = getPropertyOfVariable(targetSymbol, name.escapedText);
37026                     }
37027                     // if symbolFromVariable is export - get its final target
37028                     symbolFromVariable = resolveSymbol(symbolFromVariable, dontResolveAlias);
37029                     var symbolFromModule = getExportOfModule(targetSymbol, specifier, dontResolveAlias);
37030                     if (symbolFromModule === undefined && name.escapedText === "default" /* Default */) {
37031                         var file = ts.find(moduleSymbol.declarations, ts.isSourceFile);
37032                         if (canHaveSyntheticDefault(file, moduleSymbol, dontResolveAlias)) {
37033                             symbolFromModule = resolveExternalModuleSymbol(moduleSymbol, dontResolveAlias) || resolveSymbol(moduleSymbol, dontResolveAlias);
37034                         }
37035                     }
37036                     var symbol = symbolFromModule && symbolFromVariable && symbolFromModule !== symbolFromVariable ?
37037                         combineValueAndTypeSymbols(symbolFromVariable, symbolFromModule) :
37038                         symbolFromModule || symbolFromVariable;
37039                     if (!symbol) {
37040                         var moduleName = getFullyQualifiedName(moduleSymbol, node);
37041                         var declarationName = ts.declarationNameToString(name);
37042                         var suggestion = getSuggestedSymbolForNonexistentModule(name, targetSymbol);
37043                         if (suggestion !== undefined) {
37044                             var suggestionName = symbolToString(suggestion);
37045                             var diagnostic = error(name, ts.Diagnostics.Module_0_has_no_exported_member_1_Did_you_mean_2, moduleName, declarationName, suggestionName);
37046                             if (suggestion.valueDeclaration) {
37047                                 ts.addRelatedInfo(diagnostic, ts.createDiagnosticForNode(suggestion.valueDeclaration, ts.Diagnostics._0_is_declared_here, suggestionName));
37048                             }
37049                         }
37050                         else {
37051                             if ((_a = moduleSymbol.exports) === null || _a === void 0 ? void 0 : _a.has("default" /* Default */)) {
37052                                 error(name, ts.Diagnostics.Module_0_has_no_exported_member_1_Did_you_mean_to_use_import_1_from_0_instead, moduleName, declarationName);
37053                             }
37054                             else {
37055                                 reportNonExportedMember(node, name, declarationName, moduleSymbol, moduleName);
37056                             }
37057                         }
37058                     }
37059                     return symbol;
37060                 }
37061             }
37062         }
37063         function reportNonExportedMember(node, name, declarationName, moduleSymbol, moduleName) {
37064             var _a;
37065             var localSymbol = (_a = moduleSymbol.valueDeclaration.locals) === null || _a === void 0 ? void 0 : _a.get(name.escapedText);
37066             var exports = moduleSymbol.exports;
37067             if (localSymbol) {
37068                 var exportedEqualsSymbol = exports === null || exports === void 0 ? void 0 : exports.get("export=" /* ExportEquals */);
37069                 if (exportedEqualsSymbol) {
37070                     getSymbolIfSameReference(exportedEqualsSymbol, localSymbol) ? reportInvalidImportEqualsExportMember(node, name, declarationName, moduleName) :
37071                         error(name, ts.Diagnostics.Module_0_has_no_exported_member_1, moduleName, declarationName);
37072                 }
37073                 else {
37074                     var exportedSymbol = exports ? ts.find(symbolsToArray(exports), function (symbol) { return !!getSymbolIfSameReference(symbol, localSymbol); }) : undefined;
37075                     var diagnostic = exportedSymbol ? error(name, ts.Diagnostics.Module_0_declares_1_locally_but_it_is_exported_as_2, moduleName, declarationName, symbolToString(exportedSymbol)) :
37076                         error(name, ts.Diagnostics.Module_0_declares_1_locally_but_it_is_not_exported, moduleName, declarationName);
37077                     ts.addRelatedInfo.apply(void 0, __spreadArrays([diagnostic], ts.map(localSymbol.declarations, function (decl, index) {
37078                         return ts.createDiagnosticForNode(decl, index === 0 ? ts.Diagnostics._0_is_declared_here : ts.Diagnostics.and_here, declarationName);
37079                     })));
37080                 }
37081             }
37082             else {
37083                 error(name, ts.Diagnostics.Module_0_has_no_exported_member_1, moduleName, declarationName);
37084             }
37085         }
37086         function reportInvalidImportEqualsExportMember(node, name, declarationName, moduleName) {
37087             if (moduleKind >= ts.ModuleKind.ES2015) {
37088                 var message = compilerOptions.esModuleInterop ? ts.Diagnostics._0_can_only_be_imported_by_using_a_default_import :
37089                     ts.Diagnostics._0_can_only_be_imported_by_turning_on_the_esModuleInterop_flag_and_using_a_default_import;
37090                 error(name, message, declarationName);
37091             }
37092             else {
37093                 if (ts.isInJSFile(node)) {
37094                     var message = compilerOptions.esModuleInterop ? ts.Diagnostics._0_can_only_be_imported_by_using_a_require_call_or_by_using_a_default_import :
37095                         ts.Diagnostics._0_can_only_be_imported_by_using_a_require_call_or_by_turning_on_the_esModuleInterop_flag_and_using_a_default_import;
37096                     error(name, message, declarationName);
37097                 }
37098                 else {
37099                     var message = compilerOptions.esModuleInterop ? ts.Diagnostics._0_can_only_be_imported_by_using_import_1_require_2_or_a_default_import :
37100                         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;
37101                     error(name, message, declarationName, declarationName, moduleName);
37102                 }
37103             }
37104         }
37105         function getTargetOfImportSpecifier(node, dontResolveAlias) {
37106             var resolved = getExternalModuleMember(node.parent.parent.parent, node, dontResolveAlias);
37107             markSymbolOfAliasDeclarationIfTypeOnly(node, /*immediateTarget*/ undefined, resolved, /*overwriteEmpty*/ false);
37108             return resolved;
37109         }
37110         function getTargetOfNamespaceExportDeclaration(node, dontResolveAlias) {
37111             var resolved = resolveExternalModuleSymbol(node.parent.symbol, dontResolveAlias);
37112             markSymbolOfAliasDeclarationIfTypeOnly(node, /*immediateTarget*/ undefined, resolved, /*overwriteEmpty*/ false);
37113             return resolved;
37114         }
37115         function getTargetOfExportSpecifier(node, meaning, dontResolveAlias) {
37116             var resolved = node.parent.parent.moduleSpecifier ?
37117                 getExternalModuleMember(node.parent.parent, node, dontResolveAlias) :
37118                 resolveEntityName(node.propertyName || node.name, meaning, /*ignoreErrors*/ false, dontResolveAlias);
37119             markSymbolOfAliasDeclarationIfTypeOnly(node, /*immediateTarget*/ undefined, resolved, /*overwriteEmpty*/ false);
37120             return resolved;
37121         }
37122         function getTargetOfExportAssignment(node, dontResolveAlias) {
37123             var expression = ts.isExportAssignment(node) ? node.expression : node.right;
37124             var resolved = getTargetOfAliasLikeExpression(expression, dontResolveAlias);
37125             markSymbolOfAliasDeclarationIfTypeOnly(node, /*immediateTarget*/ undefined, resolved, /*overwriteEmpty*/ false);
37126             return resolved;
37127         }
37128         function getTargetOfAliasLikeExpression(expression, dontResolveAlias) {
37129             if (ts.isClassExpression(expression)) {
37130                 return checkExpressionCached(expression).symbol;
37131             }
37132             if (!ts.isEntityName(expression) && !ts.isEntityNameExpression(expression)) {
37133                 return undefined;
37134             }
37135             var aliasLike = resolveEntityName(expression, 111551 /* Value */ | 788968 /* Type */ | 1920 /* Namespace */, /*ignoreErrors*/ true, dontResolveAlias);
37136             if (aliasLike) {
37137                 return aliasLike;
37138             }
37139             checkExpressionCached(expression);
37140             return getNodeLinks(expression).resolvedSymbol;
37141         }
37142         function getTargetOfPropertyAssignment(node, dontRecursivelyResolve) {
37143             var expression = node.initializer;
37144             return getTargetOfAliasLikeExpression(expression, dontRecursivelyResolve);
37145         }
37146         function getTargetOfPropertyAccessExpression(node, dontRecursivelyResolve) {
37147             if (!(ts.isBinaryExpression(node.parent) && node.parent.left === node && node.parent.operatorToken.kind === 62 /* EqualsToken */)) {
37148                 return undefined;
37149             }
37150             return getTargetOfAliasLikeExpression(node.parent.right, dontRecursivelyResolve);
37151         }
37152         function getTargetOfAliasDeclaration(node, dontRecursivelyResolve) {
37153             if (dontRecursivelyResolve === void 0) { dontRecursivelyResolve = false; }
37154             switch (node.kind) {
37155                 case 253 /* ImportEqualsDeclaration */:
37156                     return getTargetOfImportEqualsDeclaration(node, dontRecursivelyResolve);
37157                 case 255 /* ImportClause */:
37158                     return getTargetOfImportClause(node, dontRecursivelyResolve);
37159                 case 256 /* NamespaceImport */:
37160                     return getTargetOfNamespaceImport(node, dontRecursivelyResolve);
37161                 case 262 /* NamespaceExport */:
37162                     return getTargetOfNamespaceExport(node, dontRecursivelyResolve);
37163                 case 258 /* ImportSpecifier */:
37164                     return getTargetOfImportSpecifier(node, dontRecursivelyResolve);
37165                 case 263 /* ExportSpecifier */:
37166                     return getTargetOfExportSpecifier(node, 111551 /* Value */ | 788968 /* Type */ | 1920 /* Namespace */, dontRecursivelyResolve);
37167                 case 259 /* ExportAssignment */:
37168                 case 209 /* BinaryExpression */:
37169                     return getTargetOfExportAssignment(node, dontRecursivelyResolve);
37170                 case 252 /* NamespaceExportDeclaration */:
37171                     return getTargetOfNamespaceExportDeclaration(node, dontRecursivelyResolve);
37172                 case 282 /* ShorthandPropertyAssignment */:
37173                     return resolveEntityName(node.name, 111551 /* Value */ | 788968 /* Type */ | 1920 /* Namespace */, /*ignoreErrors*/ true, dontRecursivelyResolve);
37174                 case 281 /* PropertyAssignment */:
37175                     return getTargetOfPropertyAssignment(node, dontRecursivelyResolve);
37176                 case 194 /* PropertyAccessExpression */:
37177                     return getTargetOfPropertyAccessExpression(node, dontRecursivelyResolve);
37178                 default:
37179                     return ts.Debug.fail();
37180             }
37181         }
37182         /**
37183          * Indicates that a symbol is an alias that does not merge with a local declaration.
37184          * OR Is a JSContainer which may merge an alias with a local declaration
37185          */
37186         function isNonLocalAlias(symbol, excludes) {
37187             if (excludes === void 0) { excludes = 111551 /* Value */ | 788968 /* Type */ | 1920 /* Namespace */; }
37188             if (!symbol)
37189                 return false;
37190             return (symbol.flags & (2097152 /* Alias */ | excludes)) === 2097152 /* Alias */ || !!(symbol.flags & 2097152 /* Alias */ && symbol.flags & 67108864 /* Assignment */);
37191         }
37192         function resolveSymbol(symbol, dontResolveAlias) {
37193             return !dontResolveAlias && isNonLocalAlias(symbol) ? resolveAlias(symbol) : symbol;
37194         }
37195         function resolveAlias(symbol) {
37196             ts.Debug.assert((symbol.flags & 2097152 /* Alias */) !== 0, "Should only get Alias here.");
37197             var links = getSymbolLinks(symbol);
37198             if (!links.target) {
37199                 links.target = resolvingSymbol;
37200                 var node = getDeclarationOfAliasSymbol(symbol);
37201                 if (!node)
37202                     return ts.Debug.fail();
37203                 var target = getTargetOfAliasDeclaration(node);
37204                 if (links.target === resolvingSymbol) {
37205                     links.target = target || unknownSymbol;
37206                 }
37207                 else {
37208                     error(node, ts.Diagnostics.Circular_definition_of_import_alias_0, symbolToString(symbol));
37209                 }
37210             }
37211             else if (links.target === resolvingSymbol) {
37212                 links.target = unknownSymbol;
37213             }
37214             return links.target;
37215         }
37216         function tryResolveAlias(symbol) {
37217             var links = getSymbolLinks(symbol);
37218             if (links.target !== resolvingSymbol) {
37219                 return resolveAlias(symbol);
37220             }
37221             return undefined;
37222         }
37223         /**
37224          * Marks a symbol as type-only if its declaration is syntactically type-only.
37225          * If it is not itself marked type-only, but resolves to a type-only alias
37226          * somewhere in its resolution chain, save a reference to the type-only alias declaration
37227          * so the alias _not_ marked type-only can be identified as _transitively_ type-only.
37228          *
37229          * This function is called on each alias declaration that could be type-only or resolve to
37230          * another type-only alias during `resolveAlias`, so that later, when an alias is used in a
37231          * JS-emitting expression, we can quickly determine if that symbol is effectively type-only
37232          * and issue an error if so.
37233          *
37234          * @param aliasDeclaration The alias declaration not marked as type-only
37235          * has already been marked as not resolving to a type-only alias. Used when recursively resolving qualified
37236          * names of import aliases, e.g. `import C = a.b.C`. If namespace `a` is not found to be type-only, the
37237          * import declaration will initially be marked as not resolving to a type-only symbol. But, namespace `b`
37238          * must still be checked for a type-only marker, overwriting the previous negative result if found.
37239          * @param immediateTarget The symbol to which the alias declaration immediately resolves
37240          * @param finalTarget The symbol to which the alias declaration ultimately resolves
37241          * @param overwriteEmpty Checks `resolvesToSymbol` for type-only declarations even if `aliasDeclaration`
37242          */
37243         function markSymbolOfAliasDeclarationIfTypeOnly(aliasDeclaration, immediateTarget, finalTarget, overwriteEmpty) {
37244             if (!aliasDeclaration)
37245                 return false;
37246             // If the declaration itself is type-only, mark it and return.
37247             // No need to check what it resolves to.
37248             var sourceSymbol = getSymbolOfNode(aliasDeclaration);
37249             if (ts.isTypeOnlyImportOrExportDeclaration(aliasDeclaration)) {
37250                 var links_1 = getSymbolLinks(sourceSymbol);
37251                 links_1.typeOnlyDeclaration = aliasDeclaration;
37252                 return true;
37253             }
37254             var links = getSymbolLinks(sourceSymbol);
37255             return markSymbolOfAliasDeclarationIfTypeOnlyWorker(links, immediateTarget, overwriteEmpty)
37256                 || markSymbolOfAliasDeclarationIfTypeOnlyWorker(links, finalTarget, overwriteEmpty);
37257         }
37258         function markSymbolOfAliasDeclarationIfTypeOnlyWorker(aliasDeclarationLinks, target, overwriteEmpty) {
37259             var _a, _b, _c;
37260             if (target && (aliasDeclarationLinks.typeOnlyDeclaration === undefined || overwriteEmpty && aliasDeclarationLinks.typeOnlyDeclaration === false)) {
37261                 var exportSymbol = (_b = (_a = target.exports) === null || _a === void 0 ? void 0 : _a.get("export=" /* ExportEquals */)) !== null && _b !== void 0 ? _b : target;
37262                 var typeOnly = exportSymbol.declarations && ts.find(exportSymbol.declarations, ts.isTypeOnlyImportOrExportDeclaration);
37263                 aliasDeclarationLinks.typeOnlyDeclaration = (_c = typeOnly !== null && typeOnly !== void 0 ? typeOnly : getSymbolLinks(exportSymbol).typeOnlyDeclaration) !== null && _c !== void 0 ? _c : false;
37264             }
37265             return !!aliasDeclarationLinks.typeOnlyDeclaration;
37266         }
37267         /** Indicates that a symbol directly or indirectly resolves to a type-only import or export. */
37268         function getTypeOnlyAliasDeclaration(symbol) {
37269             if (!(symbol.flags & 2097152 /* Alias */)) {
37270                 return undefined;
37271             }
37272             var links = getSymbolLinks(symbol);
37273             return links.typeOnlyDeclaration || undefined;
37274         }
37275         function markExportAsReferenced(node) {
37276             var symbol = getSymbolOfNode(node);
37277             var target = resolveAlias(symbol);
37278             if (target) {
37279                 var markAlias = target === unknownSymbol ||
37280                     ((target.flags & 111551 /* Value */) && !isConstEnumOrConstEnumOnlyModule(target) && !getTypeOnlyAliasDeclaration(symbol));
37281                 if (markAlias) {
37282                     markAliasSymbolAsReferenced(symbol);
37283                 }
37284             }
37285         }
37286         // When an alias symbol is referenced, we need to mark the entity it references as referenced and in turn repeat that until
37287         // we reach a non-alias or an exported entity (which is always considered referenced). We do this by checking the target of
37288         // the alias as an expression (which recursively takes us back here if the target references another alias).
37289         function markAliasSymbolAsReferenced(symbol) {
37290             var links = getSymbolLinks(symbol);
37291             if (!links.referenced) {
37292                 links.referenced = true;
37293                 var node = getDeclarationOfAliasSymbol(symbol);
37294                 if (!node)
37295                     return ts.Debug.fail();
37296                 // We defer checking of the reference of an `import =` until the import itself is referenced,
37297                 // This way a chain of imports can be elided if ultimately the final input is only used in a type
37298                 // position.
37299                 if (ts.isInternalModuleImportEqualsDeclaration(node)) {
37300                     var target = resolveSymbol(symbol);
37301                     if (target === unknownSymbol || target.flags & 111551 /* Value */) {
37302                         // import foo = <symbol>
37303                         checkExpressionCached(node.moduleReference);
37304                     }
37305                 }
37306             }
37307         }
37308         // Aliases that resolve to const enums are not marked as referenced because they are not emitted,
37309         // but their usage in value positions must be tracked to determine if the import can be type-only.
37310         function markConstEnumAliasAsReferenced(symbol) {
37311             var links = getSymbolLinks(symbol);
37312             if (!links.constEnumReferenced) {
37313                 links.constEnumReferenced = true;
37314             }
37315         }
37316         // This function is only for imports with entity names
37317         function getSymbolOfPartOfRightHandSideOfImportEquals(entityName, dontResolveAlias) {
37318             // There are three things we might try to look for. In the following examples,
37319             // the search term is enclosed in |...|:
37320             //
37321             //     import a = |b|; // Namespace
37322             //     import a = |b.c|; // Value, type, namespace
37323             //     import a = |b.c|.d; // Namespace
37324             if (entityName.kind === 75 /* Identifier */ && ts.isRightSideOfQualifiedNameOrPropertyAccess(entityName)) {
37325                 entityName = entityName.parent;
37326             }
37327             // Check for case 1 and 3 in the above example
37328             if (entityName.kind === 75 /* Identifier */ || entityName.parent.kind === 153 /* QualifiedName */) {
37329                 return resolveEntityName(entityName, 1920 /* Namespace */, /*ignoreErrors*/ false, dontResolveAlias);
37330             }
37331             else {
37332                 // Case 2 in above example
37333                 // entityName.kind could be a QualifiedName or a Missing identifier
37334                 ts.Debug.assert(entityName.parent.kind === 253 /* ImportEqualsDeclaration */);
37335                 return resolveEntityName(entityName, 111551 /* Value */ | 788968 /* Type */ | 1920 /* Namespace */, /*ignoreErrors*/ false, dontResolveAlias);
37336             }
37337         }
37338         function getFullyQualifiedName(symbol, containingLocation) {
37339             return symbol.parent ? getFullyQualifiedName(symbol.parent, containingLocation) + "." + symbolToString(symbol) : symbolToString(symbol, containingLocation, /*meaning*/ undefined, 16 /* DoNotIncludeSymbolChain */ | 4 /* AllowAnyNodeKind */);
37340         }
37341         /**
37342          * Resolves a qualified name and any involved aliases.
37343          */
37344         function resolveEntityName(name, meaning, ignoreErrors, dontResolveAlias, location) {
37345             if (ts.nodeIsMissing(name)) {
37346                 return undefined;
37347             }
37348             var namespaceMeaning = 1920 /* Namespace */ | (ts.isInJSFile(name) ? meaning & 111551 /* Value */ : 0);
37349             var symbol;
37350             if (name.kind === 75 /* Identifier */) {
37351                 var message = meaning === namespaceMeaning || ts.nodeIsSynthesized(name) ? ts.Diagnostics.Cannot_find_namespace_0 : getCannotFindNameDiagnosticForName(ts.getFirstIdentifier(name));
37352                 var symbolFromJSPrototype = ts.isInJSFile(name) && !ts.nodeIsSynthesized(name) ? resolveEntityNameFromAssignmentDeclaration(name, meaning) : undefined;
37353                 symbol = getMergedSymbol(resolveName(location || name, name.escapedText, meaning, ignoreErrors || symbolFromJSPrototype ? undefined : message, name, /*isUse*/ true));
37354                 if (!symbol) {
37355                     return getMergedSymbol(symbolFromJSPrototype);
37356                 }
37357             }
37358             else if (name.kind === 153 /* QualifiedName */ || name.kind === 194 /* PropertyAccessExpression */) {
37359                 var left = name.kind === 153 /* QualifiedName */ ? name.left : name.expression;
37360                 var right = name.kind === 153 /* QualifiedName */ ? name.right : name.name;
37361                 var namespace = resolveEntityName(left, namespaceMeaning, ignoreErrors, /*dontResolveAlias*/ false, location);
37362                 if (!namespace || ts.nodeIsMissing(right)) {
37363                     return undefined;
37364                 }
37365                 else if (namespace === unknownSymbol) {
37366                     return namespace;
37367                 }
37368                 if (ts.isInJSFile(name)) {
37369                     if (namespace.valueDeclaration &&
37370                         ts.isVariableDeclaration(namespace.valueDeclaration) &&
37371                         namespace.valueDeclaration.initializer &&
37372                         isCommonJsRequire(namespace.valueDeclaration.initializer)) {
37373                         var moduleName = namespace.valueDeclaration.initializer.arguments[0];
37374                         var moduleSym = resolveExternalModuleName(moduleName, moduleName);
37375                         if (moduleSym) {
37376                             var resolvedModuleSymbol = resolveExternalModuleSymbol(moduleSym);
37377                             if (resolvedModuleSymbol) {
37378                                 namespace = resolvedModuleSymbol;
37379                             }
37380                         }
37381                     }
37382                 }
37383                 symbol = getMergedSymbol(getSymbol(getExportsOfSymbol(namespace), right.escapedText, meaning));
37384                 if (!symbol) {
37385                     if (!ignoreErrors) {
37386                         error(right, ts.Diagnostics.Namespace_0_has_no_exported_member_1, getFullyQualifiedName(namespace), ts.declarationNameToString(right));
37387                     }
37388                     return undefined;
37389                 }
37390             }
37391             else {
37392                 throw ts.Debug.assertNever(name, "Unknown entity name kind.");
37393             }
37394             ts.Debug.assert((ts.getCheckFlags(symbol) & 1 /* Instantiated */) === 0, "Should never get an instantiated symbol here.");
37395             if (!ts.nodeIsSynthesized(name) && ts.isEntityName(name) && (symbol.flags & 2097152 /* Alias */ || name.parent.kind === 259 /* ExportAssignment */)) {
37396                 markSymbolOfAliasDeclarationIfTypeOnly(ts.getAliasDeclarationFromName(name), symbol, /*finalTarget*/ undefined, /*overwriteEmpty*/ true);
37397             }
37398             return (symbol.flags & meaning) || dontResolveAlias ? symbol : resolveAlias(symbol);
37399         }
37400         /**
37401          * 1. For prototype-property methods like `A.prototype.m = function () ...`, try to resolve names in the scope of `A` too.
37402          * Note that prototype-property assignment to locations outside the current file (eg globals) doesn't work, so
37403          * name resolution won't work either.
37404          * 2. For property assignments like `{ x: function f () { } }`, try to resolve names in the scope of `f` too.
37405          */
37406         function resolveEntityNameFromAssignmentDeclaration(name, meaning) {
37407             if (isJSDocTypeReference(name.parent)) {
37408                 var secondaryLocation = getAssignmentDeclarationLocation(name.parent);
37409                 if (secondaryLocation) {
37410                     return resolveName(secondaryLocation, name.escapedText, meaning, /*nameNotFoundMessage*/ undefined, name, /*isUse*/ true);
37411                 }
37412             }
37413         }
37414         function getAssignmentDeclarationLocation(node) {
37415             var typeAlias = ts.findAncestor(node, function (node) { return !(ts.isJSDocNode(node) || node.flags & 4194304 /* JSDoc */) ? "quit" : ts.isJSDocTypeAlias(node); });
37416             if (typeAlias) {
37417                 return;
37418             }
37419             var host = ts.getJSDocHost(node);
37420             if (ts.isExpressionStatement(host) &&
37421                 ts.isBinaryExpression(host.expression) &&
37422                 ts.getAssignmentDeclarationKind(host.expression) === 3 /* PrototypeProperty */) {
37423                 // X.prototype.m = /** @param {K} p */ function () { } <-- look for K on X's declaration
37424                 var symbol = getSymbolOfNode(host.expression.left);
37425                 if (symbol) {
37426                     return getDeclarationOfJSPrototypeContainer(symbol);
37427                 }
37428             }
37429             if ((ts.isObjectLiteralMethod(host) || ts.isPropertyAssignment(host)) &&
37430                 ts.isBinaryExpression(host.parent.parent) &&
37431                 ts.getAssignmentDeclarationKind(host.parent.parent) === 6 /* Prototype */) {
37432                 // X.prototype = { /** @param {K} p */m() { } } <-- look for K on X's declaration
37433                 var symbol = getSymbolOfNode(host.parent.parent.left);
37434                 if (symbol) {
37435                     return getDeclarationOfJSPrototypeContainer(symbol);
37436                 }
37437             }
37438             var sig = ts.getEffectiveJSDocHost(node);
37439             if (sig && ts.isFunctionLike(sig)) {
37440                 var symbol = getSymbolOfNode(sig);
37441                 return symbol && symbol.valueDeclaration;
37442             }
37443         }
37444         function getDeclarationOfJSPrototypeContainer(symbol) {
37445             var decl = symbol.parent.valueDeclaration;
37446             if (!decl) {
37447                 return undefined;
37448             }
37449             var initializer = ts.isAssignmentDeclaration(decl) ? ts.getAssignedExpandoInitializer(decl) :
37450                 ts.hasOnlyExpressionInitializer(decl) ? ts.getDeclaredExpandoInitializer(decl) :
37451                     undefined;
37452             return initializer || decl;
37453         }
37454         /**
37455          * Get the real symbol of a declaration with an expando initializer.
37456          *
37457          * Normally, declarations have an associated symbol, but when a declaration has an expando
37458          * initializer, the expando's symbol is the one that has all the members merged into it.
37459          */
37460         function getExpandoSymbol(symbol) {
37461             var decl = symbol.valueDeclaration;
37462             if (!decl || !ts.isInJSFile(decl) || symbol.flags & 524288 /* TypeAlias */ || ts.getExpandoInitializer(decl, /*isPrototypeAssignment*/ false)) {
37463                 return undefined;
37464             }
37465             var init = ts.isVariableDeclaration(decl) ? ts.getDeclaredExpandoInitializer(decl) : ts.getAssignedExpandoInitializer(decl);
37466             if (init) {
37467                 var initSymbol = getSymbolOfNode(init);
37468                 if (initSymbol) {
37469                     return mergeJSSymbols(initSymbol, symbol);
37470                 }
37471             }
37472         }
37473         function resolveExternalModuleName(location, moduleReferenceExpression, ignoreErrors) {
37474             return resolveExternalModuleNameWorker(location, moduleReferenceExpression, ignoreErrors ? undefined : ts.Diagnostics.Cannot_find_module_0_or_its_corresponding_type_declarations);
37475         }
37476         function resolveExternalModuleNameWorker(location, moduleReferenceExpression, moduleNotFoundError, isForAugmentation) {
37477             if (isForAugmentation === void 0) { isForAugmentation = false; }
37478             return ts.isStringLiteralLike(moduleReferenceExpression)
37479                 ? resolveExternalModule(location, moduleReferenceExpression.text, moduleNotFoundError, moduleReferenceExpression, isForAugmentation)
37480                 : undefined;
37481         }
37482         function resolveExternalModule(location, moduleReference, moduleNotFoundError, errorNode, isForAugmentation) {
37483             if (isForAugmentation === void 0) { isForAugmentation = false; }
37484             if (ts.startsWith(moduleReference, "@types/")) {
37485                 var diag = ts.Diagnostics.Cannot_import_type_declaration_files_Consider_importing_0_instead_of_1;
37486                 var withoutAtTypePrefix = ts.removePrefix(moduleReference, "@types/");
37487                 error(errorNode, diag, withoutAtTypePrefix, moduleReference);
37488             }
37489             var ambientModule = tryFindAmbientModule(moduleReference, /*withAugmentations*/ true);
37490             if (ambientModule) {
37491                 return ambientModule;
37492             }
37493             var currentSourceFile = ts.getSourceFileOfNode(location);
37494             var resolvedModule = ts.getResolvedModule(currentSourceFile, moduleReference); // TODO: GH#18217
37495             var resolutionDiagnostic = resolvedModule && ts.getResolutionDiagnostic(compilerOptions, resolvedModule);
37496             var sourceFile = resolvedModule && !resolutionDiagnostic && host.getSourceFile(resolvedModule.resolvedFileName);
37497             if (sourceFile) {
37498                 if (sourceFile.symbol) {
37499                     if (resolvedModule.isExternalLibraryImport && !ts.resolutionExtensionIsTSOrJson(resolvedModule.extension)) {
37500                         errorOnImplicitAnyModule(/*isError*/ false, errorNode, resolvedModule, moduleReference);
37501                     }
37502                     // merged symbol is module declaration symbol combined with all augmentations
37503                     return getMergedSymbol(sourceFile.symbol);
37504                 }
37505                 if (moduleNotFoundError) {
37506                     // report errors only if it was requested
37507                     error(errorNode, ts.Diagnostics.File_0_is_not_a_module, sourceFile.fileName);
37508                 }
37509                 return undefined;
37510             }
37511             if (patternAmbientModules) {
37512                 var pattern = ts.findBestPatternMatch(patternAmbientModules, function (_) { return _.pattern; }, moduleReference);
37513                 if (pattern) {
37514                     // If the module reference matched a pattern ambient module ('*.foo') but there's also a
37515                     // module augmentation by the specific name requested ('a.foo'), we store the merged symbol
37516                     // by the augmentation name ('a.foo'), because asking for *.foo should not give you exports
37517                     // from a.foo.
37518                     var augmentation = patternAmbientModuleAugmentations && patternAmbientModuleAugmentations.get(moduleReference);
37519                     if (augmentation) {
37520                         return getMergedSymbol(augmentation);
37521                     }
37522                     return getMergedSymbol(pattern.symbol);
37523                 }
37524             }
37525             // May be an untyped module. If so, ignore resolutionDiagnostic.
37526             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) {
37527                 if (isForAugmentation) {
37528                     var diag = ts.Diagnostics.Invalid_module_name_in_augmentation_Module_0_resolves_to_an_untyped_module_at_1_which_cannot_be_augmented;
37529                     error(errorNode, diag, moduleReference, resolvedModule.resolvedFileName);
37530                 }
37531                 else {
37532                     errorOnImplicitAnyModule(/*isError*/ noImplicitAny && !!moduleNotFoundError, errorNode, resolvedModule, moduleReference);
37533                 }
37534                 // Failed imports and untyped modules are both treated in an untyped manner; only difference is whether we give a diagnostic first.
37535                 return undefined;
37536             }
37537             if (moduleNotFoundError) {
37538                 // See if this was possibly a projectReference redirect
37539                 if (resolvedModule) {
37540                     var redirect = host.getProjectReferenceRedirect(resolvedModule.resolvedFileName);
37541                     if (redirect) {
37542                         error(errorNode, ts.Diagnostics.Output_file_0_has_not_been_built_from_source_file_1, redirect, resolvedModule.resolvedFileName);
37543                         return undefined;
37544                     }
37545                 }
37546                 if (resolutionDiagnostic) {
37547                     error(errorNode, resolutionDiagnostic, moduleReference, resolvedModule.resolvedFileName);
37548                 }
37549                 else {
37550                     var tsExtension = ts.tryExtractTSExtension(moduleReference);
37551                     if (tsExtension) {
37552                         var diag = ts.Diagnostics.An_import_path_cannot_end_with_a_0_extension_Consider_importing_1_instead;
37553                         error(errorNode, diag, tsExtension, ts.removeExtension(moduleReference, tsExtension));
37554                     }
37555                     else if (!compilerOptions.resolveJsonModule &&
37556                         ts.fileExtensionIs(moduleReference, ".json" /* Json */) &&
37557                         ts.getEmitModuleResolutionKind(compilerOptions) === ts.ModuleResolutionKind.NodeJs &&
37558                         ts.hasJsonModuleEmitEnabled(compilerOptions)) {
37559                         error(errorNode, ts.Diagnostics.Cannot_find_module_0_Consider_using_resolveJsonModule_to_import_module_with_json_extension, moduleReference);
37560                     }
37561                     else {
37562                         error(errorNode, moduleNotFoundError, moduleReference);
37563                     }
37564                 }
37565             }
37566             return undefined;
37567         }
37568         function errorOnImplicitAnyModule(isError, errorNode, _a, moduleReference) {
37569             var packageId = _a.packageId, resolvedFileName = _a.resolvedFileName;
37570             var errorInfo = !ts.isExternalModuleNameRelative(moduleReference) && packageId
37571                 ? typesPackageExists(packageId.name)
37572                     ? ts.chainDiagnosticMessages(
37573                     /*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))
37574                     : ts.chainDiagnosticMessages(
37575                     /*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))
37576                 : undefined;
37577             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));
37578         }
37579         function typesPackageExists(packageName) {
37580             return getPackagesSet().has(ts.getTypesPackageName(packageName));
37581         }
37582         function resolveExternalModuleSymbol(moduleSymbol, dontResolveAlias) {
37583             if (moduleSymbol === null || moduleSymbol === void 0 ? void 0 : moduleSymbol.exports) {
37584                 var exportEquals = resolveSymbol(moduleSymbol.exports.get("export=" /* ExportEquals */), dontResolveAlias);
37585                 var exported = getCommonJsExportEquals(getMergedSymbol(exportEquals), getMergedSymbol(moduleSymbol));
37586                 return getMergedSymbol(exported) || moduleSymbol;
37587             }
37588             return undefined;
37589         }
37590         function getCommonJsExportEquals(exported, moduleSymbol) {
37591             if (!exported || exported === unknownSymbol || exported === moduleSymbol || moduleSymbol.exports.size === 1 || exported.flags & 2097152 /* Alias */) {
37592                 return exported;
37593             }
37594             var links = getSymbolLinks(exported);
37595             if (links.cjsExportMerged) {
37596                 return links.cjsExportMerged;
37597             }
37598             var merged = exported.flags & 33554432 /* Transient */ ? exported : cloneSymbol(exported);
37599             merged.flags = merged.flags | 512 /* ValueModule */;
37600             if (merged.exports === undefined) {
37601                 merged.exports = ts.createSymbolTable();
37602             }
37603             moduleSymbol.exports.forEach(function (s, name) {
37604                 if (name === "export=" /* ExportEquals */)
37605                     return;
37606                 merged.exports.set(name, merged.exports.has(name) ? mergeSymbol(merged.exports.get(name), s) : s);
37607             });
37608             getSymbolLinks(merged).cjsExportMerged = merged;
37609             return links.cjsExportMerged = merged;
37610         }
37611         // An external module with an 'export =' declaration may be referenced as an ES6 module provided the 'export ='
37612         // references a symbol that is at least declared as a module or a variable. The target of the 'export =' may
37613         // combine other declarations with the module or variable (e.g. a class/module, function/module, interface/variable).
37614         function resolveESModuleSymbol(moduleSymbol, referencingLocation, dontResolveAlias, suppressInteropError) {
37615             var symbol = resolveExternalModuleSymbol(moduleSymbol, dontResolveAlias);
37616             if (!dontResolveAlias && symbol) {
37617                 if (!suppressInteropError && !(symbol.flags & (1536 /* Module */ | 3 /* Variable */)) && !ts.getDeclarationOfKind(symbol, 290 /* SourceFile */)) {
37618                     var compilerOptionName = moduleKind >= ts.ModuleKind.ES2015
37619                         ? "allowSyntheticDefaultImports"
37620                         : "esModuleInterop";
37621                     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);
37622                     return symbol;
37623                 }
37624                 if (compilerOptions.esModuleInterop) {
37625                     var referenceParent = referencingLocation.parent;
37626                     if ((ts.isImportDeclaration(referenceParent) && ts.getNamespaceDeclarationNode(referenceParent)) ||
37627                         ts.isImportCall(referenceParent)) {
37628                         var type = getTypeOfSymbol(symbol);
37629                         var sigs = getSignaturesOfStructuredType(type, 0 /* Call */);
37630                         if (!sigs || !sigs.length) {
37631                             sigs = getSignaturesOfStructuredType(type, 1 /* Construct */);
37632                         }
37633                         if (sigs && sigs.length) {
37634                             var moduleType = getTypeWithSyntheticDefaultImportType(type, symbol, moduleSymbol);
37635                             // Create a new symbol which has the module's type less the call and construct signatures
37636                             var result = createSymbol(symbol.flags, symbol.escapedName);
37637                             result.declarations = symbol.declarations ? symbol.declarations.slice() : [];
37638                             result.parent = symbol.parent;
37639                             result.target = symbol;
37640                             result.originatingImport = referenceParent;
37641                             if (symbol.valueDeclaration)
37642                                 result.valueDeclaration = symbol.valueDeclaration;
37643                             if (symbol.constEnumOnlyModule)
37644                                 result.constEnumOnlyModule = true;
37645                             if (symbol.members)
37646                                 result.members = ts.cloneMap(symbol.members);
37647                             if (symbol.exports)
37648                                 result.exports = ts.cloneMap(symbol.exports);
37649                             var resolvedModuleType = resolveStructuredTypeMembers(moduleType); // Should already be resolved from the signature checks above
37650                             result.type = createAnonymousType(result, resolvedModuleType.members, ts.emptyArray, ts.emptyArray, resolvedModuleType.stringIndexInfo, resolvedModuleType.numberIndexInfo);
37651                             return result;
37652                         }
37653                     }
37654                 }
37655             }
37656             return symbol;
37657         }
37658         function hasExportAssignmentSymbol(moduleSymbol) {
37659             return moduleSymbol.exports.get("export=" /* ExportEquals */) !== undefined;
37660         }
37661         function getExportsOfModuleAsArray(moduleSymbol) {
37662             return symbolsToArray(getExportsOfModule(moduleSymbol));
37663         }
37664         function getExportsAndPropertiesOfModule(moduleSymbol) {
37665             var exports = getExportsOfModuleAsArray(moduleSymbol);
37666             var exportEquals = resolveExternalModuleSymbol(moduleSymbol);
37667             if (exportEquals !== moduleSymbol) {
37668                 ts.addRange(exports, getPropertiesOfType(getTypeOfSymbol(exportEquals)));
37669             }
37670             return exports;
37671         }
37672         function tryGetMemberInModuleExports(memberName, moduleSymbol) {
37673             var symbolTable = getExportsOfModule(moduleSymbol);
37674             if (symbolTable) {
37675                 return symbolTable.get(memberName);
37676             }
37677         }
37678         function tryGetMemberInModuleExportsAndProperties(memberName, moduleSymbol) {
37679             var symbol = tryGetMemberInModuleExports(memberName, moduleSymbol);
37680             if (symbol) {
37681                 return symbol;
37682             }
37683             var exportEquals = resolveExternalModuleSymbol(moduleSymbol);
37684             if (exportEquals === moduleSymbol) {
37685                 return undefined;
37686             }
37687             var type = getTypeOfSymbol(exportEquals);
37688             return type.flags & 131068 /* Primitive */ ||
37689                 ts.getObjectFlags(type) & 1 /* Class */ ||
37690                 isArrayOrTupleLikeType(type)
37691                 ? undefined
37692                 : getPropertyOfType(type, memberName);
37693         }
37694         function getExportsOfSymbol(symbol) {
37695             return symbol.flags & 6256 /* LateBindingContainer */ ? getResolvedMembersOrExportsOfSymbol(symbol, "resolvedExports" /* resolvedExports */) :
37696                 symbol.flags & 1536 /* Module */ ? getExportsOfModule(symbol) :
37697                     symbol.exports || emptySymbols;
37698         }
37699         function getExportsOfModule(moduleSymbol) {
37700             var links = getSymbolLinks(moduleSymbol);
37701             return links.resolvedExports || (links.resolvedExports = getExportsOfModuleWorker(moduleSymbol));
37702         }
37703         /**
37704          * Extends one symbol table with another while collecting information on name collisions for error message generation into the `lookupTable` argument
37705          * Not passing `lookupTable` and `exportNode` disables this collection, and just extends the tables
37706          */
37707         function extendExportSymbols(target, source, lookupTable, exportNode) {
37708             if (!source)
37709                 return;
37710             source.forEach(function (sourceSymbol, id) {
37711                 if (id === "default" /* Default */)
37712                     return;
37713                 var targetSymbol = target.get(id);
37714                 if (!targetSymbol) {
37715                     target.set(id, sourceSymbol);
37716                     if (lookupTable && exportNode) {
37717                         lookupTable.set(id, {
37718                             specifierText: ts.getTextOfNode(exportNode.moduleSpecifier)
37719                         });
37720                     }
37721                 }
37722                 else if (lookupTable && exportNode && targetSymbol && resolveSymbol(targetSymbol) !== resolveSymbol(sourceSymbol)) {
37723                     var collisionTracker = lookupTable.get(id);
37724                     if (!collisionTracker.exportsWithDuplicate) {
37725                         collisionTracker.exportsWithDuplicate = [exportNode];
37726                     }
37727                     else {
37728                         collisionTracker.exportsWithDuplicate.push(exportNode);
37729                     }
37730                 }
37731             });
37732         }
37733         function getExportsOfModuleWorker(moduleSymbol) {
37734             var visitedSymbols = [];
37735             // A module defined by an 'export=' consists of one export that needs to be resolved
37736             moduleSymbol = resolveExternalModuleSymbol(moduleSymbol);
37737             return visit(moduleSymbol) || emptySymbols;
37738             // The ES6 spec permits export * declarations in a module to circularly reference the module itself. For example,
37739             // module 'a' can 'export * from "b"' and 'b' can 'export * from "a"' without error.
37740             function visit(symbol) {
37741                 if (!(symbol && symbol.exports && ts.pushIfUnique(visitedSymbols, symbol))) {
37742                     return;
37743                 }
37744                 var symbols = ts.cloneMap(symbol.exports);
37745                 // All export * declarations are collected in an __export symbol by the binder
37746                 var exportStars = symbol.exports.get("__export" /* ExportStar */);
37747                 if (exportStars) {
37748                     var nestedSymbols = ts.createSymbolTable();
37749                     var lookupTable_1 = ts.createMap();
37750                     for (var _i = 0, _a = exportStars.declarations; _i < _a.length; _i++) {
37751                         var node = _a[_i];
37752                         var resolvedModule = resolveExternalModuleName(node, node.moduleSpecifier);
37753                         var exportedSymbols = visit(resolvedModule);
37754                         extendExportSymbols(nestedSymbols, exportedSymbols, lookupTable_1, node);
37755                     }
37756                     lookupTable_1.forEach(function (_a, id) {
37757                         var exportsWithDuplicate = _a.exportsWithDuplicate;
37758                         // It's not an error if the file with multiple `export *`s with duplicate names exports a member with that name itself
37759                         if (id === "export=" || !(exportsWithDuplicate && exportsWithDuplicate.length) || symbols.has(id)) {
37760                             return;
37761                         }
37762                         for (var _i = 0, exportsWithDuplicate_1 = exportsWithDuplicate; _i < exportsWithDuplicate_1.length; _i++) {
37763                             var node = exportsWithDuplicate_1[_i];
37764                             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)));
37765                         }
37766                     });
37767                     extendExportSymbols(symbols, nestedSymbols);
37768                 }
37769                 return symbols;
37770             }
37771         }
37772         function getMergedSymbol(symbol) {
37773             var merged;
37774             return symbol && symbol.mergeId && (merged = mergedSymbols[symbol.mergeId]) ? merged : symbol;
37775         }
37776         function getSymbolOfNode(node) {
37777             return getMergedSymbol(node.symbol && getLateBoundSymbol(node.symbol));
37778         }
37779         function getParentOfSymbol(symbol) {
37780             return getMergedSymbol(symbol.parent && getLateBoundSymbol(symbol.parent));
37781         }
37782         function getAlternativeContainingModules(symbol, enclosingDeclaration) {
37783             var containingFile = ts.getSourceFileOfNode(enclosingDeclaration);
37784             var id = "" + getNodeId(containingFile);
37785             var links = getSymbolLinks(symbol);
37786             var results;
37787             if (links.extendedContainersByFile && (results = links.extendedContainersByFile.get(id))) {
37788                 return results;
37789             }
37790             if (containingFile && containingFile.imports) {
37791                 // Try to make an import using an import already in the enclosing file, if possible
37792                 for (var _i = 0, _a = containingFile.imports; _i < _a.length; _i++) {
37793                     var importRef = _a[_i];
37794                     if (ts.nodeIsSynthesized(importRef))
37795                         continue; // Synthetic names can't be resolved by `resolveExternalModuleName` - they'll cause a debug assert if they error
37796                     var resolvedModule = resolveExternalModuleName(enclosingDeclaration, importRef, /*ignoreErrors*/ true);
37797                     if (!resolvedModule)
37798                         continue;
37799                     var ref = getAliasForSymbolInContainer(resolvedModule, symbol);
37800                     if (!ref)
37801                         continue;
37802                     results = ts.append(results, resolvedModule);
37803                 }
37804                 if (ts.length(results)) {
37805                     (links.extendedContainersByFile || (links.extendedContainersByFile = ts.createMap())).set(id, results);
37806                     return results;
37807                 }
37808             }
37809             if (links.extendedContainers) {
37810                 return links.extendedContainers;
37811             }
37812             // No results from files already being imported by this file - expand search (expensive, but not location-specific, so cached)
37813             var otherFiles = host.getSourceFiles();
37814             for (var _b = 0, otherFiles_1 = otherFiles; _b < otherFiles_1.length; _b++) {
37815                 var file = otherFiles_1[_b];
37816                 if (!ts.isExternalModule(file))
37817                     continue;
37818                 var sym = getSymbolOfNode(file);
37819                 var ref = getAliasForSymbolInContainer(sym, symbol);
37820                 if (!ref)
37821                     continue;
37822                 results = ts.append(results, sym);
37823             }
37824             return links.extendedContainers = results || ts.emptyArray;
37825         }
37826         /**
37827          * Attempts to find the symbol corresponding to the container a symbol is in - usually this
37828          * is just its' `.parent`, but for locals, this value is `undefined`
37829          */
37830         function getContainersOfSymbol(symbol, enclosingDeclaration) {
37831             var container = getParentOfSymbol(symbol);
37832             // Type parameters end up in the `members` lists but are not externally visible
37833             if (container && !(symbol.flags & 262144 /* TypeParameter */)) {
37834                 var additionalContainers = ts.mapDefined(container.declarations, fileSymbolIfFileSymbolExportEqualsContainer);
37835                 var reexportContainers = enclosingDeclaration && getAlternativeContainingModules(symbol, enclosingDeclaration);
37836                 if (enclosingDeclaration && getAccessibleSymbolChain(container, enclosingDeclaration, 1920 /* Namespace */, /*externalOnly*/ false)) {
37837                     return ts.concatenate(ts.concatenate([container], additionalContainers), reexportContainers); // This order expresses a preference for the real container if it is in scope
37838                 }
37839                 var res = ts.append(additionalContainers, container);
37840                 return ts.concatenate(res, reexportContainers);
37841             }
37842             var candidates = ts.mapDefined(symbol.declarations, function (d) {
37843                 if (!ts.isAmbientModule(d) && d.parent && hasNonGlobalAugmentationExternalModuleSymbol(d.parent)) {
37844                     return getSymbolOfNode(d.parent);
37845                 }
37846                 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)) {
37847                     if (ts.isModuleExportsAccessExpression(d.parent.left) || ts.isExportsIdentifier(d.parent.left.expression)) {
37848                         return getSymbolOfNode(ts.getSourceFileOfNode(d));
37849                     }
37850                     checkExpressionCached(d.parent.left.expression);
37851                     return getNodeLinks(d.parent.left.expression).resolvedSymbol;
37852                 }
37853             });
37854             if (!ts.length(candidates)) {
37855                 return undefined;
37856             }
37857             return ts.mapDefined(candidates, function (candidate) { return getAliasForSymbolInContainer(candidate, symbol) ? candidate : undefined; });
37858             function fileSymbolIfFileSymbolExportEqualsContainer(d) {
37859                 return container && getFileSymbolIfFileSymbolExportEqualsContainer(d, container);
37860             }
37861         }
37862         function getFileSymbolIfFileSymbolExportEqualsContainer(d, container) {
37863             var fileSymbol = getExternalModuleContainer(d);
37864             var exported = fileSymbol && fileSymbol.exports && fileSymbol.exports.get("export=" /* ExportEquals */);
37865             return exported && getSymbolIfSameReference(exported, container) ? fileSymbol : undefined;
37866         }
37867         function getAliasForSymbolInContainer(container, symbol) {
37868             if (container === getParentOfSymbol(symbol)) {
37869                 // fast path, `symbol` is either already the alias or isn't aliased
37870                 return symbol;
37871             }
37872             // Check if container is a thing with an `export=` which points directly at `symbol`, and if so, return
37873             // the container itself as the alias for the symbol
37874             var exportEquals = container.exports && container.exports.get("export=" /* ExportEquals */);
37875             if (exportEquals && getSymbolIfSameReference(exportEquals, symbol)) {
37876                 return container;
37877             }
37878             var exports = getExportsOfSymbol(container);
37879             var quick = exports.get(symbol.escapedName);
37880             if (quick && getSymbolIfSameReference(quick, symbol)) {
37881                 return quick;
37882             }
37883             return ts.forEachEntry(exports, function (exported) {
37884                 if (getSymbolIfSameReference(exported, symbol)) {
37885                     return exported;
37886                 }
37887             });
37888         }
37889         /**
37890          * Checks if two symbols, through aliasing and/or merging, refer to the same thing
37891          */
37892         function getSymbolIfSameReference(s1, s2) {
37893             if (getMergedSymbol(resolveSymbol(getMergedSymbol(s1))) === getMergedSymbol(resolveSymbol(getMergedSymbol(s2)))) {
37894                 return s1;
37895             }
37896         }
37897         function getExportSymbolOfValueSymbolIfExported(symbol) {
37898             return getMergedSymbol(symbol && (symbol.flags & 1048576 /* ExportValue */) !== 0 ? symbol.exportSymbol : symbol);
37899         }
37900         function symbolIsValue(symbol) {
37901             return !!(symbol.flags & 111551 /* Value */ || symbol.flags & 2097152 /* Alias */ && resolveAlias(symbol).flags & 111551 /* Value */ && !getTypeOnlyAliasDeclaration(symbol));
37902         }
37903         function findConstructorDeclaration(node) {
37904             var members = node.members;
37905             for (var _i = 0, members_3 = members; _i < members_3.length; _i++) {
37906                 var member = members_3[_i];
37907                 if (member.kind === 162 /* Constructor */ && ts.nodeIsPresent(member.body)) {
37908                     return member;
37909                 }
37910             }
37911         }
37912         function createType(flags) {
37913             var result = new Type(checker, flags);
37914             typeCount++;
37915             result.id = typeCount;
37916             return result;
37917         }
37918         function createIntrinsicType(kind, intrinsicName, objectFlags) {
37919             if (objectFlags === void 0) { objectFlags = 0; }
37920             var type = createType(kind);
37921             type.intrinsicName = intrinsicName;
37922             type.objectFlags = objectFlags;
37923             return type;
37924         }
37925         function createBooleanType(trueFalseTypes) {
37926             var type = getUnionType(trueFalseTypes);
37927             type.flags |= 16 /* Boolean */;
37928             type.intrinsicName = "boolean";
37929             return type;
37930         }
37931         function createObjectType(objectFlags, symbol) {
37932             var type = createType(524288 /* Object */);
37933             type.objectFlags = objectFlags;
37934             type.symbol = symbol;
37935             type.members = undefined;
37936             type.properties = undefined;
37937             type.callSignatures = undefined;
37938             type.constructSignatures = undefined;
37939             type.stringIndexInfo = undefined;
37940             type.numberIndexInfo = undefined;
37941             return type;
37942         }
37943         function createTypeofType() {
37944             return getUnionType(ts.arrayFrom(typeofEQFacts.keys(), getLiteralType));
37945         }
37946         function createTypeParameter(symbol) {
37947             var type = createType(262144 /* TypeParameter */);
37948             if (symbol)
37949                 type.symbol = symbol;
37950             return type;
37951         }
37952         // A reserved member name starts with two underscores, but the third character cannot be an underscore,
37953         // @, or #. A third underscore indicates an escaped form of an identifier that started
37954         // with at least two underscores. The @ character indicates that the name is denoted by a well known ES
37955         // Symbol instance and the # character indicates that the name is a PrivateIdentifier.
37956         function isReservedMemberName(name) {
37957             return name.charCodeAt(0) === 95 /* _ */ &&
37958                 name.charCodeAt(1) === 95 /* _ */ &&
37959                 name.charCodeAt(2) !== 95 /* _ */ &&
37960                 name.charCodeAt(2) !== 64 /* at */ &&
37961                 name.charCodeAt(2) !== 35 /* hash */;
37962         }
37963         function getNamedMembers(members) {
37964             var result;
37965             members.forEach(function (symbol, id) {
37966                 if (!isReservedMemberName(id) && symbolIsValue(symbol)) {
37967                     (result || (result = [])).push(symbol);
37968                 }
37969             });
37970             return result || ts.emptyArray;
37971         }
37972         function setStructuredTypeMembers(type, members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo) {
37973             type.members = members;
37974             type.properties = members === emptySymbols ? ts.emptyArray : getNamedMembers(members);
37975             type.callSignatures = callSignatures;
37976             type.constructSignatures = constructSignatures;
37977             type.stringIndexInfo = stringIndexInfo;
37978             type.numberIndexInfo = numberIndexInfo;
37979             return type;
37980         }
37981         function createAnonymousType(symbol, members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo) {
37982             return setStructuredTypeMembers(createObjectType(16 /* Anonymous */, symbol), members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo);
37983         }
37984         function forEachSymbolTableInScope(enclosingDeclaration, callback) {
37985             var result;
37986             var _loop_7 = function (location) {
37987                 // Locals of a source file are not in scope (because they get merged into the global symbol table)
37988                 if (location.locals && !isGlobalSourceFile(location)) {
37989                     if (result = callback(location.locals)) {
37990                         return { value: result };
37991                     }
37992                 }
37993                 switch (location.kind) {
37994                     case 290 /* SourceFile */:
37995                         if (!ts.isExternalOrCommonJsModule(location)) {
37996                             break;
37997                         }
37998                     // falls through
37999                     case 249 /* ModuleDeclaration */:
38000                         var sym = getSymbolOfNode(location);
38001                         // `sym` may not have exports if this module declaration is backed by the symbol for a `const` that's being rewritten
38002                         // into a namespace - in such cases, it's best to just let the namespace appear empty (the const members couldn't have referred
38003                         // to one another anyway)
38004                         if (result = callback((sym === null || sym === void 0 ? void 0 : sym.exports) || emptySymbols)) {
38005                             return { value: result };
38006                         }
38007                         break;
38008                     case 245 /* ClassDeclaration */:
38009                     case 214 /* ClassExpression */:
38010                     case 246 /* InterfaceDeclaration */:
38011                         // Type parameters are bound into `members` lists so they can merge across declarations
38012                         // This is troublesome, since in all other respects, they behave like locals :cries:
38013                         // TODO: the below is shared with similar code in `resolveName` - in fact, rephrasing all this symbol
38014                         // lookup logic in terms of `resolveName` would be nice
38015                         // The below is used to lookup type parameters within a class or interface, as they are added to the class/interface locals
38016                         // These can never be latebound, so the symbol's raw members are sufficient. `getMembersOfNode` cannot be used, as it would
38017                         // trigger resolving late-bound names, which we may already be in the process of doing while we're here!
38018                         var table_1;
38019                         // TODO: Should this filtered table be cached in some way?
38020                         (getSymbolOfNode(location).members || emptySymbols).forEach(function (memberSymbol, key) {
38021                             if (memberSymbol.flags & (788968 /* Type */ & ~67108864 /* Assignment */)) {
38022                                 (table_1 || (table_1 = ts.createSymbolTable())).set(key, memberSymbol);
38023                             }
38024                         });
38025                         if (table_1 && (result = callback(table_1))) {
38026                             return { value: result };
38027                         }
38028                         break;
38029                 }
38030             };
38031             for (var location = enclosingDeclaration; location; location = location.parent) {
38032                 var state_2 = _loop_7(location);
38033                 if (typeof state_2 === "object")
38034                     return state_2.value;
38035             }
38036             return callback(globals);
38037         }
38038         function getQualifiedLeftMeaning(rightMeaning) {
38039             // If we are looking in value space, the parent meaning is value, other wise it is namespace
38040             return rightMeaning === 111551 /* Value */ ? 111551 /* Value */ : 1920 /* Namespace */;
38041         }
38042         function getAccessibleSymbolChain(symbol, enclosingDeclaration, meaning, useOnlyExternalAliasing, visitedSymbolTablesMap) {
38043             if (visitedSymbolTablesMap === void 0) { visitedSymbolTablesMap = ts.createMap(); }
38044             if (!(symbol && !isPropertyOrMethodDeclarationSymbol(symbol))) {
38045                 return undefined;
38046             }
38047             var id = "" + getSymbolId(symbol);
38048             var visitedSymbolTables = visitedSymbolTablesMap.get(id);
38049             if (!visitedSymbolTables) {
38050                 visitedSymbolTablesMap.set(id, visitedSymbolTables = []);
38051             }
38052             return forEachSymbolTableInScope(enclosingDeclaration, getAccessibleSymbolChainFromSymbolTable);
38053             /**
38054              * @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)
38055              */
38056             function getAccessibleSymbolChainFromSymbolTable(symbols, ignoreQualification) {
38057                 if (!ts.pushIfUnique(visitedSymbolTables, symbols)) {
38058                     return undefined;
38059                 }
38060                 var result = trySymbolTable(symbols, ignoreQualification);
38061                 visitedSymbolTables.pop();
38062                 return result;
38063             }
38064             function canQualifySymbol(symbolFromSymbolTable, meaning) {
38065                 // If the symbol is equivalent and doesn't need further qualification, this symbol is accessible
38066                 return !needsQualification(symbolFromSymbolTable, enclosingDeclaration, meaning) ||
38067                     // If symbol needs qualification, make sure that parent is accessible, if it is then this symbol is accessible too
38068                     !!getAccessibleSymbolChain(symbolFromSymbolTable.parent, enclosingDeclaration, getQualifiedLeftMeaning(meaning), useOnlyExternalAliasing, visitedSymbolTablesMap);
38069             }
38070             function isAccessible(symbolFromSymbolTable, resolvedAliasSymbol, ignoreQualification) {
38071                 return (symbol === (resolvedAliasSymbol || symbolFromSymbolTable) || getMergedSymbol(symbol) === getMergedSymbol(resolvedAliasSymbol || symbolFromSymbolTable)) &&
38072                     // if the symbolFromSymbolTable is not external module (it could be if it was determined as ambient external module and would be in globals table)
38073                     // and if symbolFromSymbolTable or alias resolution matches the symbol,
38074                     // check the symbol can be qualified, it is only then this symbol is accessible
38075                     !ts.some(symbolFromSymbolTable.declarations, hasNonGlobalAugmentationExternalModuleSymbol) &&
38076                     (ignoreQualification || canQualifySymbol(getMergedSymbol(symbolFromSymbolTable), meaning));
38077             }
38078             function trySymbolTable(symbols, ignoreQualification) {
38079                 // If symbol is directly available by its name in the symbol table
38080                 if (isAccessible(symbols.get(symbol.escapedName), /*resolvedAliasSymbol*/ undefined, ignoreQualification)) {
38081                     return [symbol];
38082                 }
38083                 // Check if symbol is any of the aliases in scope
38084                 var result = ts.forEachEntry(symbols, function (symbolFromSymbolTable) {
38085                     if (symbolFromSymbolTable.flags & 2097152 /* Alias */
38086                         && symbolFromSymbolTable.escapedName !== "export=" /* ExportEquals */
38087                         && symbolFromSymbolTable.escapedName !== "default" /* Default */
38088                         && !(ts.isUMDExportSymbol(symbolFromSymbolTable) && enclosingDeclaration && ts.isExternalModule(ts.getSourceFileOfNode(enclosingDeclaration)))
38089                         // If `!useOnlyExternalAliasing`, we can use any type of alias to get the name
38090                         && (!useOnlyExternalAliasing || ts.some(symbolFromSymbolTable.declarations, ts.isExternalModuleImportEqualsDeclaration))
38091                         // While exports are generally considered to be in scope, export-specifier declared symbols are _not_
38092                         // See similar comment in `resolveName` for details
38093                         && (ignoreQualification || !ts.getDeclarationOfKind(symbolFromSymbolTable, 263 /* ExportSpecifier */))) {
38094                         var resolvedImportedSymbol = resolveAlias(symbolFromSymbolTable);
38095                         var candidate = getCandidateListForSymbol(symbolFromSymbolTable, resolvedImportedSymbol, ignoreQualification);
38096                         if (candidate) {
38097                             return candidate;
38098                         }
38099                     }
38100                     if (symbolFromSymbolTable.escapedName === symbol.escapedName && symbolFromSymbolTable.exportSymbol) {
38101                         if (isAccessible(getMergedSymbol(symbolFromSymbolTable.exportSymbol), /*aliasSymbol*/ undefined, ignoreQualification)) {
38102                             return [symbol];
38103                         }
38104                     }
38105                 });
38106                 // 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
38107                 return result || (symbols === globals ? getCandidateListForSymbol(globalThisSymbol, globalThisSymbol, ignoreQualification) : undefined);
38108             }
38109             function getCandidateListForSymbol(symbolFromSymbolTable, resolvedImportedSymbol, ignoreQualification) {
38110                 if (isAccessible(symbolFromSymbolTable, resolvedImportedSymbol, ignoreQualification)) {
38111                     return [symbolFromSymbolTable];
38112                 }
38113                 // Look in the exported members, if we can find accessibleSymbolChain, symbol is accessible using this chain
38114                 // but only if the symbolFromSymbolTable can be qualified
38115                 var candidateTable = getExportsOfSymbol(resolvedImportedSymbol);
38116                 var accessibleSymbolsFromExports = candidateTable && getAccessibleSymbolChainFromSymbolTable(candidateTable, /*ignoreQualification*/ true);
38117                 if (accessibleSymbolsFromExports && canQualifySymbol(symbolFromSymbolTable, getQualifiedLeftMeaning(meaning))) {
38118                     return [symbolFromSymbolTable].concat(accessibleSymbolsFromExports);
38119                 }
38120             }
38121         }
38122         function needsQualification(symbol, enclosingDeclaration, meaning) {
38123             var qualify = false;
38124             forEachSymbolTableInScope(enclosingDeclaration, function (symbolTable) {
38125                 // If symbol of this name is not available in the symbol table we are ok
38126                 var symbolFromSymbolTable = getMergedSymbol(symbolTable.get(symbol.escapedName));
38127                 if (!symbolFromSymbolTable) {
38128                     // Continue to the next symbol table
38129                     return false;
38130                 }
38131                 // If the symbol with this name is present it should refer to the symbol
38132                 if (symbolFromSymbolTable === symbol) {
38133                     // No need to qualify
38134                     return true;
38135                 }
38136                 // Qualify if the symbol from symbol table has same meaning as expected
38137                 symbolFromSymbolTable = (symbolFromSymbolTable.flags & 2097152 /* Alias */ && !ts.getDeclarationOfKind(symbolFromSymbolTable, 263 /* ExportSpecifier */)) ? resolveAlias(symbolFromSymbolTable) : symbolFromSymbolTable;
38138                 if (symbolFromSymbolTable.flags & meaning) {
38139                     qualify = true;
38140                     return true;
38141                 }
38142                 // Continue to the next symbol table
38143                 return false;
38144             });
38145             return qualify;
38146         }
38147         function isPropertyOrMethodDeclarationSymbol(symbol) {
38148             if (symbol.declarations && symbol.declarations.length) {
38149                 for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) {
38150                     var declaration = _a[_i];
38151                     switch (declaration.kind) {
38152                         case 159 /* PropertyDeclaration */:
38153                         case 161 /* MethodDeclaration */:
38154                         case 163 /* GetAccessor */:
38155                         case 164 /* SetAccessor */:
38156                             continue;
38157                         default:
38158                             return false;
38159                     }
38160                 }
38161                 return true;
38162             }
38163             return false;
38164         }
38165         function isTypeSymbolAccessible(typeSymbol, enclosingDeclaration) {
38166             var access = isSymbolAccessible(typeSymbol, enclosingDeclaration, 788968 /* Type */, /*shouldComputeAliasesToMakeVisible*/ false);
38167             return access.accessibility === 0 /* Accessible */;
38168         }
38169         function isValueSymbolAccessible(typeSymbol, enclosingDeclaration) {
38170             var access = isSymbolAccessible(typeSymbol, enclosingDeclaration, 111551 /* Value */, /*shouldComputeAliasesToMakeVisible*/ false);
38171             return access.accessibility === 0 /* Accessible */;
38172         }
38173         function isAnySymbolAccessible(symbols, enclosingDeclaration, initialSymbol, meaning, shouldComputeAliasesToMakeVisible) {
38174             if (!ts.length(symbols))
38175                 return;
38176             var hadAccessibleChain;
38177             var earlyModuleBail = false;
38178             for (var _i = 0, _a = symbols; _i < _a.length; _i++) {
38179                 var symbol = _a[_i];
38180                 // Symbol is accessible if it by itself is accessible
38181                 var accessibleSymbolChain = getAccessibleSymbolChain(symbol, enclosingDeclaration, meaning, /*useOnlyExternalAliasing*/ false);
38182                 if (accessibleSymbolChain) {
38183                     hadAccessibleChain = symbol;
38184                     var hasAccessibleDeclarations = hasVisibleDeclarations(accessibleSymbolChain[0], shouldComputeAliasesToMakeVisible);
38185                     if (hasAccessibleDeclarations) {
38186                         return hasAccessibleDeclarations;
38187                     }
38188                 }
38189                 else {
38190                     if (ts.some(symbol.declarations, hasNonGlobalAugmentationExternalModuleSymbol)) {
38191                         if (shouldComputeAliasesToMakeVisible) {
38192                             earlyModuleBail = true;
38193                             // Generally speaking, we want to use the aliases that already exist to refer to a module, if present
38194                             // In order to do so, we need to find those aliases in order to retain them in declaration emit; so
38195                             // if we are in declaration emit, we cannot use the fast path for module visibility until we've exhausted
38196                             // all other visibility options (in order to capture the possible aliases used to reference the module)
38197                             continue;
38198                         }
38199                         // Any meaning of a module symbol is always accessible via an `import` type
38200                         return {
38201                             accessibility: 0 /* Accessible */
38202                         };
38203                     }
38204                 }
38205                 // If we haven't got the accessible symbol, it doesn't mean the symbol is actually inaccessible.
38206                 // It could be a qualified symbol and hence verify the path
38207                 // e.g.:
38208                 // module m {
38209                 //     export class c {
38210                 //     }
38211                 // }
38212                 // const x: typeof m.c
38213                 // In the above example when we start with checking if typeof m.c symbol is accessible,
38214                 // we are going to see if c can be accessed in scope directly.
38215                 // But it can't, hence the accessible is going to be undefined, but that doesn't mean m.c is inaccessible
38216                 // It is accessible if the parent m is accessible because then m.c can be accessed through qualification
38217                 var containers = getContainersOfSymbol(symbol, enclosingDeclaration);
38218                 // If we're trying to reference some object literal in, eg `var a = { x: 1 }`, the symbol for the literal, `__object`, is distinct
38219                 // from the symbol of the declaration it is being assigned to. Since we can use the declaration to refer to the literal, however,
38220                 // we'd like to make that connection here - potentially causing us to paint the declaration's visibility, and therefore the literal.
38221                 var firstDecl = !!ts.length(symbol.declarations) && ts.first(symbol.declarations);
38222                 if (!ts.length(containers) && meaning & 111551 /* Value */ && firstDecl && ts.isObjectLiteralExpression(firstDecl)) {
38223                     if (firstDecl.parent && ts.isVariableDeclaration(firstDecl.parent) && firstDecl === firstDecl.parent.initializer) {
38224                         containers = [getSymbolOfNode(firstDecl.parent)];
38225                     }
38226                 }
38227                 var parentResult = isAnySymbolAccessible(containers, enclosingDeclaration, initialSymbol, initialSymbol === symbol ? getQualifiedLeftMeaning(meaning) : meaning, shouldComputeAliasesToMakeVisible);
38228                 if (parentResult) {
38229                     return parentResult;
38230                 }
38231             }
38232             if (earlyModuleBail) {
38233                 return {
38234                     accessibility: 0 /* Accessible */
38235                 };
38236             }
38237             if (hadAccessibleChain) {
38238                 return {
38239                     accessibility: 1 /* NotAccessible */,
38240                     errorSymbolName: symbolToString(initialSymbol, enclosingDeclaration, meaning),
38241                     errorModuleName: hadAccessibleChain !== initialSymbol ? symbolToString(hadAccessibleChain, enclosingDeclaration, 1920 /* Namespace */) : undefined,
38242                 };
38243             }
38244         }
38245         /**
38246          * Check if the given symbol in given enclosing declaration is accessible and mark all associated alias to be visible if requested
38247          *
38248          * @param symbol a Symbol to check if accessible
38249          * @param enclosingDeclaration a Node containing reference to the symbol
38250          * @param meaning a SymbolFlags to check if such meaning of the symbol is accessible
38251          * @param shouldComputeAliasToMakeVisible a boolean value to indicate whether to return aliases to be mark visible in case the symbol is accessible
38252          */
38253         function isSymbolAccessible(symbol, enclosingDeclaration, meaning, shouldComputeAliasesToMakeVisible) {
38254             if (symbol && enclosingDeclaration) {
38255                 var result = isAnySymbolAccessible([symbol], enclosingDeclaration, symbol, meaning, shouldComputeAliasesToMakeVisible);
38256                 if (result) {
38257                     return result;
38258                 }
38259                 // This could be a symbol that is not exported in the external module
38260                 // or it could be a symbol from different external module that is not aliased and hence cannot be named
38261                 var symbolExternalModule = ts.forEach(symbol.declarations, getExternalModuleContainer);
38262                 if (symbolExternalModule) {
38263                     var enclosingExternalModule = getExternalModuleContainer(enclosingDeclaration);
38264                     if (symbolExternalModule !== enclosingExternalModule) {
38265                         // name from different external module that is not visible
38266                         return {
38267                             accessibility: 2 /* CannotBeNamed */,
38268                             errorSymbolName: symbolToString(symbol, enclosingDeclaration, meaning),
38269                             errorModuleName: symbolToString(symbolExternalModule)
38270                         };
38271                     }
38272                 }
38273                 // Just a local name that is not accessible
38274                 return {
38275                     accessibility: 1 /* NotAccessible */,
38276                     errorSymbolName: symbolToString(symbol, enclosingDeclaration, meaning),
38277                 };
38278             }
38279             return { accessibility: 0 /* Accessible */ };
38280         }
38281         function getExternalModuleContainer(declaration) {
38282             var node = ts.findAncestor(declaration, hasExternalModuleSymbol);
38283             return node && getSymbolOfNode(node);
38284         }
38285         function hasExternalModuleSymbol(declaration) {
38286             return ts.isAmbientModule(declaration) || (declaration.kind === 290 /* SourceFile */ && ts.isExternalOrCommonJsModule(declaration));
38287         }
38288         function hasNonGlobalAugmentationExternalModuleSymbol(declaration) {
38289             return ts.isModuleWithStringLiteralName(declaration) || (declaration.kind === 290 /* SourceFile */ && ts.isExternalOrCommonJsModule(declaration));
38290         }
38291         function hasVisibleDeclarations(symbol, shouldComputeAliasToMakeVisible) {
38292             var aliasesToMakeVisible;
38293             if (!ts.every(ts.filter(symbol.declarations, function (d) { return d.kind !== 75 /* Identifier */; }), getIsDeclarationVisible)) {
38294                 return undefined;
38295             }
38296             return { accessibility: 0 /* Accessible */, aliasesToMakeVisible: aliasesToMakeVisible };
38297             function getIsDeclarationVisible(declaration) {
38298                 if (!isDeclarationVisible(declaration)) {
38299                     // Mark the unexported alias as visible if its parent is visible
38300                     // because these kind of aliases can be used to name types in declaration file
38301                     var anyImportSyntax = getAnyImportSyntax(declaration);
38302                     if (anyImportSyntax &&
38303                         !ts.hasModifier(anyImportSyntax, 1 /* Export */) && // import clause without export
38304                         isDeclarationVisible(anyImportSyntax.parent)) {
38305                         return addVisibleAlias(declaration, anyImportSyntax);
38306                     }
38307                     else if (ts.isVariableDeclaration(declaration) && ts.isVariableStatement(declaration.parent.parent) &&
38308                         !ts.hasModifier(declaration.parent.parent, 1 /* Export */) && // unexported variable statement
38309                         isDeclarationVisible(declaration.parent.parent.parent)) {
38310                         return addVisibleAlias(declaration, declaration.parent.parent);
38311                     }
38312                     else if (ts.isLateVisibilityPaintedStatement(declaration) // unexported top-level statement
38313                         && !ts.hasModifier(declaration, 1 /* Export */)
38314                         && isDeclarationVisible(declaration.parent)) {
38315                         return addVisibleAlias(declaration, declaration);
38316                     }
38317                     // Declaration is not visible
38318                     return false;
38319                 }
38320                 return true;
38321             }
38322             function addVisibleAlias(declaration, aliasingStatement) {
38323                 // In function "buildTypeDisplay" where we decide whether to write type-alias or serialize types,
38324                 // we want to just check if type- alias is accessible or not but we don't care about emitting those alias at that time
38325                 // since we will do the emitting later in trackSymbol.
38326                 if (shouldComputeAliasToMakeVisible) {
38327                     getNodeLinks(declaration).isVisible = true;
38328                     aliasesToMakeVisible = ts.appendIfUnique(aliasesToMakeVisible, aliasingStatement);
38329                 }
38330                 return true;
38331             }
38332         }
38333         function isEntityNameVisible(entityName, enclosingDeclaration) {
38334             // get symbol of the first identifier of the entityName
38335             var meaning;
38336             if (entityName.parent.kind === 172 /* TypeQuery */ ||
38337                 ts.isExpressionWithTypeArgumentsInClassExtendsClause(entityName.parent) ||
38338                 entityName.parent.kind === 154 /* ComputedPropertyName */) {
38339                 // Typeof value
38340                 meaning = 111551 /* Value */ | 1048576 /* ExportValue */;
38341             }
38342             else if (entityName.kind === 153 /* QualifiedName */ || entityName.kind === 194 /* PropertyAccessExpression */ ||
38343                 entityName.parent.kind === 253 /* ImportEqualsDeclaration */) {
38344                 // Left identifier from type reference or TypeAlias
38345                 // Entity name of the import declaration
38346                 meaning = 1920 /* Namespace */;
38347             }
38348             else {
38349                 // Type Reference or TypeAlias entity = Identifier
38350                 meaning = 788968 /* Type */;
38351             }
38352             var firstIdentifier = ts.getFirstIdentifier(entityName);
38353             var symbol = resolveName(enclosingDeclaration, firstIdentifier.escapedText, meaning, /*nodeNotFoundErrorMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false);
38354             // Verify if the symbol is accessible
38355             return (symbol && hasVisibleDeclarations(symbol, /*shouldComputeAliasToMakeVisible*/ true)) || {
38356                 accessibility: 1 /* NotAccessible */,
38357                 errorSymbolName: ts.getTextOfNode(firstIdentifier),
38358                 errorNode: firstIdentifier
38359             };
38360         }
38361         function symbolToString(symbol, enclosingDeclaration, meaning, flags, writer) {
38362             if (flags === void 0) { flags = 4 /* AllowAnyNodeKind */; }
38363             var nodeFlags = 70221824 /* IgnoreErrors */;
38364             if (flags & 2 /* UseOnlyExternalAliasing */) {
38365                 nodeFlags |= 128 /* UseOnlyExternalAliasing */;
38366             }
38367             if (flags & 1 /* WriteTypeParametersOrArguments */) {
38368                 nodeFlags |= 512 /* WriteTypeParametersInQualifiedName */;
38369             }
38370             if (flags & 8 /* UseAliasDefinedOutsideCurrentScope */) {
38371                 nodeFlags |= 16384 /* UseAliasDefinedOutsideCurrentScope */;
38372             }
38373             if (flags & 16 /* DoNotIncludeSymbolChain */) {
38374                 nodeFlags |= 134217728 /* DoNotIncludeSymbolChain */;
38375             }
38376             var builder = flags & 4 /* AllowAnyNodeKind */ ? nodeBuilder.symbolToExpression : nodeBuilder.symbolToEntityName;
38377             return writer ? symbolToStringWorker(writer).getText() : ts.usingSingleLineStringWriter(symbolToStringWorker);
38378             function symbolToStringWorker(writer) {
38379                 var entity = builder(symbol, meaning, enclosingDeclaration, nodeFlags); // TODO: GH#18217
38380                 var printer = ts.createPrinter({ removeComments: true });
38381                 var sourceFile = enclosingDeclaration && ts.getSourceFileOfNode(enclosingDeclaration);
38382                 printer.writeNode(4 /* Unspecified */, entity, /*sourceFile*/ sourceFile, writer);
38383                 return writer;
38384             }
38385         }
38386         function signatureToString(signature, enclosingDeclaration, flags, kind, writer) {
38387             if (flags === void 0) { flags = 0 /* None */; }
38388             return writer ? signatureToStringWorker(writer).getText() : ts.usingSingleLineStringWriter(signatureToStringWorker);
38389             function signatureToStringWorker(writer) {
38390                 var sigOutput;
38391                 if (flags & 262144 /* WriteArrowStyleSignature */) {
38392                     sigOutput = kind === 1 /* Construct */ ? 171 /* ConstructorType */ : 170 /* FunctionType */;
38393                 }
38394                 else {
38395                     sigOutput = kind === 1 /* Construct */ ? 166 /* ConstructSignature */ : 165 /* CallSignature */;
38396                 }
38397                 var sig = nodeBuilder.signatureToSignatureDeclaration(signature, sigOutput, enclosingDeclaration, toNodeBuilderFlags(flags) | 70221824 /* IgnoreErrors */ | 512 /* WriteTypeParametersInQualifiedName */);
38398                 var printer = ts.createPrinter({ removeComments: true, omitTrailingSemicolon: true });
38399                 var sourceFile = enclosingDeclaration && ts.getSourceFileOfNode(enclosingDeclaration);
38400                 printer.writeNode(4 /* Unspecified */, sig, /*sourceFile*/ sourceFile, ts.getTrailingSemicolonDeferringWriter(writer)); // TODO: GH#18217
38401                 return writer;
38402             }
38403         }
38404         function typeToString(type, enclosingDeclaration, flags, writer) {
38405             if (flags === void 0) { flags = 1048576 /* AllowUniqueESSymbolType */ | 16384 /* UseAliasDefinedOutsideCurrentScope */; }
38406             if (writer === void 0) { writer = ts.createTextWriter(""); }
38407             var noTruncation = compilerOptions.noErrorTruncation || flags & 1 /* NoTruncation */;
38408             var typeNode = nodeBuilder.typeToTypeNode(type, enclosingDeclaration, toNodeBuilderFlags(flags) | 70221824 /* IgnoreErrors */ | (noTruncation ? 1 /* NoTruncation */ : 0), writer);
38409             if (typeNode === undefined)
38410                 return ts.Debug.fail("should always get typenode");
38411             var options = { removeComments: true };
38412             var printer = ts.createPrinter(options);
38413             var sourceFile = enclosingDeclaration && ts.getSourceFileOfNode(enclosingDeclaration);
38414             printer.writeNode(4 /* Unspecified */, typeNode, /*sourceFile*/ sourceFile, writer);
38415             var result = writer.getText();
38416             var maxLength = noTruncation ? ts.noTruncationMaximumTruncationLength * 2 : ts.defaultMaximumTruncationLength * 2;
38417             if (maxLength && result && result.length >= maxLength) {
38418                 return result.substr(0, maxLength - "...".length) + "...";
38419             }
38420             return result;
38421         }
38422         function getTypeNamesForErrorDisplay(left, right) {
38423             var leftStr = symbolValueDeclarationIsContextSensitive(left.symbol) ? typeToString(left, left.symbol.valueDeclaration) : typeToString(left);
38424             var rightStr = symbolValueDeclarationIsContextSensitive(right.symbol) ? typeToString(right, right.symbol.valueDeclaration) : typeToString(right);
38425             if (leftStr === rightStr) {
38426                 leftStr = typeToString(left, /*enclosingDeclaration*/ undefined, 64 /* UseFullyQualifiedType */);
38427                 rightStr = typeToString(right, /*enclosingDeclaration*/ undefined, 64 /* UseFullyQualifiedType */);
38428             }
38429             return [leftStr, rightStr];
38430         }
38431         function symbolValueDeclarationIsContextSensitive(symbol) {
38432             return symbol && symbol.valueDeclaration && ts.isExpression(symbol.valueDeclaration) && !isContextSensitive(symbol.valueDeclaration);
38433         }
38434         function toNodeBuilderFlags(flags) {
38435             if (flags === void 0) { flags = 0 /* None */; }
38436             return flags & 814775659 /* NodeBuilderFlagsMask */;
38437         }
38438         function createNodeBuilder() {
38439             return {
38440                 typeToTypeNode: function (type, enclosingDeclaration, flags, tracker) {
38441                     return withContext(enclosingDeclaration, flags, tracker, function (context) { return typeToTypeNodeHelper(type, context); });
38442                 },
38443                 indexInfoToIndexSignatureDeclaration: function (indexInfo, kind, enclosingDeclaration, flags, tracker) {
38444                     return withContext(enclosingDeclaration, flags, tracker, function (context) { return indexInfoToIndexSignatureDeclarationHelper(indexInfo, kind, context); });
38445                 },
38446                 signatureToSignatureDeclaration: function (signature, kind, enclosingDeclaration, flags, tracker) {
38447                     return withContext(enclosingDeclaration, flags, tracker, function (context) { return signatureToSignatureDeclarationHelper(signature, kind, context); });
38448                 },
38449                 symbolToEntityName: function (symbol, meaning, enclosingDeclaration, flags, tracker) {
38450                     return withContext(enclosingDeclaration, flags, tracker, function (context) { return symbolToName(symbol, context, meaning, /*expectsIdentifier*/ false); });
38451                 },
38452                 symbolToExpression: function (symbol, meaning, enclosingDeclaration, flags, tracker) {
38453                     return withContext(enclosingDeclaration, flags, tracker, function (context) { return symbolToExpression(symbol, context, meaning); });
38454                 },
38455                 symbolToTypeParameterDeclarations: function (symbol, enclosingDeclaration, flags, tracker) {
38456                     return withContext(enclosingDeclaration, flags, tracker, function (context) { return typeParametersToTypeParameterDeclarations(symbol, context); });
38457                 },
38458                 symbolToParameterDeclaration: function (symbol, enclosingDeclaration, flags, tracker) {
38459                     return withContext(enclosingDeclaration, flags, tracker, function (context) { return symbolToParameterDeclaration(symbol, context); });
38460                 },
38461                 typeParameterToDeclaration: function (parameter, enclosingDeclaration, flags, tracker) {
38462                     return withContext(enclosingDeclaration, flags, tracker, function (context) { return typeParameterToDeclaration(parameter, context); });
38463                 },
38464                 symbolTableToDeclarationStatements: function (symbolTable, enclosingDeclaration, flags, tracker, bundled) {
38465                     return withContext(enclosingDeclaration, flags, tracker, function (context) { return symbolTableToDeclarationStatements(symbolTable, context, bundled); });
38466                 },
38467             };
38468             function withContext(enclosingDeclaration, flags, tracker, cb) {
38469                 ts.Debug.assert(enclosingDeclaration === undefined || (enclosingDeclaration.flags & 8 /* Synthesized */) === 0);
38470                 var context = {
38471                     enclosingDeclaration: enclosingDeclaration,
38472                     flags: flags || 0 /* None */,
38473                     // If no full tracker is provided, fake up a dummy one with a basic limited-functionality moduleResolverHost
38474                     tracker: tracker && tracker.trackSymbol ? tracker : { trackSymbol: ts.noop, moduleResolverHost: flags & 134217728 /* DoNotIncludeSymbolChain */ ? {
38475                             getCommonSourceDirectory: !!host.getCommonSourceDirectory ? function () { return host.getCommonSourceDirectory(); } : function () { return ""; },
38476                             getSourceFiles: function () { return host.getSourceFiles(); },
38477                             getCurrentDirectory: function () { return host.getCurrentDirectory(); },
38478                             getProbableSymlinks: ts.maybeBind(host, host.getProbableSymlinks),
38479                             useCaseSensitiveFileNames: ts.maybeBind(host, host.useCaseSensitiveFileNames),
38480                             redirectTargetsMap: host.redirectTargetsMap,
38481                             getProjectReferenceRedirect: function (fileName) { return host.getProjectReferenceRedirect(fileName); },
38482                             isSourceOfProjectReferenceRedirect: function (fileName) { return host.isSourceOfProjectReferenceRedirect(fileName); },
38483                             fileExists: function (fileName) { return host.fileExists(fileName); },
38484                         } : undefined },
38485                     encounteredError: false,
38486                     visitedTypes: undefined,
38487                     symbolDepth: undefined,
38488                     inferTypeParameters: undefined,
38489                     approximateLength: 0
38490                 };
38491                 var resultingNode = cb(context);
38492                 return context.encounteredError ? undefined : resultingNode;
38493             }
38494             function checkTruncationLength(context) {
38495                 if (context.truncating)
38496                     return context.truncating;
38497                 return context.truncating = context.approximateLength > ((context.flags & 1 /* NoTruncation */) ? ts.noTruncationMaximumTruncationLength : ts.defaultMaximumTruncationLength);
38498             }
38499             function typeToTypeNodeHelper(type, context) {
38500                 if (cancellationToken && cancellationToken.throwIfCancellationRequested) {
38501                     cancellationToken.throwIfCancellationRequested();
38502                 }
38503                 var inTypeAlias = context.flags & 8388608 /* InTypeAlias */;
38504                 context.flags &= ~8388608 /* InTypeAlias */;
38505                 if (!type) {
38506                     if (!(context.flags & 262144 /* AllowEmptyUnionOrIntersection */)) {
38507                         context.encounteredError = true;
38508                         return undefined; // TODO: GH#18217
38509                     }
38510                     context.approximateLength += 3;
38511                     return ts.createKeywordTypeNode(125 /* AnyKeyword */);
38512                 }
38513                 if (!(context.flags & 536870912 /* NoTypeReduction */)) {
38514                     type = getReducedType(type);
38515                 }
38516                 if (type.flags & 1 /* Any */) {
38517                     context.approximateLength += 3;
38518                     return ts.createKeywordTypeNode(125 /* AnyKeyword */);
38519                 }
38520                 if (type.flags & 2 /* Unknown */) {
38521                     return ts.createKeywordTypeNode(148 /* UnknownKeyword */);
38522                 }
38523                 if (type.flags & 4 /* String */) {
38524                     context.approximateLength += 6;
38525                     return ts.createKeywordTypeNode(143 /* StringKeyword */);
38526                 }
38527                 if (type.flags & 8 /* Number */) {
38528                     context.approximateLength += 6;
38529                     return ts.createKeywordTypeNode(140 /* NumberKeyword */);
38530                 }
38531                 if (type.flags & 64 /* BigInt */) {
38532                     context.approximateLength += 6;
38533                     return ts.createKeywordTypeNode(151 /* BigIntKeyword */);
38534                 }
38535                 if (type.flags & 16 /* Boolean */) {
38536                     context.approximateLength += 7;
38537                     return ts.createKeywordTypeNode(128 /* BooleanKeyword */);
38538                 }
38539                 if (type.flags & 1024 /* EnumLiteral */ && !(type.flags & 1048576 /* Union */)) {
38540                     var parentSymbol = getParentOfSymbol(type.symbol);
38541                     var parentName = symbolToTypeNode(parentSymbol, context, 788968 /* Type */);
38542                     var enumLiteralName = getDeclaredTypeOfSymbol(parentSymbol) === type
38543                         ? parentName
38544                         : appendReferenceToType(parentName, ts.createTypeReferenceNode(ts.symbolName(type.symbol), /*typeArguments*/ undefined));
38545                     return enumLiteralName;
38546                 }
38547                 if (type.flags & 1056 /* EnumLike */) {
38548                     return symbolToTypeNode(type.symbol, context, 788968 /* Type */);
38549                 }
38550                 if (type.flags & 128 /* StringLiteral */) {
38551                     context.approximateLength += (type.value.length + 2);
38552                     return ts.createLiteralTypeNode(ts.setEmitFlags(ts.createLiteral(type.value, !!(context.flags & 268435456 /* UseSingleQuotesForStringLiteralType */)), 16777216 /* NoAsciiEscaping */));
38553                 }
38554                 if (type.flags & 256 /* NumberLiteral */) {
38555                     var value = type.value;
38556                     context.approximateLength += ("" + value).length;
38557                     return ts.createLiteralTypeNode(value < 0 ? ts.createPrefix(40 /* MinusToken */, ts.createLiteral(-value)) : ts.createLiteral(value));
38558                 }
38559                 if (type.flags & 2048 /* BigIntLiteral */) {
38560                     context.approximateLength += (ts.pseudoBigIntToString(type.value).length) + 1;
38561                     return ts.createLiteralTypeNode((ts.createLiteral(type.value)));
38562                 }
38563                 if (type.flags & 512 /* BooleanLiteral */) {
38564                     context.approximateLength += type.intrinsicName.length;
38565                     return type.intrinsicName === "true" ? ts.createTrue() : ts.createFalse();
38566                 }
38567                 if (type.flags & 8192 /* UniqueESSymbol */) {
38568                     if (!(context.flags & 1048576 /* AllowUniqueESSymbolType */)) {
38569                         if (isValueSymbolAccessible(type.symbol, context.enclosingDeclaration)) {
38570                             context.approximateLength += 6;
38571                             return symbolToTypeNode(type.symbol, context, 111551 /* Value */);
38572                         }
38573                         if (context.tracker.reportInaccessibleUniqueSymbolError) {
38574                             context.tracker.reportInaccessibleUniqueSymbolError();
38575                         }
38576                     }
38577                     context.approximateLength += 13;
38578                     return ts.createTypeOperatorNode(147 /* UniqueKeyword */, ts.createKeywordTypeNode(144 /* SymbolKeyword */));
38579                 }
38580                 if (type.flags & 16384 /* Void */) {
38581                     context.approximateLength += 4;
38582                     return ts.createKeywordTypeNode(110 /* VoidKeyword */);
38583                 }
38584                 if (type.flags & 32768 /* Undefined */) {
38585                     context.approximateLength += 9;
38586                     return ts.createKeywordTypeNode(146 /* UndefinedKeyword */);
38587                 }
38588                 if (type.flags & 65536 /* Null */) {
38589                     context.approximateLength += 4;
38590                     return ts.createKeywordTypeNode(100 /* NullKeyword */);
38591                 }
38592                 if (type.flags & 131072 /* Never */) {
38593                     context.approximateLength += 5;
38594                     return ts.createKeywordTypeNode(137 /* NeverKeyword */);
38595                 }
38596                 if (type.flags & 4096 /* ESSymbol */) {
38597                     context.approximateLength += 6;
38598                     return ts.createKeywordTypeNode(144 /* SymbolKeyword */);
38599                 }
38600                 if (type.flags & 67108864 /* NonPrimitive */) {
38601                     context.approximateLength += 6;
38602                     return ts.createKeywordTypeNode(141 /* ObjectKeyword */);
38603                 }
38604                 if (isThisTypeParameter(type)) {
38605                     if (context.flags & 4194304 /* InObjectTypeLiteral */) {
38606                         if (!context.encounteredError && !(context.flags & 32768 /* AllowThisInObjectLiteral */)) {
38607                             context.encounteredError = true;
38608                         }
38609                         if (context.tracker.reportInaccessibleThisError) {
38610                             context.tracker.reportInaccessibleThisError();
38611                         }
38612                     }
38613                     context.approximateLength += 4;
38614                     return ts.createThis();
38615                 }
38616                 if (!inTypeAlias && type.aliasSymbol && (context.flags & 16384 /* UseAliasDefinedOutsideCurrentScope */ || isTypeSymbolAccessible(type.aliasSymbol, context.enclosingDeclaration))) {
38617                     var typeArgumentNodes = mapToTypeNodes(type.aliasTypeArguments, context);
38618                     if (isReservedMemberName(type.aliasSymbol.escapedName) && !(type.aliasSymbol.flags & 32 /* Class */))
38619                         return ts.createTypeReferenceNode(ts.createIdentifier(""), typeArgumentNodes);
38620                     return symbolToTypeNode(type.aliasSymbol, context, 788968 /* Type */, typeArgumentNodes);
38621                 }
38622                 var objectFlags = ts.getObjectFlags(type);
38623                 if (objectFlags & 4 /* Reference */) {
38624                     ts.Debug.assert(!!(type.flags & 524288 /* Object */));
38625                     return type.node ? visitAndTransformType(type, typeReferenceToTypeNode) : typeReferenceToTypeNode(type);
38626                 }
38627                 if (type.flags & 262144 /* TypeParameter */ || objectFlags & 3 /* ClassOrInterface */) {
38628                     if (type.flags & 262144 /* TypeParameter */ && ts.contains(context.inferTypeParameters, type)) {
38629                         context.approximateLength += (ts.symbolName(type.symbol).length + 6);
38630                         return ts.createInferTypeNode(typeParameterToDeclarationWithConstraint(type, context, /*constraintNode*/ undefined));
38631                     }
38632                     if (context.flags & 4 /* GenerateNamesForShadowedTypeParams */ &&
38633                         type.flags & 262144 /* TypeParameter */ &&
38634                         !isTypeSymbolAccessible(type.symbol, context.enclosingDeclaration)) {
38635                         var name = typeParameterToName(type, context);
38636                         context.approximateLength += ts.idText(name).length;
38637                         return ts.createTypeReferenceNode(ts.createIdentifier(ts.idText(name)), /*typeArguments*/ undefined);
38638                     }
38639                     // Ignore constraint/default when creating a usage (as opposed to declaration) of a type parameter.
38640                     return type.symbol
38641                         ? symbolToTypeNode(type.symbol, context, 788968 /* Type */)
38642                         : ts.createTypeReferenceNode(ts.createIdentifier("?"), /*typeArguments*/ undefined);
38643                 }
38644                 if (type.flags & (1048576 /* Union */ | 2097152 /* Intersection */)) {
38645                     var types = type.flags & 1048576 /* Union */ ? formatUnionTypes(type.types) : type.types;
38646                     if (ts.length(types) === 1) {
38647                         return typeToTypeNodeHelper(types[0], context);
38648                     }
38649                     var typeNodes = mapToTypeNodes(types, context, /*isBareList*/ true);
38650                     if (typeNodes && typeNodes.length > 0) {
38651                         var unionOrIntersectionTypeNode = ts.createUnionOrIntersectionTypeNode(type.flags & 1048576 /* Union */ ? 178 /* UnionType */ : 179 /* IntersectionType */, typeNodes);
38652                         return unionOrIntersectionTypeNode;
38653                     }
38654                     else {
38655                         if (!context.encounteredError && !(context.flags & 262144 /* AllowEmptyUnionOrIntersection */)) {
38656                             context.encounteredError = true;
38657                         }
38658                         return undefined; // TODO: GH#18217
38659                     }
38660                 }
38661                 if (objectFlags & (16 /* Anonymous */ | 32 /* Mapped */)) {
38662                     ts.Debug.assert(!!(type.flags & 524288 /* Object */));
38663                     // The type is an object literal type.
38664                     return createAnonymousTypeNode(type);
38665                 }
38666                 if (type.flags & 4194304 /* Index */) {
38667                     var indexedType = type.type;
38668                     context.approximateLength += 6;
38669                     var indexTypeNode = typeToTypeNodeHelper(indexedType, context);
38670                     return ts.createTypeOperatorNode(indexTypeNode);
38671                 }
38672                 if (type.flags & 8388608 /* IndexedAccess */) {
38673                     var objectTypeNode = typeToTypeNodeHelper(type.objectType, context);
38674                     var indexTypeNode = typeToTypeNodeHelper(type.indexType, context);
38675                     context.approximateLength += 2;
38676                     return ts.createIndexedAccessTypeNode(objectTypeNode, indexTypeNode);
38677                 }
38678                 if (type.flags & 16777216 /* Conditional */) {
38679                     var checkTypeNode = typeToTypeNodeHelper(type.checkType, context);
38680                     var saveInferTypeParameters = context.inferTypeParameters;
38681                     context.inferTypeParameters = type.root.inferTypeParameters;
38682                     var extendsTypeNode = typeToTypeNodeHelper(type.extendsType, context);
38683                     context.inferTypeParameters = saveInferTypeParameters;
38684                     var trueTypeNode = typeToTypeNodeOrCircularityElision(getTrueTypeFromConditionalType(type));
38685                     var falseTypeNode = typeToTypeNodeOrCircularityElision(getFalseTypeFromConditionalType(type));
38686                     context.approximateLength += 15;
38687                     return ts.createConditionalTypeNode(checkTypeNode, extendsTypeNode, trueTypeNode, falseTypeNode);
38688                 }
38689                 if (type.flags & 33554432 /* Substitution */) {
38690                     return typeToTypeNodeHelper(type.baseType, context);
38691                 }
38692                 return ts.Debug.fail("Should be unreachable.");
38693                 function typeToTypeNodeOrCircularityElision(type) {
38694                     var _a, _b;
38695                     if (type.flags & 1048576 /* Union */) {
38696                         if (context.visitedTypes && context.visitedTypes.has("" + getTypeId(type))) {
38697                             if (!(context.flags & 131072 /* AllowAnonymousIdentifier */)) {
38698                                 context.encounteredError = true;
38699                                 (_b = (_a = context.tracker) === null || _a === void 0 ? void 0 : _a.reportCyclicStructureError) === null || _b === void 0 ? void 0 : _b.call(_a);
38700                             }
38701                             return createElidedInformationPlaceholder(context);
38702                         }
38703                         return visitAndTransformType(type, function (type) { return typeToTypeNodeHelper(type, context); });
38704                     }
38705                     return typeToTypeNodeHelper(type, context);
38706                 }
38707                 function createMappedTypeNodeFromType(type) {
38708                     ts.Debug.assert(!!(type.flags & 524288 /* Object */));
38709                     var readonlyToken = type.declaration.readonlyToken ? ts.createToken(type.declaration.readonlyToken.kind) : undefined;
38710                     var questionToken = type.declaration.questionToken ? ts.createToken(type.declaration.questionToken.kind) : undefined;
38711                     var appropriateConstraintTypeNode;
38712                     if (isMappedTypeWithKeyofConstraintDeclaration(type)) {
38713                         // We have a { [P in keyof T]: X }
38714                         // We do this to ensure we retain the toplevel keyof-ness of the type which may be lost due to keyof distribution during `getConstraintTypeFromMappedType`
38715                         appropriateConstraintTypeNode = ts.createTypeOperatorNode(typeToTypeNodeHelper(getModifiersTypeFromMappedType(type), context));
38716                     }
38717                     else {
38718                         appropriateConstraintTypeNode = typeToTypeNodeHelper(getConstraintTypeFromMappedType(type), context);
38719                     }
38720                     var typeParameterNode = typeParameterToDeclarationWithConstraint(getTypeParameterFromMappedType(type), context, appropriateConstraintTypeNode);
38721                     var templateTypeNode = typeToTypeNodeHelper(getTemplateTypeFromMappedType(type), context);
38722                     var mappedTypeNode = ts.createMappedTypeNode(readonlyToken, typeParameterNode, questionToken, templateTypeNode);
38723                     context.approximateLength += 10;
38724                     return ts.setEmitFlags(mappedTypeNode, 1 /* SingleLine */);
38725                 }
38726                 function createAnonymousTypeNode(type) {
38727                     var typeId = "" + type.id;
38728                     var symbol = type.symbol;
38729                     if (symbol) {
38730                         if (isJSConstructor(symbol.valueDeclaration)) {
38731                             // Instance and static types share the same symbol; only add 'typeof' for the static side.
38732                             var isInstanceType = type === getDeclaredTypeOfClassOrInterface(symbol) ? 788968 /* Type */ : 111551 /* Value */;
38733                             return symbolToTypeNode(symbol, context, isInstanceType);
38734                         }
38735                         // Always use 'typeof T' for type of class, enum, and module objects
38736                         else if (symbol.flags & 32 /* Class */ && !getBaseTypeVariableOfClass(symbol) && !(symbol.valueDeclaration.kind === 214 /* ClassExpression */ && context.flags & 2048 /* WriteClassExpressionAsTypeLiteral */) ||
38737                             symbol.flags & (384 /* Enum */ | 512 /* ValueModule */) ||
38738                             shouldWriteTypeOfFunctionSymbol()) {
38739                             return symbolToTypeNode(symbol, context, 111551 /* Value */);
38740                         }
38741                         else if (context.visitedTypes && context.visitedTypes.has(typeId)) {
38742                             // If type is an anonymous type literal in a type alias declaration, use type alias name
38743                             var typeAlias = getTypeAliasForTypeLiteral(type);
38744                             if (typeAlias) {
38745                                 // The specified symbol flags need to be reinterpreted as type flags
38746                                 return symbolToTypeNode(typeAlias, context, 788968 /* Type */);
38747                             }
38748                             else {
38749                                 return createElidedInformationPlaceholder(context);
38750                             }
38751                         }
38752                         else {
38753                             return visitAndTransformType(type, createTypeNodeFromObjectType);
38754                         }
38755                     }
38756                     else {
38757                         // Anonymous types without a symbol are never circular.
38758                         return createTypeNodeFromObjectType(type);
38759                     }
38760                     function shouldWriteTypeOfFunctionSymbol() {
38761                         var isStaticMethodSymbol = !!(symbol.flags & 8192 /* Method */) && // typeof static method
38762                             ts.some(symbol.declarations, function (declaration) { return ts.hasModifier(declaration, 32 /* Static */); });
38763                         var isNonLocalFunctionSymbol = !!(symbol.flags & 16 /* Function */) &&
38764                             (symbol.parent || // is exported function symbol
38765                                 ts.forEach(symbol.declarations, function (declaration) {
38766                                     return declaration.parent.kind === 290 /* SourceFile */ || declaration.parent.kind === 250 /* ModuleBlock */;
38767                                 }));
38768                         if (isStaticMethodSymbol || isNonLocalFunctionSymbol) {
38769                             // typeof is allowed only for static/non local functions
38770                             return (!!(context.flags & 4096 /* UseTypeOfFunction */) || (context.visitedTypes && context.visitedTypes.has(typeId))) && // it is type of the symbol uses itself recursively
38771                                 (!(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
38772                         }
38773                     }
38774                 }
38775                 function visitAndTransformType(type, transform) {
38776                     var typeId = "" + type.id;
38777                     var isConstructorObject = ts.getObjectFlags(type) & 16 /* Anonymous */ && type.symbol && type.symbol.flags & 32 /* Class */;
38778                     var id = ts.getObjectFlags(type) & 4 /* Reference */ && type.node ? "N" + getNodeId(type.node) :
38779                         type.symbol ? (isConstructorObject ? "+" : "") + getSymbolId(type.symbol) :
38780                             undefined;
38781                     // Since instantiations of the same anonymous type have the same symbol, tracking symbols instead
38782                     // of types allows us to catch circular references to instantiations of the same anonymous type
38783                     if (!context.visitedTypes) {
38784                         context.visitedTypes = ts.createMap();
38785                     }
38786                     if (id && !context.symbolDepth) {
38787                         context.symbolDepth = ts.createMap();
38788                     }
38789                     var depth;
38790                     if (id) {
38791                         depth = context.symbolDepth.get(id) || 0;
38792                         if (depth > 10) {
38793                             return createElidedInformationPlaceholder(context);
38794                         }
38795                         context.symbolDepth.set(id, depth + 1);
38796                     }
38797                     context.visitedTypes.set(typeId, true);
38798                     var result = transform(type);
38799                     context.visitedTypes.delete(typeId);
38800                     if (id) {
38801                         context.symbolDepth.set(id, depth);
38802                     }
38803                     return result;
38804                 }
38805                 function createTypeNodeFromObjectType(type) {
38806                     if (isGenericMappedType(type)) {
38807                         return createMappedTypeNodeFromType(type);
38808                     }
38809                     var resolved = resolveStructuredTypeMembers(type);
38810                     if (!resolved.properties.length && !resolved.stringIndexInfo && !resolved.numberIndexInfo) {
38811                         if (!resolved.callSignatures.length && !resolved.constructSignatures.length) {
38812                             context.approximateLength += 2;
38813                             return ts.setEmitFlags(ts.createTypeLiteralNode(/*members*/ undefined), 1 /* SingleLine */);
38814                         }
38815                         if (resolved.callSignatures.length === 1 && !resolved.constructSignatures.length) {
38816                             var signature = resolved.callSignatures[0];
38817                             var signatureNode = signatureToSignatureDeclarationHelper(signature, 170 /* FunctionType */, context);
38818                             return signatureNode;
38819                         }
38820                         if (resolved.constructSignatures.length === 1 && !resolved.callSignatures.length) {
38821                             var signature = resolved.constructSignatures[0];
38822                             var signatureNode = signatureToSignatureDeclarationHelper(signature, 171 /* ConstructorType */, context);
38823                             return signatureNode;
38824                         }
38825                     }
38826                     var savedFlags = context.flags;
38827                     context.flags |= 4194304 /* InObjectTypeLiteral */;
38828                     var members = createTypeNodesFromResolvedType(resolved);
38829                     context.flags = savedFlags;
38830                     var typeLiteralNode = ts.createTypeLiteralNode(members);
38831                     context.approximateLength += 2;
38832                     return ts.setEmitFlags(typeLiteralNode, (context.flags & 1024 /* MultilineObjectLiterals */) ? 0 : 1 /* SingleLine */);
38833                 }
38834                 function typeReferenceToTypeNode(type) {
38835                     var typeArguments = getTypeArguments(type);
38836                     if (type.target === globalArrayType || type.target === globalReadonlyArrayType) {
38837                         if (context.flags & 2 /* WriteArrayAsGenericType */) {
38838                             var typeArgumentNode = typeToTypeNodeHelper(typeArguments[0], context);
38839                             return ts.createTypeReferenceNode(type.target === globalArrayType ? "Array" : "ReadonlyArray", [typeArgumentNode]);
38840                         }
38841                         var elementType = typeToTypeNodeHelper(typeArguments[0], context);
38842                         var arrayType = ts.createArrayTypeNode(elementType);
38843                         return type.target === globalArrayType ? arrayType : ts.createTypeOperatorNode(138 /* ReadonlyKeyword */, arrayType);
38844                     }
38845                     else if (type.target.objectFlags & 8 /* Tuple */) {
38846                         if (typeArguments.length > 0) {
38847                             var arity = getTypeReferenceArity(type);
38848                             var tupleConstituentNodes = mapToTypeNodes(typeArguments.slice(0, arity), context);
38849                             var hasRestElement = type.target.hasRestElement;
38850                             if (tupleConstituentNodes) {
38851                                 for (var i = type.target.minLength; i < Math.min(arity, tupleConstituentNodes.length); i++) {
38852                                     tupleConstituentNodes[i] = hasRestElement && i === arity - 1 ?
38853                                         ts.createRestTypeNode(ts.createArrayTypeNode(tupleConstituentNodes[i])) :
38854                                         ts.createOptionalTypeNode(tupleConstituentNodes[i]);
38855                                 }
38856                                 var tupleTypeNode = ts.createTupleTypeNode(tupleConstituentNodes);
38857                                 return type.target.readonly ? ts.createTypeOperatorNode(138 /* ReadonlyKeyword */, tupleTypeNode) : tupleTypeNode;
38858                             }
38859                         }
38860                         if (context.encounteredError || (context.flags & 524288 /* AllowEmptyTuple */)) {
38861                             var tupleTypeNode = ts.createTupleTypeNode([]);
38862                             return type.target.readonly ? ts.createTypeOperatorNode(138 /* ReadonlyKeyword */, tupleTypeNode) : tupleTypeNode;
38863                         }
38864                         context.encounteredError = true;
38865                         return undefined; // TODO: GH#18217
38866                     }
38867                     else if (context.flags & 2048 /* WriteClassExpressionAsTypeLiteral */ &&
38868                         type.symbol.valueDeclaration &&
38869                         ts.isClassLike(type.symbol.valueDeclaration) &&
38870                         !isValueSymbolAccessible(type.symbol, context.enclosingDeclaration)) {
38871                         return createAnonymousTypeNode(type);
38872                     }
38873                     else {
38874                         var outerTypeParameters = type.target.outerTypeParameters;
38875                         var i = 0;
38876                         var resultType = void 0;
38877                         if (outerTypeParameters) {
38878                             var length_2 = outerTypeParameters.length;
38879                             while (i < length_2) {
38880                                 // Find group of type arguments for type parameters with the same declaring container.
38881                                 var start = i;
38882                                 var parent = getParentSymbolOfTypeParameter(outerTypeParameters[i]);
38883                                 do {
38884                                     i++;
38885                                 } while (i < length_2 && getParentSymbolOfTypeParameter(outerTypeParameters[i]) === parent);
38886                                 // When type parameters are their own type arguments for the whole group (i.e. we have
38887                                 // the default outer type arguments), we don't show the group.
38888                                 if (!ts.rangeEquals(outerTypeParameters, typeArguments, start, i)) {
38889                                     var typeArgumentSlice = mapToTypeNodes(typeArguments.slice(start, i), context);
38890                                     var flags_2 = context.flags;
38891                                     context.flags |= 16 /* ForbidIndexedAccessSymbolReferences */;
38892                                     var ref = symbolToTypeNode(parent, context, 788968 /* Type */, typeArgumentSlice);
38893                                     context.flags = flags_2;
38894                                     resultType = !resultType ? ref : appendReferenceToType(resultType, ref);
38895                                 }
38896                             }
38897                         }
38898                         var typeArgumentNodes = void 0;
38899                         if (typeArguments.length > 0) {
38900                             var typeParameterCount = (type.target.typeParameters || ts.emptyArray).length;
38901                             typeArgumentNodes = mapToTypeNodes(typeArguments.slice(i, typeParameterCount), context);
38902                         }
38903                         var flags = context.flags;
38904                         context.flags |= 16 /* ForbidIndexedAccessSymbolReferences */;
38905                         var finalRef = symbolToTypeNode(type.symbol, context, 788968 /* Type */, typeArgumentNodes);
38906                         context.flags = flags;
38907                         return !resultType ? finalRef : appendReferenceToType(resultType, finalRef);
38908                     }
38909                 }
38910                 function appendReferenceToType(root, ref) {
38911                     if (ts.isImportTypeNode(root)) {
38912                         // first shift type arguments
38913                         var innerParams = root.typeArguments;
38914                         if (root.qualifier) {
38915                             (ts.isIdentifier(root.qualifier) ? root.qualifier : root.qualifier.right).typeArguments = innerParams;
38916                         }
38917                         root.typeArguments = ref.typeArguments;
38918                         // then move qualifiers
38919                         var ids = getAccessStack(ref);
38920                         for (var _i = 0, ids_1 = ids; _i < ids_1.length; _i++) {
38921                             var id = ids_1[_i];
38922                             root.qualifier = root.qualifier ? ts.createQualifiedName(root.qualifier, id) : id;
38923                         }
38924                         return root;
38925                     }
38926                     else {
38927                         // first shift type arguments
38928                         var innerParams = root.typeArguments;
38929                         (ts.isIdentifier(root.typeName) ? root.typeName : root.typeName.right).typeArguments = innerParams;
38930                         root.typeArguments = ref.typeArguments;
38931                         // then move qualifiers
38932                         var ids = getAccessStack(ref);
38933                         for (var _a = 0, ids_2 = ids; _a < ids_2.length; _a++) {
38934                             var id = ids_2[_a];
38935                             root.typeName = ts.createQualifiedName(root.typeName, id);
38936                         }
38937                         return root;
38938                     }
38939                 }
38940                 function getAccessStack(ref) {
38941                     var state = ref.typeName;
38942                     var ids = [];
38943                     while (!ts.isIdentifier(state)) {
38944                         ids.unshift(state.right);
38945                         state = state.left;
38946                     }
38947                     ids.unshift(state);
38948                     return ids;
38949                 }
38950                 function createTypeNodesFromResolvedType(resolvedType) {
38951                     if (checkTruncationLength(context)) {
38952                         return [ts.createPropertySignature(/*modifiers*/ undefined, "...", /*questionToken*/ undefined, /*type*/ undefined, /*initializer*/ undefined)];
38953                     }
38954                     var typeElements = [];
38955                     for (var _i = 0, _a = resolvedType.callSignatures; _i < _a.length; _i++) {
38956                         var signature = _a[_i];
38957                         typeElements.push(signatureToSignatureDeclarationHelper(signature, 165 /* CallSignature */, context));
38958                     }
38959                     for (var _b = 0, _c = resolvedType.constructSignatures; _b < _c.length; _b++) {
38960                         var signature = _c[_b];
38961                         typeElements.push(signatureToSignatureDeclarationHelper(signature, 166 /* ConstructSignature */, context));
38962                     }
38963                     if (resolvedType.stringIndexInfo) {
38964                         var indexSignature = void 0;
38965                         if (resolvedType.objectFlags & 2048 /* ReverseMapped */) {
38966                             indexSignature = indexInfoToIndexSignatureDeclarationHelper(createIndexInfo(anyType, resolvedType.stringIndexInfo.isReadonly, resolvedType.stringIndexInfo.declaration), 0 /* String */, context);
38967                             indexSignature.type = createElidedInformationPlaceholder(context);
38968                         }
38969                         else {
38970                             indexSignature = indexInfoToIndexSignatureDeclarationHelper(resolvedType.stringIndexInfo, 0 /* String */, context);
38971                         }
38972                         typeElements.push(indexSignature);
38973                     }
38974                     if (resolvedType.numberIndexInfo) {
38975                         typeElements.push(indexInfoToIndexSignatureDeclarationHelper(resolvedType.numberIndexInfo, 1 /* Number */, context));
38976                     }
38977                     var properties = resolvedType.properties;
38978                     if (!properties) {
38979                         return typeElements;
38980                     }
38981                     var i = 0;
38982                     for (var _d = 0, properties_1 = properties; _d < properties_1.length; _d++) {
38983                         var propertySymbol = properties_1[_d];
38984                         i++;
38985                         if (context.flags & 2048 /* WriteClassExpressionAsTypeLiteral */) {
38986                             if (propertySymbol.flags & 4194304 /* Prototype */) {
38987                                 continue;
38988                             }
38989                             if (ts.getDeclarationModifierFlagsFromSymbol(propertySymbol) & (8 /* Private */ | 16 /* Protected */) && context.tracker.reportPrivateInBaseOfClassExpression) {
38990                                 context.tracker.reportPrivateInBaseOfClassExpression(ts.unescapeLeadingUnderscores(propertySymbol.escapedName));
38991                             }
38992                         }
38993                         if (checkTruncationLength(context) && (i + 2 < properties.length - 1)) {
38994                             typeElements.push(ts.createPropertySignature(/*modifiers*/ undefined, "... " + (properties.length - i) + " more ...", /*questionToken*/ undefined, /*type*/ undefined, /*initializer*/ undefined));
38995                             addPropertyToElementList(properties[properties.length - 1], context, typeElements);
38996                             break;
38997                         }
38998                         addPropertyToElementList(propertySymbol, context, typeElements);
38999                     }
39000                     return typeElements.length ? typeElements : undefined;
39001                 }
39002             }
39003             function createElidedInformationPlaceholder(context) {
39004                 context.approximateLength += 3;
39005                 if (!(context.flags & 1 /* NoTruncation */)) {
39006                     return ts.createTypeReferenceNode(ts.createIdentifier("..."), /*typeArguments*/ undefined);
39007                 }
39008                 return ts.createKeywordTypeNode(125 /* AnyKeyword */);
39009             }
39010             function addPropertyToElementList(propertySymbol, context, typeElements) {
39011                 var propertyIsReverseMapped = !!(ts.getCheckFlags(propertySymbol) & 8192 /* ReverseMapped */);
39012                 var propertyType = propertyIsReverseMapped && context.flags & 33554432 /* InReverseMappedType */ ?
39013                     anyType : getTypeOfSymbol(propertySymbol);
39014                 var saveEnclosingDeclaration = context.enclosingDeclaration;
39015                 context.enclosingDeclaration = undefined;
39016                 if (context.tracker.trackSymbol && ts.getCheckFlags(propertySymbol) & 4096 /* Late */) {
39017                     var decl = ts.first(propertySymbol.declarations);
39018                     if (hasLateBindableName(decl)) {
39019                         if (ts.isBinaryExpression(decl)) {
39020                             var name = ts.getNameOfDeclaration(decl);
39021                             if (name && ts.isElementAccessExpression(name) && ts.isPropertyAccessEntityNameExpression(name.argumentExpression)) {
39022                                 trackComputedName(name.argumentExpression, saveEnclosingDeclaration, context);
39023                             }
39024                         }
39025                         else {
39026                             trackComputedName(decl.name.expression, saveEnclosingDeclaration, context);
39027                         }
39028                     }
39029                 }
39030                 context.enclosingDeclaration = saveEnclosingDeclaration;
39031                 var propertyName = getPropertyNameNodeForSymbol(propertySymbol, context);
39032                 context.approximateLength += (ts.symbolName(propertySymbol).length + 1);
39033                 var optionalToken = propertySymbol.flags & 16777216 /* Optional */ ? ts.createToken(57 /* QuestionToken */) : undefined;
39034                 if (propertySymbol.flags & (16 /* Function */ | 8192 /* Method */) && !getPropertiesOfObjectType(propertyType).length && !isReadonlySymbol(propertySymbol)) {
39035                     var signatures = getSignaturesOfType(filterType(propertyType, function (t) { return !(t.flags & 32768 /* Undefined */); }), 0 /* Call */);
39036                     for (var _i = 0, signatures_1 = signatures; _i < signatures_1.length; _i++) {
39037                         var signature = signatures_1[_i];
39038                         var methodDeclaration = signatureToSignatureDeclarationHelper(signature, 160 /* MethodSignature */, context);
39039                         methodDeclaration.name = propertyName;
39040                         methodDeclaration.questionToken = optionalToken;
39041                         typeElements.push(preserveCommentsOn(methodDeclaration));
39042                     }
39043                 }
39044                 else {
39045                     var savedFlags = context.flags;
39046                     context.flags |= propertyIsReverseMapped ? 33554432 /* InReverseMappedType */ : 0;
39047                     var propertyTypeNode = void 0;
39048                     if (propertyIsReverseMapped && !!(savedFlags & 33554432 /* InReverseMappedType */)) {
39049                         propertyTypeNode = createElidedInformationPlaceholder(context);
39050                     }
39051                     else {
39052                         propertyTypeNode = propertyType ? serializeTypeForDeclaration(context, propertyType, propertySymbol, saveEnclosingDeclaration) : ts.createKeywordTypeNode(125 /* AnyKeyword */);
39053                     }
39054                     context.flags = savedFlags;
39055                     var modifiers = isReadonlySymbol(propertySymbol) ? [ts.createToken(138 /* ReadonlyKeyword */)] : undefined;
39056                     if (modifiers) {
39057                         context.approximateLength += 9;
39058                     }
39059                     var propertySignature = ts.createPropertySignature(modifiers, propertyName, optionalToken, propertyTypeNode, 
39060                     /*initializer*/ undefined);
39061                     typeElements.push(preserveCommentsOn(propertySignature));
39062                 }
39063                 function preserveCommentsOn(node) {
39064                     if (ts.some(propertySymbol.declarations, function (d) { return d.kind === 323 /* JSDocPropertyTag */; })) {
39065                         var d = ts.find(propertySymbol.declarations, function (d) { return d.kind === 323 /* JSDocPropertyTag */; });
39066                         var commentText = d.comment;
39067                         if (commentText) {
39068                             ts.setSyntheticLeadingComments(node, [{ kind: 3 /* MultiLineCommentTrivia */, text: "*\n * " + commentText.replace(/\n/g, "\n * ") + "\n ", pos: -1, end: -1, hasTrailingNewLine: true }]);
39069                         }
39070                     }
39071                     else if (propertySymbol.valueDeclaration) {
39072                         // Copy comments to node for declaration emit
39073                         ts.setCommentRange(node, propertySymbol.valueDeclaration);
39074                     }
39075                     return node;
39076                 }
39077             }
39078             function mapToTypeNodes(types, context, isBareList) {
39079                 if (ts.some(types)) {
39080                     if (checkTruncationLength(context)) {
39081                         if (!isBareList) {
39082                             return [ts.createTypeReferenceNode("...", /*typeArguments*/ undefined)];
39083                         }
39084                         else if (types.length > 2) {
39085                             return [
39086                                 typeToTypeNodeHelper(types[0], context),
39087                                 ts.createTypeReferenceNode("... " + (types.length - 2) + " more ...", /*typeArguments*/ undefined),
39088                                 typeToTypeNodeHelper(types[types.length - 1], context)
39089                             ];
39090                         }
39091                     }
39092                     var mayHaveNameCollisions = !(context.flags & 64 /* UseFullyQualifiedType */);
39093                     /** Map from type reference identifier text to [type, index in `result` where the type node is] */
39094                     var seenNames = mayHaveNameCollisions ? ts.createUnderscoreEscapedMultiMap() : undefined;
39095                     var result_3 = [];
39096                     var i = 0;
39097                     for (var _i = 0, types_1 = types; _i < types_1.length; _i++) {
39098                         var type = types_1[_i];
39099                         i++;
39100                         if (checkTruncationLength(context) && (i + 2 < types.length - 1)) {
39101                             result_3.push(ts.createTypeReferenceNode("... " + (types.length - i) + " more ...", /*typeArguments*/ undefined));
39102                             var typeNode_1 = typeToTypeNodeHelper(types[types.length - 1], context);
39103                             if (typeNode_1) {
39104                                 result_3.push(typeNode_1);
39105                             }
39106                             break;
39107                         }
39108                         context.approximateLength += 2; // Account for whitespace + separator
39109                         var typeNode = typeToTypeNodeHelper(type, context);
39110                         if (typeNode) {
39111                             result_3.push(typeNode);
39112                             if (seenNames && ts.isIdentifierTypeReference(typeNode)) {
39113                                 seenNames.add(typeNode.typeName.escapedText, [type, result_3.length - 1]);
39114                             }
39115                         }
39116                     }
39117                     if (seenNames) {
39118                         // To avoid printing types like `[Foo, Foo]` or `Bar & Bar` where
39119                         // occurrences of the same name actually come from different
39120                         // namespaces, go through the single-identifier type reference nodes
39121                         // we just generated, and see if any names were generated more than
39122                         // once while referring to different types. If so, regenerate the
39123                         // type node for each entry by that name with the
39124                         // `UseFullyQualifiedType` flag enabled.
39125                         var saveContextFlags = context.flags;
39126                         context.flags |= 64 /* UseFullyQualifiedType */;
39127                         seenNames.forEach(function (types) {
39128                             if (!ts.arrayIsHomogeneous(types, function (_a, _b) {
39129                                 var a = _a[0];
39130                                 var b = _b[0];
39131                                 return typesAreSameReference(a, b);
39132                             })) {
39133                                 for (var _i = 0, types_2 = types; _i < types_2.length; _i++) {
39134                                     var _a = types_2[_i], type = _a[0], resultIndex = _a[1];
39135                                     result_3[resultIndex] = typeToTypeNodeHelper(type, context);
39136                                 }
39137                             }
39138                         });
39139                         context.flags = saveContextFlags;
39140                     }
39141                     return result_3;
39142                 }
39143             }
39144             function typesAreSameReference(a, b) {
39145                 return a === b
39146                     || !!a.symbol && a.symbol === b.symbol
39147                     || !!a.aliasSymbol && a.aliasSymbol === b.aliasSymbol;
39148             }
39149             function indexInfoToIndexSignatureDeclarationHelper(indexInfo, kind, context) {
39150                 var name = ts.getNameFromIndexInfo(indexInfo) || "x";
39151                 var indexerTypeNode = ts.createKeywordTypeNode(kind === 0 /* String */ ? 143 /* StringKeyword */ : 140 /* NumberKeyword */);
39152                 var indexingParameter = ts.createParameter(
39153                 /*decorators*/ undefined, 
39154                 /*modifiers*/ undefined, 
39155                 /*dotDotDotToken*/ undefined, name, 
39156                 /*questionToken*/ undefined, indexerTypeNode, 
39157                 /*initializer*/ undefined);
39158                 var typeNode = typeToTypeNodeHelper(indexInfo.type || anyType, context);
39159                 if (!indexInfo.type && !(context.flags & 2097152 /* AllowEmptyIndexInfoType */)) {
39160                     context.encounteredError = true;
39161                 }
39162                 context.approximateLength += (name.length + 4);
39163                 return ts.createIndexSignature(
39164                 /*decorators*/ undefined, indexInfo.isReadonly ? [ts.createToken(138 /* ReadonlyKeyword */)] : undefined, [indexingParameter], typeNode);
39165             }
39166             function signatureToSignatureDeclarationHelper(signature, kind, context, privateSymbolVisitor, bundledImports) {
39167                 var suppressAny = context.flags & 256 /* SuppressAnyReturnType */;
39168                 if (suppressAny)
39169                     context.flags &= ~256 /* SuppressAnyReturnType */; // suppress only toplevel `any`s
39170                 var typeParameters;
39171                 var typeArguments;
39172                 if (context.flags & 32 /* WriteTypeArgumentsOfSignature */ && signature.target && signature.mapper && signature.target.typeParameters) {
39173                     typeArguments = signature.target.typeParameters.map(function (parameter) { return typeToTypeNodeHelper(instantiateType(parameter, signature.mapper), context); });
39174                 }
39175                 else {
39176                     typeParameters = signature.typeParameters && signature.typeParameters.map(function (parameter) { return typeParameterToDeclaration(parameter, context); });
39177                 }
39178                 var parameters = getExpandedParameters(signature).map(function (parameter) { return symbolToParameterDeclaration(parameter, context, kind === 162 /* Constructor */, privateSymbolVisitor, bundledImports); });
39179                 if (signature.thisParameter) {
39180                     var thisParameter = symbolToParameterDeclaration(signature.thisParameter, context);
39181                     parameters.unshift(thisParameter);
39182                 }
39183                 var returnTypeNode;
39184                 var typePredicate = getTypePredicateOfSignature(signature);
39185                 if (typePredicate) {
39186                     var assertsModifier = typePredicate.kind === 2 /* AssertsThis */ || typePredicate.kind === 3 /* AssertsIdentifier */ ?
39187                         ts.createToken(124 /* AssertsKeyword */) :
39188                         undefined;
39189                     var parameterName = typePredicate.kind === 1 /* Identifier */ || typePredicate.kind === 3 /* AssertsIdentifier */ ?
39190                         ts.setEmitFlags(ts.createIdentifier(typePredicate.parameterName), 16777216 /* NoAsciiEscaping */) :
39191                         ts.createThisTypeNode();
39192                     var typeNode = typePredicate.type && typeToTypeNodeHelper(typePredicate.type, context);
39193                     returnTypeNode = ts.createTypePredicateNodeWithModifier(assertsModifier, parameterName, typeNode);
39194                 }
39195                 else {
39196                     var returnType = getReturnTypeOfSignature(signature);
39197                     if (returnType && !(suppressAny && isTypeAny(returnType))) {
39198                         returnTypeNode = serializeReturnTypeForSignature(context, returnType, signature, privateSymbolVisitor, bundledImports);
39199                     }
39200                     else if (!suppressAny) {
39201                         returnTypeNode = ts.createKeywordTypeNode(125 /* AnyKeyword */);
39202                     }
39203                 }
39204                 context.approximateLength += 3; // Usually a signature contributes a few more characters than this, but 3 is the minimum
39205                 return ts.createSignatureDeclaration(kind, typeParameters, parameters, returnTypeNode, typeArguments);
39206             }
39207             function typeParameterToDeclarationWithConstraint(type, context, constraintNode) {
39208                 var savedContextFlags = context.flags;
39209                 context.flags &= ~512 /* WriteTypeParametersInQualifiedName */; // Avoids potential infinite loop when building for a claimspace with a generic
39210                 var name = typeParameterToName(type, context);
39211                 var defaultParameter = getDefaultFromTypeParameter(type);
39212                 var defaultParameterNode = defaultParameter && typeToTypeNodeHelper(defaultParameter, context);
39213                 context.flags = savedContextFlags;
39214                 return ts.createTypeParameterDeclaration(name, constraintNode, defaultParameterNode);
39215             }
39216             function typeParameterToDeclaration(type, context, constraint) {
39217                 if (constraint === void 0) { constraint = getConstraintOfTypeParameter(type); }
39218                 var constraintNode = constraint && typeToTypeNodeHelper(constraint, context);
39219                 return typeParameterToDeclarationWithConstraint(type, context, constraintNode);
39220             }
39221             function symbolToParameterDeclaration(parameterSymbol, context, preserveModifierFlags, privateSymbolVisitor, bundledImports) {
39222                 var parameterDeclaration = ts.getDeclarationOfKind(parameterSymbol, 156 /* Parameter */);
39223                 if (!parameterDeclaration && !ts.isTransientSymbol(parameterSymbol)) {
39224                     parameterDeclaration = ts.getDeclarationOfKind(parameterSymbol, 317 /* JSDocParameterTag */);
39225                 }
39226                 var parameterType = getTypeOfSymbol(parameterSymbol);
39227                 if (parameterDeclaration && isRequiredInitializedParameter(parameterDeclaration)) {
39228                     parameterType = getOptionalType(parameterType);
39229                 }
39230                 var parameterTypeNode = serializeTypeForDeclaration(context, parameterType, parameterSymbol, context.enclosingDeclaration, privateSymbolVisitor, bundledImports);
39231                 var modifiers = !(context.flags & 8192 /* OmitParameterModifiers */) && preserveModifierFlags && parameterDeclaration && parameterDeclaration.modifiers ? parameterDeclaration.modifiers.map(ts.getSynthesizedClone) : undefined;
39232                 var isRest = parameterDeclaration && ts.isRestParameter(parameterDeclaration) || ts.getCheckFlags(parameterSymbol) & 32768 /* RestParameter */;
39233                 var dotDotDotToken = isRest ? ts.createToken(25 /* DotDotDotToken */) : undefined;
39234                 var name = parameterDeclaration ? parameterDeclaration.name ?
39235                     parameterDeclaration.name.kind === 75 /* Identifier */ ? ts.setEmitFlags(ts.getSynthesizedClone(parameterDeclaration.name), 16777216 /* NoAsciiEscaping */) :
39236                         parameterDeclaration.name.kind === 153 /* QualifiedName */ ? ts.setEmitFlags(ts.getSynthesizedClone(parameterDeclaration.name.right), 16777216 /* NoAsciiEscaping */) :
39237                             cloneBindingName(parameterDeclaration.name) :
39238                     ts.symbolName(parameterSymbol) :
39239                     ts.symbolName(parameterSymbol);
39240                 var isOptional = parameterDeclaration && isOptionalParameter(parameterDeclaration) || ts.getCheckFlags(parameterSymbol) & 16384 /* OptionalParameter */;
39241                 var questionToken = isOptional ? ts.createToken(57 /* QuestionToken */) : undefined;
39242                 var parameterNode = ts.createParameter(
39243                 /*decorators*/ undefined, modifiers, dotDotDotToken, name, questionToken, parameterTypeNode, 
39244                 /*initializer*/ undefined);
39245                 context.approximateLength += ts.symbolName(parameterSymbol).length + 3;
39246                 return parameterNode;
39247                 function cloneBindingName(node) {
39248                     return elideInitializerAndSetEmitFlags(node);
39249                     function elideInitializerAndSetEmitFlags(node) {
39250                         if (context.tracker.trackSymbol && ts.isComputedPropertyName(node) && isLateBindableName(node)) {
39251                             trackComputedName(node.expression, context.enclosingDeclaration, context);
39252                         }
39253                         var visited = ts.visitEachChild(node, elideInitializerAndSetEmitFlags, ts.nullTransformationContext, /*nodesVisitor*/ undefined, elideInitializerAndSetEmitFlags);
39254                         var clone = ts.nodeIsSynthesized(visited) ? visited : ts.getSynthesizedClone(visited);
39255                         if (clone.kind === 191 /* BindingElement */) {
39256                             clone.initializer = undefined;
39257                         }
39258                         return ts.setEmitFlags(clone, 1 /* SingleLine */ | 16777216 /* NoAsciiEscaping */);
39259                     }
39260                 }
39261             }
39262             function trackComputedName(accessExpression, enclosingDeclaration, context) {
39263                 if (!context.tracker.trackSymbol)
39264                     return;
39265                 // get symbol of the first identifier of the entityName
39266                 var firstIdentifier = ts.getFirstIdentifier(accessExpression);
39267                 var name = resolveName(firstIdentifier, firstIdentifier.escapedText, 111551 /* Value */ | 1048576 /* ExportValue */, /*nodeNotFoundErrorMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ true);
39268                 if (name) {
39269                     context.tracker.trackSymbol(name, enclosingDeclaration, 111551 /* Value */);
39270                 }
39271             }
39272             function lookupSymbolChain(symbol, context, meaning, yieldModuleSymbol) {
39273                 context.tracker.trackSymbol(symbol, context.enclosingDeclaration, meaning); // TODO: GH#18217
39274                 return lookupSymbolChainWorker(symbol, context, meaning, yieldModuleSymbol);
39275             }
39276             function lookupSymbolChainWorker(symbol, context, meaning, yieldModuleSymbol) {
39277                 // Try to get qualified name if the symbol is not a type parameter and there is an enclosing declaration.
39278                 var chain;
39279                 var isTypeParameter = symbol.flags & 262144 /* TypeParameter */;
39280                 if (!isTypeParameter && (context.enclosingDeclaration || context.flags & 64 /* UseFullyQualifiedType */) && !(context.flags & 134217728 /* DoNotIncludeSymbolChain */)) {
39281                     chain = ts.Debug.checkDefined(getSymbolChain(symbol, meaning, /*endOfChain*/ true));
39282                     ts.Debug.assert(chain && chain.length > 0);
39283                 }
39284                 else {
39285                     chain = [symbol];
39286                 }
39287                 return chain;
39288                 /** @param endOfChain Set to false for recursive calls; non-recursive calls should always output something. */
39289                 function getSymbolChain(symbol, meaning, endOfChain) {
39290                     var accessibleSymbolChain = getAccessibleSymbolChain(symbol, context.enclosingDeclaration, meaning, !!(context.flags & 128 /* UseOnlyExternalAliasing */));
39291                     var parentSpecifiers;
39292                     if (!accessibleSymbolChain ||
39293                         needsQualification(accessibleSymbolChain[0], context.enclosingDeclaration, accessibleSymbolChain.length === 1 ? meaning : getQualifiedLeftMeaning(meaning))) {
39294                         // Go up and add our parent.
39295                         var parents_1 = getContainersOfSymbol(accessibleSymbolChain ? accessibleSymbolChain[0] : symbol, context.enclosingDeclaration);
39296                         if (ts.length(parents_1)) {
39297                             parentSpecifiers = parents_1.map(function (symbol) {
39298                                 return ts.some(symbol.declarations, hasNonGlobalAugmentationExternalModuleSymbol)
39299                                     ? getSpecifierForModuleSymbol(symbol, context)
39300                                     : undefined;
39301                             });
39302                             var indices = parents_1.map(function (_, i) { return i; });
39303                             indices.sort(sortByBestName);
39304                             var sortedParents = indices.map(function (i) { return parents_1[i]; });
39305                             for (var _i = 0, sortedParents_1 = sortedParents; _i < sortedParents_1.length; _i++) {
39306                                 var parent = sortedParents_1[_i];
39307                                 var parentChain = getSymbolChain(parent, getQualifiedLeftMeaning(meaning), /*endOfChain*/ false);
39308                                 if (parentChain) {
39309                                     if (parent.exports && parent.exports.get("export=" /* ExportEquals */) &&
39310                                         getSymbolIfSameReference(parent.exports.get("export=" /* ExportEquals */), symbol)) {
39311                                         // parentChain root _is_ symbol - symbol is a module export=, so it kinda looks like it's own parent
39312                                         // No need to lookup an alias for the symbol in itself
39313                                         accessibleSymbolChain = parentChain;
39314                                         break;
39315                                     }
39316                                     accessibleSymbolChain = parentChain.concat(accessibleSymbolChain || [getAliasForSymbolInContainer(parent, symbol) || symbol]);
39317                                     break;
39318                                 }
39319                             }
39320                         }
39321                     }
39322                     if (accessibleSymbolChain) {
39323                         return accessibleSymbolChain;
39324                     }
39325                     if (
39326                     // If this is the last part of outputting the symbol, always output. The cases apply only to parent symbols.
39327                     endOfChain ||
39328                         // If a parent symbol is an anonymous type, don't write it.
39329                         !(symbol.flags & (2048 /* TypeLiteral */ | 4096 /* ObjectLiteral */))) {
39330                         // If a parent symbol is an external module, don't write it. (We prefer just `x` vs `"foo/bar".x`.)
39331                         if (!endOfChain && !yieldModuleSymbol && !!ts.forEach(symbol.declarations, hasNonGlobalAugmentationExternalModuleSymbol)) {
39332                             return;
39333                         }
39334                         return [symbol];
39335                     }
39336                     function sortByBestName(a, b) {
39337                         var specifierA = parentSpecifiers[a];
39338                         var specifierB = parentSpecifiers[b];
39339                         if (specifierA && specifierB) {
39340                             var isBRelative = ts.pathIsRelative(specifierB);
39341                             if (ts.pathIsRelative(specifierA) === isBRelative) {
39342                                 // Both relative or both non-relative, sort by number of parts
39343                                 return ts.moduleSpecifiers.countPathComponents(specifierA) - ts.moduleSpecifiers.countPathComponents(specifierB);
39344                             }
39345                             if (isBRelative) {
39346                                 // A is non-relative, B is relative: prefer A
39347                                 return -1;
39348                             }
39349                             // A is relative, B is non-relative: prefer B
39350                             return 1;
39351                         }
39352                         return 0;
39353                     }
39354                 }
39355             }
39356             function typeParametersToTypeParameterDeclarations(symbol, context) {
39357                 var typeParameterNodes;
39358                 var targetSymbol = getTargetSymbol(symbol);
39359                 if (targetSymbol.flags & (32 /* Class */ | 64 /* Interface */ | 524288 /* TypeAlias */)) {
39360                     typeParameterNodes = ts.createNodeArray(ts.map(getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol), function (tp) { return typeParameterToDeclaration(tp, context); }));
39361                 }
39362                 return typeParameterNodes;
39363             }
39364             function lookupTypeParameterNodes(chain, index, context) {
39365                 ts.Debug.assert(chain && 0 <= index && index < chain.length);
39366                 var symbol = chain[index];
39367                 var symbolId = "" + getSymbolId(symbol);
39368                 if (context.typeParameterSymbolList && context.typeParameterSymbolList.get(symbolId)) {
39369                     return undefined;
39370                 }
39371                 (context.typeParameterSymbolList || (context.typeParameterSymbolList = ts.createMap())).set(symbolId, true);
39372                 var typeParameterNodes;
39373                 if (context.flags & 512 /* WriteTypeParametersInQualifiedName */ && index < (chain.length - 1)) {
39374                     var parentSymbol = symbol;
39375                     var nextSymbol_1 = chain[index + 1];
39376                     if (ts.getCheckFlags(nextSymbol_1) & 1 /* Instantiated */) {
39377                         var params = getTypeParametersOfClassOrInterface(parentSymbol.flags & 2097152 /* Alias */ ? resolveAlias(parentSymbol) : parentSymbol);
39378                         typeParameterNodes = mapToTypeNodes(ts.map(params, function (t) { return getMappedType(t, nextSymbol_1.mapper); }), context);
39379                     }
39380                     else {
39381                         typeParameterNodes = typeParametersToTypeParameterDeclarations(symbol, context);
39382                     }
39383                 }
39384                 return typeParameterNodes;
39385             }
39386             /**
39387              * Given A[B][C][D], finds A[B]
39388              */
39389             function getTopmostIndexedAccessType(top) {
39390                 if (ts.isIndexedAccessTypeNode(top.objectType)) {
39391                     return getTopmostIndexedAccessType(top.objectType);
39392                 }
39393                 return top;
39394             }
39395             function getSpecifierForModuleSymbol(symbol, context) {
39396                 var file = ts.getDeclarationOfKind(symbol, 290 /* SourceFile */);
39397                 if (!file) {
39398                     var equivalentFileSymbol = ts.firstDefined(symbol.declarations, function (d) { return getFileSymbolIfFileSymbolExportEqualsContainer(d, symbol); });
39399                     if (equivalentFileSymbol) {
39400                         file = ts.getDeclarationOfKind(equivalentFileSymbol, 290 /* SourceFile */);
39401                     }
39402                 }
39403                 if (file && file.moduleName !== undefined) {
39404                     // Use the amd name if it is available
39405                     return file.moduleName;
39406                 }
39407                 if (!file) {
39408                     if (context.tracker.trackReferencedAmbientModule) {
39409                         var ambientDecls = ts.filter(symbol.declarations, ts.isAmbientModule);
39410                         if (ts.length(ambientDecls)) {
39411                             for (var _i = 0, ambientDecls_1 = ambientDecls; _i < ambientDecls_1.length; _i++) {
39412                                 var decl = ambientDecls_1[_i];
39413                                 context.tracker.trackReferencedAmbientModule(decl, symbol);
39414                             }
39415                         }
39416                     }
39417                     if (ambientModuleSymbolRegex.test(symbol.escapedName)) {
39418                         return symbol.escapedName.substring(1, symbol.escapedName.length - 1);
39419                     }
39420                 }
39421                 if (!context.enclosingDeclaration || !context.tracker.moduleResolverHost) {
39422                     // If there's no context declaration, we can't lookup a non-ambient specifier, so we just use the symbol name
39423                     if (ambientModuleSymbolRegex.test(symbol.escapedName)) {
39424                         return symbol.escapedName.substring(1, symbol.escapedName.length - 1);
39425                     }
39426                     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
39427                 }
39428                 var contextFile = ts.getSourceFileOfNode(ts.getOriginalNode(context.enclosingDeclaration));
39429                 var links = getSymbolLinks(symbol);
39430                 var specifier = links.specifierCache && links.specifierCache.get(contextFile.path);
39431                 if (!specifier) {
39432                     var isBundle_1 = (compilerOptions.out || compilerOptions.outFile);
39433                     // For declaration bundles, we need to generate absolute paths relative to the common source dir for imports,
39434                     // just like how the declaration emitter does for the ambient module declarations - we can easily accomplish this
39435                     // using the `baseUrl` compiler option (which we would otherwise never use in declaration emit) and a non-relative
39436                     // specifier preference
39437                     var moduleResolverHost = context.tracker.moduleResolverHost;
39438                     var specifierCompilerOptions = isBundle_1 ? __assign(__assign({}, compilerOptions), { baseUrl: moduleResolverHost.getCommonSourceDirectory() }) : compilerOptions;
39439                     specifier = ts.first(ts.moduleSpecifiers.getModuleSpecifiers(symbol, specifierCompilerOptions, contextFile, moduleResolverHost, { importModuleSpecifierPreference: isBundle_1 ? "non-relative" : "relative" }));
39440                     links.specifierCache = links.specifierCache || ts.createMap();
39441                     links.specifierCache.set(contextFile.path, specifier);
39442                 }
39443                 return specifier;
39444             }
39445             function symbolToTypeNode(symbol, context, meaning, overrideTypeArguments) {
39446                 var chain = lookupSymbolChain(symbol, context, meaning, !(context.flags & 16384 /* UseAliasDefinedOutsideCurrentScope */)); // If we're using aliases outside the current scope, dont bother with the module
39447                 var isTypeOf = meaning === 111551 /* Value */;
39448                 if (ts.some(chain[0].declarations, hasNonGlobalAugmentationExternalModuleSymbol)) {
39449                     // module is root, must use `ImportTypeNode`
39450                     var nonRootParts = chain.length > 1 ? createAccessFromSymbolChain(chain, chain.length - 1, 1) : undefined;
39451                     var typeParameterNodes = overrideTypeArguments || lookupTypeParameterNodes(chain, 0, context);
39452                     var specifier = getSpecifierForModuleSymbol(chain[0], context);
39453                     if (!(context.flags & 67108864 /* AllowNodeModulesRelativePaths */) && ts.getEmitModuleResolutionKind(compilerOptions) === ts.ModuleResolutionKind.NodeJs && specifier.indexOf("/node_modules/") >= 0) {
39454                         // If ultimately we can only name the symbol with a reference that dives into a `node_modules` folder, we should error
39455                         // since declaration files with these kinds of references are liable to fail when published :(
39456                         context.encounteredError = true;
39457                         if (context.tracker.reportLikelyUnsafeImportRequiredError) {
39458                             context.tracker.reportLikelyUnsafeImportRequiredError(specifier);
39459                         }
39460                     }
39461                     var lit = ts.createLiteralTypeNode(ts.createLiteral(specifier));
39462                     if (context.tracker.trackExternalModuleSymbolOfImportTypeNode)
39463                         context.tracker.trackExternalModuleSymbolOfImportTypeNode(chain[0]);
39464                     context.approximateLength += specifier.length + 10; // specifier + import("")
39465                     if (!nonRootParts || ts.isEntityName(nonRootParts)) {
39466                         if (nonRootParts) {
39467                             var lastId = ts.isIdentifier(nonRootParts) ? nonRootParts : nonRootParts.right;
39468                             lastId.typeArguments = undefined;
39469                         }
39470                         return ts.createImportTypeNode(lit, nonRootParts, typeParameterNodes, isTypeOf);
39471                     }
39472                     else {
39473                         var splitNode = getTopmostIndexedAccessType(nonRootParts);
39474                         var qualifier = splitNode.objectType.typeName;
39475                         return ts.createIndexedAccessTypeNode(ts.createImportTypeNode(lit, qualifier, typeParameterNodes, isTypeOf), splitNode.indexType);
39476                     }
39477                 }
39478                 var entityName = createAccessFromSymbolChain(chain, chain.length - 1, 0);
39479                 if (ts.isIndexedAccessTypeNode(entityName)) {
39480                     return entityName; // Indexed accesses can never be `typeof`
39481                 }
39482                 if (isTypeOf) {
39483                     return ts.createTypeQueryNode(entityName);
39484                 }
39485                 else {
39486                     var lastId = ts.isIdentifier(entityName) ? entityName : entityName.right;
39487                     var lastTypeArgs = lastId.typeArguments;
39488                     lastId.typeArguments = undefined;
39489                     return ts.createTypeReferenceNode(entityName, lastTypeArgs);
39490                 }
39491                 function createAccessFromSymbolChain(chain, index, stopper) {
39492                     var typeParameterNodes = index === (chain.length - 1) ? overrideTypeArguments : lookupTypeParameterNodes(chain, index, context);
39493                     var symbol = chain[index];
39494                     var parent = chain[index - 1];
39495                     var symbolName;
39496                     if (index === 0) {
39497                         context.flags |= 16777216 /* InInitialEntityName */;
39498                         symbolName = getNameOfSymbolAsWritten(symbol, context);
39499                         context.approximateLength += (symbolName ? symbolName.length : 0) + 1;
39500                         context.flags ^= 16777216 /* InInitialEntityName */;
39501                     }
39502                     else {
39503                         if (parent && getExportsOfSymbol(parent)) {
39504                             var exports_1 = getExportsOfSymbol(parent);
39505                             ts.forEachEntry(exports_1, function (ex, name) {
39506                                 if (getSymbolIfSameReference(ex, symbol) && !isLateBoundName(name) && name !== "export=" /* ExportEquals */) {
39507                                     symbolName = ts.unescapeLeadingUnderscores(name);
39508                                     return true;
39509                                 }
39510                             });
39511                         }
39512                     }
39513                     if (!symbolName) {
39514                         symbolName = getNameOfSymbolAsWritten(symbol, context);
39515                     }
39516                     context.approximateLength += symbolName.length + 1;
39517                     if (!(context.flags & 16 /* ForbidIndexedAccessSymbolReferences */) && parent &&
39518                         getMembersOfSymbol(parent) && getMembersOfSymbol(parent).get(symbol.escapedName) &&
39519                         getSymbolIfSameReference(getMembersOfSymbol(parent).get(symbol.escapedName), symbol)) {
39520                         // Should use an indexed access
39521                         var LHS = createAccessFromSymbolChain(chain, index - 1, stopper);
39522                         if (ts.isIndexedAccessTypeNode(LHS)) {
39523                             return ts.createIndexedAccessTypeNode(LHS, ts.createLiteralTypeNode(ts.createLiteral(symbolName)));
39524                         }
39525                         else {
39526                             return ts.createIndexedAccessTypeNode(ts.createTypeReferenceNode(LHS, typeParameterNodes), ts.createLiteralTypeNode(ts.createLiteral(symbolName)));
39527                         }
39528                     }
39529                     var identifier = ts.setEmitFlags(ts.createIdentifier(symbolName, typeParameterNodes), 16777216 /* NoAsciiEscaping */);
39530                     identifier.symbol = symbol;
39531                     if (index > stopper) {
39532                         var LHS = createAccessFromSymbolChain(chain, index - 1, stopper);
39533                         if (!ts.isEntityName(LHS)) {
39534                             return ts.Debug.fail("Impossible construct - an export of an indexed access cannot be reachable");
39535                         }
39536                         return ts.createQualifiedName(LHS, identifier);
39537                     }
39538                     return identifier;
39539                 }
39540             }
39541             function typeParameterShadowsNameInScope(escapedName, context, type) {
39542                 var result = resolveName(context.enclosingDeclaration, escapedName, 788968 /* Type */, /*nameNotFoundArg*/ undefined, escapedName, /*isUse*/ false);
39543                 if (result) {
39544                     if (result.flags & 262144 /* TypeParameter */ && result === type.symbol) {
39545                         return false;
39546                     }
39547                     return true;
39548                 }
39549                 return false;
39550             }
39551             function typeParameterToName(type, context) {
39552                 if (context.flags & 4 /* GenerateNamesForShadowedTypeParams */ && context.typeParameterNames) {
39553                     var cached = context.typeParameterNames.get("" + getTypeId(type));
39554                     if (cached) {
39555                         return cached;
39556                     }
39557                 }
39558                 var result = symbolToName(type.symbol, context, 788968 /* Type */, /*expectsIdentifier*/ true);
39559                 if (!(result.kind & 75 /* Identifier */)) {
39560                     return ts.createIdentifier("(Missing type parameter)");
39561                 }
39562                 if (context.flags & 4 /* GenerateNamesForShadowedTypeParams */) {
39563                     var rawtext = result.escapedText;
39564                     var i = 0;
39565                     var text = rawtext;
39566                     while ((context.typeParameterNamesByText && context.typeParameterNamesByText.get(text)) || typeParameterShadowsNameInScope(text, context, type)) {
39567                         i++;
39568                         text = rawtext + "_" + i;
39569                     }
39570                     if (text !== rawtext) {
39571                         result = ts.createIdentifier(text, result.typeArguments);
39572                     }
39573                     (context.typeParameterNames || (context.typeParameterNames = ts.createMap())).set("" + getTypeId(type), result);
39574                     (context.typeParameterNamesByText || (context.typeParameterNamesByText = ts.createMap())).set(result.escapedText, true);
39575                 }
39576                 return result;
39577             }
39578             function symbolToName(symbol, context, meaning, expectsIdentifier) {
39579                 var chain = lookupSymbolChain(symbol, context, meaning);
39580                 if (expectsIdentifier && chain.length !== 1
39581                     && !context.encounteredError
39582                     && !(context.flags & 65536 /* AllowQualifedNameInPlaceOfIdentifier */)) {
39583                     context.encounteredError = true;
39584                 }
39585                 return createEntityNameFromSymbolChain(chain, chain.length - 1);
39586                 function createEntityNameFromSymbolChain(chain, index) {
39587                     var typeParameterNodes = lookupTypeParameterNodes(chain, index, context);
39588                     var symbol = chain[index];
39589                     if (index === 0) {
39590                         context.flags |= 16777216 /* InInitialEntityName */;
39591                     }
39592                     var symbolName = getNameOfSymbolAsWritten(symbol, context);
39593                     if (index === 0) {
39594                         context.flags ^= 16777216 /* InInitialEntityName */;
39595                     }
39596                     var identifier = ts.setEmitFlags(ts.createIdentifier(symbolName, typeParameterNodes), 16777216 /* NoAsciiEscaping */);
39597                     identifier.symbol = symbol;
39598                     return index > 0 ? ts.createQualifiedName(createEntityNameFromSymbolChain(chain, index - 1), identifier) : identifier;
39599                 }
39600             }
39601             function symbolToExpression(symbol, context, meaning) {
39602                 var chain = lookupSymbolChain(symbol, context, meaning);
39603                 return createExpressionFromSymbolChain(chain, chain.length - 1);
39604                 function createExpressionFromSymbolChain(chain, index) {
39605                     var typeParameterNodes = lookupTypeParameterNodes(chain, index, context);
39606                     var symbol = chain[index];
39607                     if (index === 0) {
39608                         context.flags |= 16777216 /* InInitialEntityName */;
39609                     }
39610                     var symbolName = getNameOfSymbolAsWritten(symbol, context);
39611                     if (index === 0) {
39612                         context.flags ^= 16777216 /* InInitialEntityName */;
39613                     }
39614                     var firstChar = symbolName.charCodeAt(0);
39615                     if (ts.isSingleOrDoubleQuote(firstChar) && ts.some(symbol.declarations, hasNonGlobalAugmentationExternalModuleSymbol)) {
39616                         return ts.createLiteral(getSpecifierForModuleSymbol(symbol, context));
39617                     }
39618                     var canUsePropertyAccess = firstChar === 35 /* hash */ ?
39619                         symbolName.length > 1 && ts.isIdentifierStart(symbolName.charCodeAt(1), languageVersion) :
39620                         ts.isIdentifierStart(firstChar, languageVersion);
39621                     if (index === 0 || canUsePropertyAccess) {
39622                         var identifier = ts.setEmitFlags(ts.createIdentifier(symbolName, typeParameterNodes), 16777216 /* NoAsciiEscaping */);
39623                         identifier.symbol = symbol;
39624                         return index > 0 ? ts.createPropertyAccess(createExpressionFromSymbolChain(chain, index - 1), identifier) : identifier;
39625                     }
39626                     else {
39627                         if (firstChar === 91 /* openBracket */) {
39628                             symbolName = symbolName.substring(1, symbolName.length - 1);
39629                             firstChar = symbolName.charCodeAt(0);
39630                         }
39631                         var expression = void 0;
39632                         if (ts.isSingleOrDoubleQuote(firstChar)) {
39633                             expression = ts.createLiteral(symbolName.substring(1, symbolName.length - 1).replace(/\\./g, function (s) { return s.substring(1); }));
39634                             expression.singleQuote = firstChar === 39 /* singleQuote */;
39635                         }
39636                         else if (("" + +symbolName) === symbolName) {
39637                             expression = ts.createLiteral(+symbolName);
39638                         }
39639                         if (!expression) {
39640                             expression = ts.setEmitFlags(ts.createIdentifier(symbolName, typeParameterNodes), 16777216 /* NoAsciiEscaping */);
39641                             expression.symbol = symbol;
39642                         }
39643                         return ts.createElementAccess(createExpressionFromSymbolChain(chain, index - 1), expression);
39644                     }
39645                 }
39646             }
39647             function isSingleQuotedStringNamed(d) {
39648                 var name = ts.getNameOfDeclaration(d);
39649                 if (name && ts.isStringLiteral(name) && (name.singleQuote ||
39650                     (!ts.nodeIsSynthesized(name) && ts.startsWith(ts.getTextOfNode(name, /*includeTrivia*/ false), "'")))) {
39651                     return true;
39652                 }
39653                 return false;
39654             }
39655             function getPropertyNameNodeForSymbol(symbol, context) {
39656                 var singleQuote = !!ts.length(symbol.declarations) && ts.every(symbol.declarations, isSingleQuotedStringNamed);
39657                 var fromNameType = getPropertyNameNodeForSymbolFromNameType(symbol, context, singleQuote);
39658                 if (fromNameType) {
39659                     return fromNameType;
39660                 }
39661                 if (ts.isKnownSymbol(symbol)) {
39662                     return ts.createComputedPropertyName(ts.createPropertyAccess(ts.createIdentifier("Symbol"), symbol.escapedName.substr(3)));
39663                 }
39664                 var rawName = ts.unescapeLeadingUnderscores(symbol.escapedName);
39665                 return createPropertyNameNodeForIdentifierOrLiteral(rawName, singleQuote);
39666             }
39667             // See getNameForSymbolFromNameType for a stringy equivalent
39668             function getPropertyNameNodeForSymbolFromNameType(symbol, context, singleQuote) {
39669                 var nameType = getSymbolLinks(symbol).nameType;
39670                 if (nameType) {
39671                     if (nameType.flags & 384 /* StringOrNumberLiteral */) {
39672                         var name = "" + nameType.value;
39673                         if (!ts.isIdentifierText(name, compilerOptions.target) && !isNumericLiteralName(name)) {
39674                             return ts.createLiteral(name, !!singleQuote);
39675                         }
39676                         if (isNumericLiteralName(name) && ts.startsWith(name, "-")) {
39677                             return ts.createComputedPropertyName(ts.createLiteral(+name));
39678                         }
39679                         return createPropertyNameNodeForIdentifierOrLiteral(name);
39680                     }
39681                     if (nameType.flags & 8192 /* UniqueESSymbol */) {
39682                         return ts.createComputedPropertyName(symbolToExpression(nameType.symbol, context, 111551 /* Value */));
39683                     }
39684                 }
39685             }
39686             function createPropertyNameNodeForIdentifierOrLiteral(name, singleQuote) {
39687                 return ts.isIdentifierText(name, compilerOptions.target) ? ts.createIdentifier(name) : ts.createLiteral(isNumericLiteralName(name) && +name >= 0 ? +name : name, !!singleQuote);
39688             }
39689             function cloneNodeBuilderContext(context) {
39690                 var initial = __assign({}, context);
39691                 // Make type parameters created within this context not consume the name outside this context
39692                 // The symbol serializer ends up creating many sibling scopes that all need "separate" contexts when
39693                 // it comes to naming things - within a normal `typeToTypeNode` call, the node builder only ever descends
39694                 // through the type tree, so the only cases where we could have used distinct sibling scopes was when there
39695                 // were multiple generic overloads with similar generated type parameter names
39696                 // The effect:
39697                 // When we write out
39698                 // export const x: <T>(x: T) => T
39699                 // export const y: <T>(x: T) => T
39700                 // we write it out like that, rather than as
39701                 // export const x: <T>(x: T) => T
39702                 // export const y: <T_1>(x: T_1) => T_1
39703                 if (initial.typeParameterNames) {
39704                     initial.typeParameterNames = ts.cloneMap(initial.typeParameterNames);
39705                 }
39706                 if (initial.typeParameterNamesByText) {
39707                     initial.typeParameterNamesByText = ts.cloneMap(initial.typeParameterNamesByText);
39708                 }
39709                 if (initial.typeParameterSymbolList) {
39710                     initial.typeParameterSymbolList = ts.cloneMap(initial.typeParameterSymbolList);
39711                 }
39712                 return initial;
39713             }
39714             function getDeclarationWithTypeAnnotation(symbol, enclosingDeclaration) {
39715                 return symbol.declarations && ts.find(symbol.declarations, function (s) { return !!ts.getEffectiveTypeAnnotationNode(s) && (!enclosingDeclaration || !!ts.findAncestor(s, function (n) { return n === enclosingDeclaration; })); });
39716             }
39717             function existingTypeNodeIsNotReferenceOrIsReferenceWithCompatibleTypeArgumentCount(existing, type) {
39718                 return !(ts.getObjectFlags(type) & 4 /* Reference */) || !ts.isTypeReferenceNode(existing) || ts.length(existing.typeArguments) >= getMinTypeArgumentCount(type.target.typeParameters);
39719             }
39720             /**
39721              * Unlike `typeToTypeNodeHelper`, this handles setting up the `AllowUniqueESSymbolType` flag
39722              * so a `unique symbol` is returned when appropriate for the input symbol, rather than `typeof sym`
39723              */
39724             function serializeTypeForDeclaration(context, type, symbol, enclosingDeclaration, includePrivateSymbol, bundled) {
39725                 if (type !== errorType && enclosingDeclaration) {
39726                     var declWithExistingAnnotation = getDeclarationWithTypeAnnotation(symbol, enclosingDeclaration);
39727                     if (declWithExistingAnnotation && !ts.isFunctionLikeDeclaration(declWithExistingAnnotation)) {
39728                         // try to reuse the existing annotation
39729                         var existing = ts.getEffectiveTypeAnnotationNode(declWithExistingAnnotation);
39730                         if (getTypeFromTypeNode(existing) === type && existingTypeNodeIsNotReferenceOrIsReferenceWithCompatibleTypeArgumentCount(existing, type)) {
39731                             var result_4 = serializeExistingTypeNode(context, existing, includePrivateSymbol, bundled);
39732                             if (result_4) {
39733                                 return result_4;
39734                             }
39735                         }
39736                     }
39737                 }
39738                 var oldFlags = context.flags;
39739                 if (type.flags & 8192 /* UniqueESSymbol */ &&
39740                     type.symbol === symbol) {
39741                     context.flags |= 1048576 /* AllowUniqueESSymbolType */;
39742                 }
39743                 var result = typeToTypeNodeHelper(type, context);
39744                 context.flags = oldFlags;
39745                 return result;
39746             }
39747             function serializeReturnTypeForSignature(context, type, signature, includePrivateSymbol, bundled) {
39748                 if (type !== errorType && context.enclosingDeclaration) {
39749                     var annotation = signature.declaration && ts.getEffectiveReturnTypeNode(signature.declaration);
39750                     if (!!ts.findAncestor(annotation, function (n) { return n === context.enclosingDeclaration; }) && annotation && instantiateType(getTypeFromTypeNode(annotation), signature.mapper) === type && existingTypeNodeIsNotReferenceOrIsReferenceWithCompatibleTypeArgumentCount(annotation, type)) {
39751                         var result = serializeExistingTypeNode(context, annotation, includePrivateSymbol, bundled);
39752                         if (result) {
39753                             return result;
39754                         }
39755                     }
39756                 }
39757                 return typeToTypeNodeHelper(type, context);
39758             }
39759             function serializeExistingTypeNode(context, existing, includePrivateSymbol, bundled) {
39760                 if (cancellationToken && cancellationToken.throwIfCancellationRequested) {
39761                     cancellationToken.throwIfCancellationRequested();
39762                 }
39763                 var hadError = false;
39764                 var transformed = ts.visitNode(existing, visitExistingNodeTreeSymbols);
39765                 if (hadError) {
39766                     return undefined;
39767                 }
39768                 return transformed === existing ? ts.getMutableClone(existing) : transformed;
39769                 function visitExistingNodeTreeSymbols(node) {
39770                     var _a, _b;
39771                     // We don't _actually_ support jsdoc namepath types, emit `any` instead
39772                     if (ts.isJSDocAllType(node) || node.kind === 302 /* JSDocNamepathType */) {
39773                         return ts.createKeywordTypeNode(125 /* AnyKeyword */);
39774                     }
39775                     if (ts.isJSDocUnknownType(node)) {
39776                         return ts.createKeywordTypeNode(148 /* UnknownKeyword */);
39777                     }
39778                     if (ts.isJSDocNullableType(node)) {
39779                         return ts.createUnionTypeNode([ts.visitNode(node.type, visitExistingNodeTreeSymbols), ts.createKeywordTypeNode(100 /* NullKeyword */)]);
39780                     }
39781                     if (ts.isJSDocOptionalType(node)) {
39782                         return ts.createUnionTypeNode([ts.visitNode(node.type, visitExistingNodeTreeSymbols), ts.createKeywordTypeNode(146 /* UndefinedKeyword */)]);
39783                     }
39784                     if (ts.isJSDocNonNullableType(node)) {
39785                         return ts.visitNode(node.type, visitExistingNodeTreeSymbols);
39786                     }
39787                     if (ts.isJSDocVariadicType(node)) {
39788                         return ts.createArrayTypeNode(ts.visitNode(node.type, visitExistingNodeTreeSymbols));
39789                     }
39790                     if (ts.isJSDocTypeLiteral(node)) {
39791                         return ts.createTypeLiteralNode(ts.map(node.jsDocPropertyTags, function (t) {
39792                             var name = ts.isIdentifier(t.name) ? t.name : t.name.right;
39793                             var typeViaParent = getTypeOfPropertyOfType(getTypeFromTypeNode(node), name.escapedText);
39794                             var overrideTypeNode = typeViaParent && t.typeExpression && getTypeFromTypeNode(t.typeExpression.type) !== typeViaParent ? typeToTypeNodeHelper(typeViaParent, context) : undefined;
39795                             return ts.createPropertySignature(
39796                             /*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 */), 
39797                             /*initializer*/ undefined);
39798                         }));
39799                     }
39800                     if (ts.isTypeReferenceNode(node) && ts.isIdentifier(node.typeName) && node.typeName.escapedText === "") {
39801                         return ts.setOriginalNode(ts.createKeywordTypeNode(125 /* AnyKeyword */), node);
39802                     }
39803                     if ((ts.isExpressionWithTypeArguments(node) || ts.isTypeReferenceNode(node)) && ts.isJSDocIndexSignature(node)) {
39804                         return ts.createTypeLiteralNode([ts.createIndexSignature(
39805                             /*decorators*/ undefined, 
39806                             /*modifiers*/ undefined, [ts.createParameter(
39807                                 /*decorators*/ undefined, 
39808                                 /*modifiers*/ undefined, 
39809                                 /*dotdotdotToken*/ undefined, "x", 
39810                                 /*questionToken*/ undefined, ts.visitNode(node.typeArguments[0], visitExistingNodeTreeSymbols))], ts.visitNode(node.typeArguments[1], visitExistingNodeTreeSymbols))]);
39811                     }
39812                     if (ts.isJSDocFunctionType(node)) {
39813                         if (ts.isJSDocConstructSignature(node)) {
39814                             var newTypeNode_1;
39815                             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(
39816                             /*decorators*/ undefined, 
39817                             /*modifiers*/ undefined, getEffectiveDotDotDotForParameter(p), p.name || getEffectiveDotDotDotForParameter(p) ? "args" : "arg" + i, p.questionToken, ts.visitNode(p.type, visitExistingNodeTreeSymbols), 
39818                             /*initializer*/ undefined); }), ts.visitNode(newTypeNode_1 || node.type, visitExistingNodeTreeSymbols));
39819                         }
39820                         else {
39821                             return ts.createFunctionTypeNode(ts.visitNodes(node.typeParameters, visitExistingNodeTreeSymbols), ts.map(node.parameters, function (p, i) { return ts.createParameter(
39822                             /*decorators*/ undefined, 
39823                             /*modifiers*/ undefined, getEffectiveDotDotDotForParameter(p), p.name || getEffectiveDotDotDotForParameter(p) ? "args" : "arg" + i, p.questionToken, ts.visitNode(p.type, visitExistingNodeTreeSymbols), 
39824                             /*initializer*/ undefined); }), ts.visitNode(node.type, visitExistingNodeTreeSymbols));
39825                         }
39826                     }
39827                     if (ts.isTypeReferenceNode(node) && ts.isInJSDoc(node) && (getIntendedTypeFromJSDocTypeReference(node) || unknownSymbol === resolveTypeReferenceName(getTypeReferenceName(node), 788968 /* Type */, /*ignoreErrors*/ true))) {
39828                         return ts.setOriginalNode(typeToTypeNodeHelper(getTypeFromTypeNode(node), context), node);
39829                     }
39830                     if (ts.isLiteralImportTypeNode(node)) {
39831                         return ts.updateImportTypeNode(node, ts.updateLiteralTypeNode(node.argument, rewriteModuleSpecifier(node, node.argument.literal)), node.qualifier, ts.visitNodes(node.typeArguments, visitExistingNodeTreeSymbols, ts.isTypeNode), node.isTypeOf);
39832                     }
39833                     if (ts.isEntityName(node) || ts.isEntityNameExpression(node)) {
39834                         var leftmost = ts.getFirstIdentifier(node);
39835                         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)))) {
39836                             hadError = true;
39837                             return node;
39838                         }
39839                         var sym = resolveEntityName(leftmost, 67108863 /* All */, /*ignoreErrors*/ true, /*dontResolveALias*/ true);
39840                         if (sym) {
39841                             if (isSymbolAccessible(sym, context.enclosingDeclaration, 67108863 /* All */, /*shouldComputeAliasesToMakeVisible*/ false).accessibility !== 0 /* Accessible */) {
39842                                 hadError = true;
39843                             }
39844                             else {
39845                                 (_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 */);
39846                                 includePrivateSymbol === null || includePrivateSymbol === void 0 ? void 0 : includePrivateSymbol(sym);
39847                             }
39848                             if (ts.isIdentifier(node)) {
39849                                 var name = sym.flags & 262144 /* TypeParameter */ ? typeParameterToName(getDeclaredTypeOfSymbol(sym), context) : ts.getMutableClone(node);
39850                                 name.symbol = sym; // for quickinfo, which uses identifier symbol information
39851                                 return ts.setEmitFlags(ts.setOriginalNode(name, node), 16777216 /* NoAsciiEscaping */);
39852                             }
39853                         }
39854                     }
39855                     return ts.visitEachChild(node, visitExistingNodeTreeSymbols, ts.nullTransformationContext);
39856                     function getEffectiveDotDotDotForParameter(p) {
39857                         return p.dotDotDotToken || (p.type && ts.isJSDocVariadicType(p.type) ? ts.createToken(25 /* DotDotDotToken */) : undefined);
39858                     }
39859                     function rewriteModuleSpecifier(parent, lit) {
39860                         if (bundled) {
39861                             if (context.tracker && context.tracker.moduleResolverHost) {
39862                                 var targetFile = getExternalModuleFileFromDeclaration(parent);
39863                                 if (targetFile) {
39864                                     var getCanonicalFileName = ts.createGetCanonicalFileName(!!host.useCaseSensitiveFileNames);
39865                                     var resolverHost = {
39866                                         getCanonicalFileName: getCanonicalFileName,
39867                                         getCurrentDirectory: function () { return context.tracker.moduleResolverHost.getCurrentDirectory(); },
39868                                         getCommonSourceDirectory: function () { return context.tracker.moduleResolverHost.getCommonSourceDirectory(); }
39869                                     };
39870                                     var newName = ts.getResolvedExternalModuleName(resolverHost, targetFile);
39871                                     return ts.createLiteral(newName);
39872                                 }
39873                             }
39874                         }
39875                         else {
39876                             if (context.tracker && context.tracker.trackExternalModuleSymbolOfImportTypeNode) {
39877                                 var moduleSym = resolveExternalModuleNameWorker(lit, lit, /*moduleNotFoundError*/ undefined);
39878                                 if (moduleSym) {
39879                                     context.tracker.trackExternalModuleSymbolOfImportTypeNode(moduleSym);
39880                                 }
39881                             }
39882                         }
39883                         return lit;
39884                     }
39885                 }
39886             }
39887             function symbolTableToDeclarationStatements(symbolTable, context, bundled) {
39888                 var serializePropertySymbolForClass = makeSerializePropertySymbol(ts.createProperty, 161 /* MethodDeclaration */, /*useAcessors*/ true);
39889                 var serializePropertySymbolForInterfaceWorker = makeSerializePropertySymbol(function (_decorators, mods, name, question, type, initializer) { return ts.createPropertySignature(mods, name, question, type, initializer); }, 160 /* MethodSignature */, /*useAcessors*/ false);
39890                 // TODO: Use `setOriginalNode` on original declaration names where possible so these declarations see some kind of
39891                 // declaration mapping
39892                 // We save the enclosing declaration off here so it's not adjusted by well-meaning declaration
39893                 // emit codepaths which want to apply more specific contexts (so we can still refer to the root real declaration
39894                 // we're trying to emit from later on)
39895                 var enclosingDeclaration = context.enclosingDeclaration;
39896                 var results = [];
39897                 var visitedSymbols = ts.createMap();
39898                 var deferredPrivates;
39899                 var oldcontext = context;
39900                 context = __assign(__assign({}, oldcontext), { usedSymbolNames: ts.createMap(), remappedSymbolNames: ts.createMap(), tracker: __assign(__assign({}, oldcontext.tracker), { trackSymbol: function (sym, decl, meaning) {
39901                             var accessibleResult = isSymbolAccessible(sym, decl, meaning, /*computeALiases*/ false);
39902                             if (accessibleResult.accessibility === 0 /* Accessible */) {
39903                                 // Lookup the root symbol of the chain of refs we'll use to access it and serialize it
39904                                 var chain = lookupSymbolChainWorker(sym, context, meaning);
39905                                 if (!(sym.flags & 4 /* Property */)) {
39906                                     includePrivateSymbol(chain[0]);
39907                                 }
39908                             }
39909                             else if (oldcontext.tracker && oldcontext.tracker.trackSymbol) {
39910                                 oldcontext.tracker.trackSymbol(sym, decl, meaning);
39911                             }
39912                         } }) });
39913                 if (oldcontext.usedSymbolNames) {
39914                     oldcontext.usedSymbolNames.forEach(function (_, name) {
39915                         context.usedSymbolNames.set(name, true);
39916                     });
39917                 }
39918                 ts.forEachEntry(symbolTable, function (symbol, name) {
39919                     var baseName = ts.unescapeLeadingUnderscores(name);
39920                     void getInternalSymbolName(symbol, baseName); // Called to cache values into `usedSymbolNames` and `remappedSymbolNames`
39921                 });
39922                 var addingDeclare = !bundled;
39923                 var exportEquals = symbolTable.get("export=" /* ExportEquals */);
39924                 if (exportEquals && symbolTable.size > 1 && exportEquals.flags & 2097152 /* Alias */) {
39925                     symbolTable = ts.createSymbolTable();
39926                     // Remove extraneous elements from root symbol table (they'll be mixed back in when the target of the `export=` is looked up)
39927                     symbolTable.set("export=" /* ExportEquals */, exportEquals);
39928                 }
39929                 visitSymbolTable(symbolTable);
39930                 return mergeRedundantStatements(results);
39931                 function isIdentifierAndNotUndefined(node) {
39932                     return !!node && node.kind === 75 /* Identifier */;
39933                 }
39934                 function getNamesOfDeclaration(statement) {
39935                     if (ts.isVariableStatement(statement)) {
39936                         return ts.filter(ts.map(statement.declarationList.declarations, ts.getNameOfDeclaration), isIdentifierAndNotUndefined);
39937                     }
39938                     return ts.filter([ts.getNameOfDeclaration(statement)], isIdentifierAndNotUndefined);
39939                 }
39940                 function flattenExportAssignedNamespace(statements) {
39941                     var exportAssignment = ts.find(statements, ts.isExportAssignment);
39942                     var ns = ts.find(statements, ts.isModuleDeclaration);
39943                     if (ns && exportAssignment && exportAssignment.isExportEquals &&
39944                         ts.isIdentifier(exportAssignment.expression) && ts.isIdentifier(ns.name) && ts.idText(ns.name) === ts.idText(exportAssignment.expression) &&
39945                         ns.body && ts.isModuleBlock(ns.body)) {
39946                         // Pass 0: Correct situations where a module has both an `export = ns` and multiple top-level exports by stripping the export modifiers from
39947                         //  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
39948                         var excessExports = ts.filter(statements, function (s) { return !!(ts.getModifierFlags(s) & 1 /* Export */); });
39949                         if (ts.length(excessExports)) {
39950                             ns.body.statements = ts.createNodeArray(__spreadArrays(ns.body.statements, [ts.createExportDeclaration(
39951                                 /*decorators*/ undefined, 
39952                                 /*modifiers*/ undefined, ts.createNamedExports(ts.map(ts.flatMap(excessExports, function (e) { return getNamesOfDeclaration(e); }), function (id) { return ts.createExportSpecifier(/*alias*/ undefined, id); })), 
39953                                 /*moduleSpecifier*/ undefined)]));
39954                         }
39955                         // Pass 1: Flatten `export namespace _exports {} export = _exports;` so long as the `export=` only points at a single namespace declaration
39956                         if (!ts.find(statements, function (s) { return s !== ns && ts.nodeHasName(s, ns.name); })) {
39957                             results = [];
39958                             ts.forEach(ns.body.statements, function (s) {
39959                                 addResult(s, 0 /* None */); // Recalculates the ambient (and export, if applicable from above) flag
39960                             });
39961                             statements = __spreadArrays(ts.filter(statements, function (s) { return s !== ns && s !== exportAssignment; }), results);
39962                         }
39963                     }
39964                     return statements;
39965                 }
39966                 function mergeExportDeclarations(statements) {
39967                     // Pass 2: Combine all `export {}` declarations
39968                     var exports = ts.filter(statements, function (d) { return ts.isExportDeclaration(d) && !d.moduleSpecifier && !!d.exportClause && ts.isNamedExports(d.exportClause); });
39969                     if (ts.length(exports) > 1) {
39970                         var nonExports = ts.filter(statements, function (d) { return !ts.isExportDeclaration(d) || !!d.moduleSpecifier || !d.exportClause; });
39971                         statements = __spreadArrays(nonExports, [ts.createExportDeclaration(
39972                             /*decorators*/ undefined, 
39973                             /*modifiers*/ undefined, ts.createNamedExports(ts.flatMap(exports, function (e) { return ts.cast(e.exportClause, ts.isNamedExports).elements; })), 
39974                             /*moduleSpecifier*/ undefined)]);
39975                     }
39976                     // Pass 2b: Also combine all `export {} from "..."` declarations as needed
39977                     var reexports = ts.filter(statements, function (d) { return ts.isExportDeclaration(d) && !!d.moduleSpecifier && !!d.exportClause && ts.isNamedExports(d.exportClause); });
39978                     if (ts.length(reexports) > 1) {
39979                         var groups = ts.group(reexports, function (decl) { return ts.isStringLiteral(decl.moduleSpecifier) ? ">" + decl.moduleSpecifier.text : ">"; });
39980                         if (groups.length !== reexports.length) {
39981                             var _loop_8 = function (group_1) {
39982                                 if (group_1.length > 1) {
39983                                     // remove group members from statements and then merge group members and add back to statements
39984                                     statements = __spreadArrays(ts.filter(statements, function (s) { return group_1.indexOf(s) === -1; }), [
39985                                         ts.createExportDeclaration(
39986                                         /*decorators*/ undefined, 
39987                                         /*modifiers*/ undefined, ts.createNamedExports(ts.flatMap(group_1, function (e) { return ts.cast(e.exportClause, ts.isNamedExports).elements; })), group_1[0].moduleSpecifier)
39988                                     ]);
39989                                 }
39990                             };
39991                             for (var _i = 0, groups_1 = groups; _i < groups_1.length; _i++) {
39992                                 var group_1 = groups_1[_i];
39993                                 _loop_8(group_1);
39994                             }
39995                         }
39996                     }
39997                     return statements;
39998                 }
39999                 function inlineExportModifiers(statements) {
40000                     // Pass 3: Move all `export {}`'s to `export` modifiers where possible
40001                     var exportDecl = ts.find(statements, function (d) { return ts.isExportDeclaration(d) && !d.moduleSpecifier && !!d.exportClause; });
40002                     if (exportDecl && exportDecl.exportClause && ts.isNamedExports(exportDecl.exportClause)) {
40003                         var replacements = ts.mapDefined(exportDecl.exportClause.elements, function (e) {
40004                             if (!e.propertyName) {
40005                                 // export {name} - look thru `statements` for `name`, and if all results can take an `export` modifier, do so and filter it
40006                                 var associated = ts.filter(statements, function (s) { return ts.nodeHasName(s, e.name); });
40007                                 if (ts.length(associated) && ts.every(associated, canHaveExportModifier)) {
40008                                     ts.forEach(associated, addExportModifier);
40009                                     return undefined;
40010                                 }
40011                             }
40012                             return e;
40013                         });
40014                         if (!ts.length(replacements)) {
40015                             // all clauses removed, filter the export declaration
40016                             statements = ts.filter(statements, function (s) { return s !== exportDecl; });
40017                         }
40018                         else {
40019                             // some items filtered, others not - update the export declaration
40020                             // (mutating because why not, we're building a whole new tree here anyway)
40021                             exportDecl.exportClause.elements = ts.createNodeArray(replacements);
40022                         }
40023                     }
40024                     return statements;
40025                 }
40026                 function mergeRedundantStatements(statements) {
40027                     statements = flattenExportAssignedNamespace(statements);
40028                     statements = mergeExportDeclarations(statements);
40029                     statements = inlineExportModifiers(statements);
40030                     // 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
40031                     // declaration privacy is respected.
40032                     if (enclosingDeclaration &&
40033                         ((ts.isSourceFile(enclosingDeclaration) && ts.isExternalOrCommonJsModule(enclosingDeclaration)) || ts.isModuleDeclaration(enclosingDeclaration)) &&
40034                         (!ts.some(statements, ts.isExternalModuleIndicator) || (!ts.hasScopeMarker(statements) && ts.some(statements, ts.needsScopeMarker)))) {
40035                         statements.push(ts.createEmptyExports());
40036                     }
40037                     return statements;
40038                 }
40039                 function canHaveExportModifier(node) {
40040                     return ts.isEnumDeclaration(node) ||
40041                         ts.isVariableStatement(node) ||
40042                         ts.isFunctionDeclaration(node) ||
40043                         ts.isClassDeclaration(node) ||
40044                         (ts.isModuleDeclaration(node) && !ts.isExternalModuleAugmentation(node) && !ts.isGlobalScopeAugmentation(node)) ||
40045                         ts.isInterfaceDeclaration(node) ||
40046                         isTypeDeclaration(node);
40047                 }
40048                 function addExportModifier(statement) {
40049                     var flags = (ts.getModifierFlags(statement) | 1 /* Export */) & ~2 /* Ambient */;
40050                     statement.modifiers = ts.createNodeArray(ts.createModifiersFromModifierFlags(flags));
40051                     statement.modifierFlagsCache = 0;
40052                 }
40053                 function visitSymbolTable(symbolTable, suppressNewPrivateContext, propertyAsAlias) {
40054                     var oldDeferredPrivates = deferredPrivates;
40055                     if (!suppressNewPrivateContext) {
40056                         deferredPrivates = ts.createMap();
40057                     }
40058                     symbolTable.forEach(function (symbol) {
40059                         serializeSymbol(symbol, /*isPrivate*/ false, !!propertyAsAlias);
40060                     });
40061                     if (!suppressNewPrivateContext) {
40062                         // deferredPrivates will be filled up by visiting the symbol table
40063                         // And will continue to iterate as elements are added while visited `deferredPrivates`
40064                         // (As that's how a map iterator is defined to work)
40065                         deferredPrivates.forEach(function (symbol) {
40066                             serializeSymbol(symbol, /*isPrivate*/ true, !!propertyAsAlias);
40067                         });
40068                     }
40069                     deferredPrivates = oldDeferredPrivates;
40070                 }
40071                 function serializeSymbol(symbol, isPrivate, propertyAsAlias) {
40072                     // cache visited list based on merged symbol, since we want to use the unmerged top-level symbol, but
40073                     // still skip reserializing it if we encounter the merged product later on
40074                     var visitedSym = getMergedSymbol(symbol);
40075                     if (visitedSymbols.has("" + getSymbolId(visitedSym))) {
40076                         return; // Already printed
40077                     }
40078                     visitedSymbols.set("" + getSymbolId(visitedSym), true);
40079                     // Only actually serialize symbols within the correct enclosing declaration, otherwise do nothing with the out-of-context symbol
40080                     var skipMembershipCheck = !isPrivate; // We only call this on exported symbols when we know they're in the correct scope
40081                     if (skipMembershipCheck || (!!ts.length(symbol.declarations) && ts.some(symbol.declarations, function (d) { return !!ts.findAncestor(d, function (n) { return n === enclosingDeclaration; }); }))) {
40082                         var oldContext = context;
40083                         context = cloneNodeBuilderContext(context);
40084                         var result = serializeSymbolWorker(symbol, isPrivate, propertyAsAlias);
40085                         context = oldContext;
40086                         return result;
40087                     }
40088                 }
40089                 // Synthesize declarations for a symbol - might be an Interface, a Class, a Namespace, a Type, a Variable (const, let, or var), an Alias
40090                 // or a merge of some number of those.
40091                 // An interesting challenge is ensuring that when classes merge with namespaces and interfaces, is keeping
40092                 // each symbol in only one of the representations
40093                 // Also, synthesizing a default export of some kind
40094                 // If it's an alias: emit `export default ref`
40095                 // If it's a property: emit `export default _default` with a `_default` prop
40096                 // If it's a class/interface/function: emit a class/interface/function with a `default` modifier
40097                 // These forms can merge, eg (`export default 12; export default interface A {}`)
40098                 function serializeSymbolWorker(symbol, isPrivate, propertyAsAlias) {
40099                     var symbolName = ts.unescapeLeadingUnderscores(symbol.escapedName);
40100                     var isDefault = symbol.escapedName === "default" /* Default */;
40101                     if (!(context.flags & 131072 /* AllowAnonymousIdentifier */) && ts.isStringANonContextualKeyword(symbolName) && !isDefault) {
40102                         // 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` :(
40103                         context.encounteredError = true;
40104                         // TODO: Issue error via symbol tracker?
40105                         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
40106                     }
40107                     var needsPostExportDefault = isDefault && !!(symbol.flags & -113 /* ExportDoesNotSupportDefaultModifier */
40108                         || (symbol.flags & 16 /* Function */ && ts.length(getPropertiesOfType(getTypeOfSymbol(symbol))))) && !(symbol.flags & 2097152 /* Alias */); // An alias symbol should preclude needing to make an alias ourselves
40109                     if (needsPostExportDefault) {
40110                         isPrivate = true;
40111                     }
40112                     var modifierFlags = (!isPrivate ? 1 /* Export */ : 0) | (isDefault && !needsPostExportDefault ? 512 /* Default */ : 0);
40113                     var isConstMergedWithNS = symbol.flags & 1536 /* Module */ &&
40114                         symbol.flags & (2 /* BlockScopedVariable */ | 1 /* FunctionScopedVariable */ | 4 /* Property */) &&
40115                         symbol.escapedName !== "export=" /* ExportEquals */;
40116                     var isConstMergedWithNSPrintableAsSignatureMerge = isConstMergedWithNS && isTypeRepresentableAsFunctionNamespaceMerge(getTypeOfSymbol(symbol), symbol);
40117                     if (symbol.flags & (16 /* Function */ | 8192 /* Method */) || isConstMergedWithNSPrintableAsSignatureMerge) {
40118                         serializeAsFunctionNamespaceMerge(getTypeOfSymbol(symbol), symbol, getInternalSymbolName(symbol, symbolName), modifierFlags);
40119                     }
40120                     if (symbol.flags & 524288 /* TypeAlias */) {
40121                         serializeTypeAlias(symbol, symbolName, modifierFlags);
40122                     }
40123                     // Need to skip over export= symbols below - json source files get a single `Property` flagged
40124                     // symbol of name `export=` which needs to be handled like an alias. It's not great, but it is what it is.
40125                     if (symbol.flags & (2 /* BlockScopedVariable */ | 1 /* FunctionScopedVariable */ | 4 /* Property */)
40126                         && symbol.escapedName !== "export=" /* ExportEquals */
40127                         && !(symbol.flags & 4194304 /* Prototype */)
40128                         && !(symbol.flags & 32 /* Class */)
40129                         && !isConstMergedWithNSPrintableAsSignatureMerge) {
40130                         serializeVariableOrProperty(symbol, symbolName, isPrivate, needsPostExportDefault, propertyAsAlias, modifierFlags);
40131                     }
40132                     if (symbol.flags & 384 /* Enum */) {
40133                         serializeEnum(symbol, symbolName, modifierFlags);
40134                     }
40135                     if (symbol.flags & 32 /* Class */) {
40136                         if (symbol.flags & 4 /* Property */ && ts.isBinaryExpression(symbol.valueDeclaration.parent) && ts.isClassExpression(symbol.valueDeclaration.parent.right)) {
40137                             // Looks like a `module.exports.Sub = class {}` - if we serialize `symbol` as a class, the result will have no members,
40138                             // since the classiness is actually from the target of the effective alias the symbol is. yes. A BlockScopedVariable|Class|Property
40139                             // _really_ acts like an Alias, and none of a BlockScopedVariable, Class, or Property. This is the travesty of JS binding today.
40140                             serializeAsAlias(symbol, getInternalSymbolName(symbol, symbolName), modifierFlags);
40141                         }
40142                         else {
40143                             serializeAsClass(symbol, getInternalSymbolName(symbol, symbolName), modifierFlags);
40144                         }
40145                     }
40146                     if ((symbol.flags & (512 /* ValueModule */ | 1024 /* NamespaceModule */) && (!isConstMergedWithNS || isTypeOnlyNamespace(symbol))) || isConstMergedWithNSPrintableAsSignatureMerge) {
40147                         serializeModule(symbol, symbolName, modifierFlags);
40148                     }
40149                     if (symbol.flags & 64 /* Interface */) {
40150                         serializeInterface(symbol, symbolName, modifierFlags);
40151                     }
40152                     if (symbol.flags & 2097152 /* Alias */) {
40153                         serializeAsAlias(symbol, getInternalSymbolName(symbol, symbolName), modifierFlags);
40154                     }
40155                     if (symbol.flags & 4 /* Property */ && symbol.escapedName === "export=" /* ExportEquals */) {
40156                         serializeMaybeAliasAssignment(symbol);
40157                     }
40158                     if (symbol.flags & 8388608 /* ExportStar */) {
40159                         // synthesize export * from "moduleReference"
40160                         // Straightforward - only one thing to do - make an export declaration
40161                         for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) {
40162                             var node = _a[_i];
40163                             var resolvedModule = resolveExternalModuleName(node, node.moduleSpecifier);
40164                             if (!resolvedModule)
40165                                 continue;
40166                             addResult(ts.createExportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, /*exportClause*/ undefined, ts.createLiteral(getSpecifierForModuleSymbol(resolvedModule, context))), 0 /* None */);
40167                         }
40168                     }
40169                     if (needsPostExportDefault) {
40170                         addResult(ts.createExportAssignment(/*decorators*/ undefined, /*modifiers*/ undefined, /*isExportAssignment*/ false, ts.createIdentifier(getInternalSymbolName(symbol, symbolName))), 0 /* None */);
40171                     }
40172                 }
40173                 function includePrivateSymbol(symbol) {
40174                     if (ts.some(symbol.declarations, ts.isParameterDeclaration))
40175                         return;
40176                     ts.Debug.assertIsDefined(deferredPrivates);
40177                     getUnusedName(ts.unescapeLeadingUnderscores(symbol.escapedName), symbol); // Call to cache unique name for symbol
40178                     deferredPrivates.set("" + getSymbolId(symbol), symbol);
40179                 }
40180                 function isExportingScope(enclosingDeclaration) {
40181                     return ((ts.isSourceFile(enclosingDeclaration) && (ts.isExternalOrCommonJsModule(enclosingDeclaration) || ts.isJsonSourceFile(enclosingDeclaration))) ||
40182                         (ts.isAmbientModule(enclosingDeclaration) && !ts.isGlobalScopeAugmentation(enclosingDeclaration)));
40183                 }
40184                 // Prepends a `declare` and/or `export` modifier if the context requires it, and then adds `node` to `result` and returns `node`
40185                 // Note: This _mutates_ `node` without using `updateNode` - the assumption being that all nodes should be manufactured fresh by the node builder
40186                 function addResult(node, additionalModifierFlags) {
40187                     var newModifierFlags = 0 /* None */;
40188                     if (additionalModifierFlags & 1 /* Export */ &&
40189                         enclosingDeclaration &&
40190                         isExportingScope(enclosingDeclaration) &&
40191                         canHaveExportModifier(node)) {
40192                         // Classes, namespaces, variables, functions, interfaces, and types should all be `export`ed in a module context if not private
40193                         newModifierFlags |= 1 /* Export */;
40194                     }
40195                     if (addingDeclare && !(newModifierFlags & 1 /* Export */) &&
40196                         (!enclosingDeclaration || !(enclosingDeclaration.flags & 8388608 /* Ambient */)) &&
40197                         (ts.isEnumDeclaration(node) || ts.isVariableStatement(node) || ts.isFunctionDeclaration(node) || ts.isClassDeclaration(node) || ts.isModuleDeclaration(node))) {
40198                         // Classes, namespaces, variables, enums, and functions all need `declare` modifiers to be valid in a declaration file top-level scope
40199                         newModifierFlags |= 2 /* Ambient */;
40200                     }
40201                     if ((additionalModifierFlags & 512 /* Default */) && (ts.isClassDeclaration(node) || ts.isInterfaceDeclaration(node) || ts.isFunctionDeclaration(node))) {
40202                         newModifierFlags |= 512 /* Default */;
40203                     }
40204                     if (newModifierFlags) {
40205                         node.modifiers = ts.createNodeArray(ts.createModifiersFromModifierFlags(newModifierFlags | ts.getModifierFlags(node)));
40206                         node.modifierFlagsCache = 0; // Reset computed flags cache
40207                     }
40208                     results.push(node);
40209                 }
40210                 function serializeTypeAlias(symbol, symbolName, modifierFlags) {
40211                     var aliasType = getDeclaredTypeOfTypeAlias(symbol);
40212                     var typeParams = getSymbolLinks(symbol).typeParameters;
40213                     var typeParamDecls = ts.map(typeParams, function (p) { return typeParameterToDeclaration(p, context); });
40214                     var jsdocAliasDecl = ts.find(symbol.declarations, ts.isJSDocTypeAlias);
40215                     var commentText = jsdocAliasDecl ? jsdocAliasDecl.comment || jsdocAliasDecl.parent.comment : undefined;
40216                     var oldFlags = context.flags;
40217                     context.flags |= 8388608 /* InTypeAlias */;
40218                     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);
40219                     context.flags = oldFlags;
40220                 }
40221                 function serializeInterface(symbol, symbolName, modifierFlags) {
40222                     var interfaceType = getDeclaredTypeOfClassOrInterface(symbol);
40223                     var localParams = getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol);
40224                     var typeParamDecls = ts.map(localParams, function (p) { return typeParameterToDeclaration(p, context); });
40225                     var baseTypes = getBaseTypes(interfaceType);
40226                     var baseType = ts.length(baseTypes) ? getIntersectionType(baseTypes) : undefined;
40227                     var members = ts.flatMap(getPropertiesOfType(interfaceType), function (p) { return serializePropertySymbolForInterface(p, baseType); });
40228                     var callSignatures = serializeSignatures(0 /* Call */, interfaceType, baseType, 165 /* CallSignature */);
40229                     var constructSignatures = serializeSignatures(1 /* Construct */, interfaceType, baseType, 166 /* ConstructSignature */);
40230                     var indexSignatures = serializeIndexSignatures(interfaceType, baseType);
40231                     var heritageClauses = !ts.length(baseTypes) ? undefined : [ts.createHeritageClause(90 /* ExtendsKeyword */, ts.mapDefined(baseTypes, function (b) { return trySerializeAsTypeReference(b); }))];
40232                     addResult(ts.createInterfaceDeclaration(
40233                     /*decorators*/ undefined, 
40234                     /*modifiers*/ undefined, getInternalSymbolName(symbol, symbolName), typeParamDecls, heritageClauses, __spreadArrays(indexSignatures, constructSignatures, callSignatures, members)), modifierFlags);
40235                 }
40236                 function getNamespaceMembersForSerialization(symbol) {
40237                     return !symbol.exports ? [] : ts.filter(ts.arrayFrom(symbol.exports.values()), isNamespaceMember);
40238                 }
40239                 function isTypeOnlyNamespace(symbol) {
40240                     return ts.every(getNamespaceMembersForSerialization(symbol), function (m) { return !(resolveSymbol(m).flags & 111551 /* Value */); });
40241                 }
40242                 function serializeModule(symbol, symbolName, modifierFlags) {
40243                     var members = getNamespaceMembersForSerialization(symbol);
40244                     // 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)
40245                     var locationMap = ts.arrayToMultiMap(members, function (m) { return m.parent && m.parent === symbol ? "real" : "merged"; });
40246                     var realMembers = locationMap.get("real") || ts.emptyArray;
40247                     var mergedMembers = locationMap.get("merged") || ts.emptyArray;
40248                     // TODO: `suppressNewPrivateContext` is questionable -we need to simply be emitting privates in whatever scope they were declared in, rather
40249                     // 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,
40250                     // so we don't even have placeholders to fill in.
40251                     if (ts.length(realMembers)) {
40252                         var localName = getInternalSymbolName(symbol, symbolName);
40253                         serializeAsNamespaceDeclaration(realMembers, localName, modifierFlags, !!(symbol.flags & (16 /* Function */ | 67108864 /* Assignment */)));
40254                     }
40255                     if (ts.length(mergedMembers)) {
40256                         var containingFile_1 = ts.getSourceFileOfNode(context.enclosingDeclaration);
40257                         var localName = getInternalSymbolName(symbol, symbolName);
40258                         var nsBody = ts.createModuleBlock([ts.createExportDeclaration(
40259                             /*decorators*/ undefined, 
40260                             /*modifiers*/ undefined, ts.createNamedExports(ts.mapDefined(ts.filter(mergedMembers, function (n) { return n.escapedName !== "export=" /* ExportEquals */; }), function (s) {
40261                                 var _a, _b;
40262                                 var name = ts.unescapeLeadingUnderscores(s.escapedName);
40263                                 var localName = getInternalSymbolName(s, name);
40264                                 var aliasDecl = s.declarations && getDeclarationOfAliasSymbol(s);
40265                                 if (containingFile_1 && (aliasDecl ? containingFile_1 !== ts.getSourceFileOfNode(aliasDecl) : !ts.some(s.declarations, function (d) { return ts.getSourceFileOfNode(d) === containingFile_1; }))) {
40266                                     (_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);
40267                                     return undefined;
40268                                 }
40269                                 var target = aliasDecl && getTargetOfAliasDeclaration(aliasDecl, /*dontRecursivelyResolve*/ true);
40270                                 includePrivateSymbol(target || s);
40271                                 var targetName = target ? getInternalSymbolName(target, ts.unescapeLeadingUnderscores(target.escapedName)) : localName;
40272                                 return ts.createExportSpecifier(name === targetName ? undefined : targetName, name);
40273                             })))]);
40274                         addResult(ts.createModuleDeclaration(
40275                         /*decorators*/ undefined, 
40276                         /*modifiers*/ undefined, ts.createIdentifier(localName), nsBody, 16 /* Namespace */), 0 /* None */);
40277                     }
40278                 }
40279                 function serializeEnum(symbol, symbolName, modifierFlags) {
40280                     addResult(ts.createEnumDeclaration(
40281                     /*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) {
40282                         // TODO: Handle computed names
40283                         // I hate that to get the initialized value we need to walk back to the declarations here; but there's no
40284                         // other way to get the possible const value of an enum member that I'm aware of, as the value is cached
40285                         // _on the declaration_, not on the declaration's symbol...
40286                         var initializedValue = p.declarations && p.declarations[0] && ts.isEnumMember(p.declarations[0]) && getConstantValue(p.declarations[0]);
40287                         return ts.createEnumMember(ts.unescapeLeadingUnderscores(p.escapedName), initializedValue === undefined ? undefined : ts.createLiteral(initializedValue));
40288                     })), modifierFlags);
40289                 }
40290                 function serializeVariableOrProperty(symbol, symbolName, isPrivate, needsPostExportDefault, propertyAsAlias, modifierFlags) {
40291                     if (propertyAsAlias) {
40292                         serializeMaybeAliasAssignment(symbol);
40293                     }
40294                     else {
40295                         var type = getTypeOfSymbol(symbol);
40296                         var localName = getInternalSymbolName(symbol, symbolName);
40297                         if (!(symbol.flags & 16 /* Function */) && isTypeRepresentableAsFunctionNamespaceMerge(type, symbol)) {
40298                             // 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
40299                             serializeAsFunctionNamespaceMerge(type, symbol, localName, modifierFlags);
40300                         }
40301                         else {
40302                             // 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!_
40303                             // `var` is `FunctionScopedVariable`, `const` and `let` are `BlockScopedVariable`, and `module.exports.thing =` is `Property`
40304                             var flags = !(symbol.flags & 2 /* BlockScopedVariable */) ? undefined
40305                                 : isConstVariable(symbol) ? 2 /* Const */
40306                                     : 1 /* Let */;
40307                             var name = (needsPostExportDefault || !(symbol.flags & 4 /* Property */)) ? localName : getUnusedName(localName, symbol);
40308                             var textRange = symbol.declarations && ts.find(symbol.declarations, function (d) { return ts.isVariableDeclaration(d); });
40309                             if (textRange && ts.isVariableDeclarationList(textRange.parent) && textRange.parent.declarations.length === 1) {
40310                                 textRange = textRange.parent.parent;
40311                             }
40312                             var statement = ts.setTextRange(ts.createVariableStatement(/*modifiers*/ undefined, ts.createVariableDeclarationList([
40313                                 ts.createVariableDeclaration(name, serializeTypeForDeclaration(context, type, symbol, enclosingDeclaration, includePrivateSymbol, bundled))
40314                             ], flags)), textRange);
40315                             addResult(statement, name !== localName ? modifierFlags & ~1 /* Export */ : modifierFlags);
40316                             if (name !== localName && !isPrivate) {
40317                                 // We rename the variable declaration we generate for Property symbols since they may have a name which
40318                                 // conflicts with a local declaration. For example, given input:
40319                                 // ```
40320                                 // function g() {}
40321                                 // module.exports.g = g
40322                                 // ```
40323                                 // In such a situation, we have a local variable named `g`, and a separate exported variable named `g`.
40324                                 // Naively, we would emit
40325                                 // ```
40326                                 // function g() {}
40327                                 // export const g: typeof g;
40328                                 // ```
40329                                 // That's obviously incorrect - the `g` in the type annotation needs to refer to the local `g`, but
40330                                 // the export declaration shadows it.
40331                                 // To work around that, we instead write
40332                                 // ```
40333                                 // function g() {}
40334                                 // const g_1: typeof g;
40335                                 // export { g_1 as g };
40336                                 // ```
40337                                 // To create an export named `g` that does _not_ shadow the local `g`
40338                                 addResult(ts.createExportDeclaration(
40339                                 /*decorators*/ undefined, 
40340                                 /*modifiers*/ undefined, ts.createNamedExports([ts.createExportSpecifier(name, localName)])), 0 /* None */);
40341                             }
40342                         }
40343                     }
40344                 }
40345                 function serializeAsFunctionNamespaceMerge(type, symbol, localName, modifierFlags) {
40346                     var signatures = getSignaturesOfType(type, 0 /* Call */);
40347                     for (var _i = 0, signatures_2 = signatures; _i < signatures_2.length; _i++) {
40348                         var sig = signatures_2[_i];
40349                         // Each overload becomes a separate function declaration, in order
40350                         var decl = signatureToSignatureDeclarationHelper(sig, 244 /* FunctionDeclaration */, context, includePrivateSymbol, bundled);
40351                         decl.name = ts.createIdentifier(localName);
40352                         // for expressions assigned to `var`s, use the `var` as the text range
40353                         addResult(ts.setTextRange(decl, sig.declaration && ts.isVariableDeclaration(sig.declaration.parent) && sig.declaration.parent.parent || sig.declaration), modifierFlags);
40354                     }
40355                     // Module symbol emit will take care of module-y members, provided it has exports
40356                     if (!(symbol.flags & (512 /* ValueModule */ | 1024 /* NamespaceModule */) && !!symbol.exports && !!symbol.exports.size)) {
40357                         var props = ts.filter(getPropertiesOfType(type), isNamespaceMember);
40358                         serializeAsNamespaceDeclaration(props, localName, modifierFlags, /*suppressNewPrivateContext*/ true);
40359                     }
40360                 }
40361                 function serializeAsNamespaceDeclaration(props, localName, modifierFlags, suppressNewPrivateContext) {
40362                     if (ts.length(props)) {
40363                         var localVsRemoteMap = ts.arrayToMultiMap(props, function (p) {
40364                             return !ts.length(p.declarations) || ts.some(p.declarations, function (d) {
40365                                 return ts.getSourceFileOfNode(d) === ts.getSourceFileOfNode(context.enclosingDeclaration);
40366                             }) ? "local" : "remote";
40367                         });
40368                         var localProps = localVsRemoteMap.get("local") || ts.emptyArray;
40369                         // handle remote props first - we need to make an `import` declaration that points at the module containing each remote
40370                         // prop in the outermost scope (TODO: a namespace within a namespace would need to be appropriately handled by this)
40371                         // Example:
40372                         // import Foo_1 = require("./exporter");
40373                         // export namespace ns {
40374                         //     import Foo = Foo_1.Foo;
40375                         //     export { Foo };
40376                         //     export const c: number;
40377                         // }
40378                         // This is needed because in JS, statements like `const x = require("./f")` support both type and value lookup, even if they're
40379                         // normally just value lookup (so it functions kinda like an alias even when it's not an alias)
40380                         // _Usually_, we'll simply print the top-level as an alias instead of a `var` in such situations, however is is theoretically
40381                         // possible to encounter a situation where a type has members from both the current file and other files - in those situations,
40382                         // emit akin to the above would be needed.
40383                         // Add a namespace
40384                         var fakespace = ts.createModuleDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, ts.createIdentifier(localName), ts.createModuleBlock([]), 16 /* Namespace */);
40385                         fakespace.flags ^= 8 /* Synthesized */; // unset synthesized so it is usable as an enclosing declaration
40386                         fakespace.parent = enclosingDeclaration;
40387                         fakespace.locals = ts.createSymbolTable(props);
40388                         fakespace.symbol = props[0].parent;
40389                         var oldResults = results;
40390                         results = [];
40391                         var oldAddingDeclare = addingDeclare;
40392                         addingDeclare = false;
40393                         var subcontext = __assign(__assign({}, context), { enclosingDeclaration: fakespace });
40394                         var oldContext = context;
40395                         context = subcontext;
40396                         // 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
40397                         visitSymbolTable(ts.createSymbolTable(localProps), suppressNewPrivateContext, /*propertyAsAlias*/ true);
40398                         context = oldContext;
40399                         addingDeclare = oldAddingDeclare;
40400                         var declarations = results;
40401                         results = oldResults;
40402                         fakespace.flags ^= 8 /* Synthesized */; // reset synthesized
40403                         fakespace.parent = undefined;
40404                         fakespace.locals = undefined;
40405                         fakespace.symbol = undefined;
40406                         fakespace.body = ts.createModuleBlock(declarations);
40407                         addResult(fakespace, modifierFlags); // namespaces can never be default exported
40408                     }
40409                 }
40410                 function isNamespaceMember(p) {
40411                     return !(p.flags & 4194304 /* Prototype */ || p.escapedName === "prototype" || p.valueDeclaration && ts.isClassLike(p.valueDeclaration.parent));
40412                 }
40413                 function serializeAsClass(symbol, localName, modifierFlags) {
40414                     var localParams = getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol);
40415                     var typeParamDecls = ts.map(localParams, function (p) { return typeParameterToDeclaration(p, context); });
40416                     var classType = getDeclaredTypeOfClassOrInterface(symbol);
40417                     var baseTypes = getBaseTypes(classType);
40418                     var implementsTypes = getImplementsTypes(classType);
40419                     var staticType = getTypeOfSymbol(symbol);
40420                     var staticBaseType = getBaseConstructorTypeOfClass(staticType);
40421                     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); }))]);
40422                     var symbolProps = getNonInterhitedProperties(classType, baseTypes, getPropertiesOfType(classType));
40423                     var publicSymbolProps = ts.filter(symbolProps, function (s) {
40424                         // `valueDeclaration` could be undefined if inherited from
40425                         // a union/intersection base type, but inherited properties
40426                         // don't matter here.
40427                         var valueDecl = s.valueDeclaration;
40428                         return valueDecl && !(ts.isNamedDeclaration(valueDecl) && ts.isPrivateIdentifier(valueDecl.name));
40429                     });
40430                     var hasPrivateIdentifier = ts.some(symbolProps, function (s) {
40431                         // `valueDeclaration` could be undefined if inherited from
40432                         // a union/intersection base type, but inherited properties
40433                         // don't matter here.
40434                         var valueDecl = s.valueDeclaration;
40435                         return valueDecl && ts.isNamedDeclaration(valueDecl) && ts.isPrivateIdentifier(valueDecl.name);
40436                     });
40437                     // Boil down all private properties into a single one.
40438                     var privateProperties = hasPrivateIdentifier ?
40439                         [ts.createProperty(
40440                             /*decorators*/ undefined, 
40441                             /*modifiers*/ undefined, ts.createPrivateIdentifier("#private"), 
40442                             /*questionOrExclamationToken*/ undefined, 
40443                             /*type*/ undefined, 
40444                             /*initializer*/ undefined)] :
40445                         ts.emptyArray;
40446                     var publicProperties = ts.flatMap(publicSymbolProps, function (p) { return serializePropertySymbolForClass(p, /*isStatic*/ false, baseTypes[0]); });
40447                     // Consider static members empty if symbol also has function or module meaning - function namespacey emit will handle statics
40448                     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); });
40449                     var constructors = serializeSignatures(1 /* Construct */, staticType, baseTypes[0], 162 /* Constructor */);
40450                     for (var _i = 0, constructors_1 = constructors; _i < constructors_1.length; _i++) {
40451                         var c = constructors_1[_i];
40452                         // A constructor's return type and type parameters are supposed to be controlled by the enclosing class declaration
40453                         // `signatureToSignatureDeclarationHelper` appends them regardless, so for now we delete them here
40454                         c.type = undefined;
40455                         c.typeParameters = undefined;
40456                     }
40457                     var indexSignatures = serializeIndexSignatures(classType, baseTypes[0]);
40458                     addResult(ts.setTextRange(ts.createClassDeclaration(
40459                     /*decorators*/ undefined, 
40460                     /*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);
40461                 }
40462                 function serializeAsAlias(symbol, localName, modifierFlags) {
40463                     // synthesize an alias, eg `export { symbolName as Name }`
40464                     // need to mark the alias `symbol` points at
40465                     // as something we need to serialize as a private declaration as well
40466                     var node = getDeclarationOfAliasSymbol(symbol);
40467                     if (!node)
40468                         return ts.Debug.fail();
40469                     var target = getMergedSymbol(getTargetOfAliasDeclaration(node, /*dontRecursivelyResolve*/ true));
40470                     if (!target) {
40471                         return;
40472                     }
40473                     var verbatimTargetName = ts.unescapeLeadingUnderscores(target.escapedName);
40474                     if (verbatimTargetName === "export=" /* ExportEquals */ && (compilerOptions.esModuleInterop || compilerOptions.allowSyntheticDefaultImports)) {
40475                         // target refers to an `export=` symbol that was hoisted into a synthetic default - rename here to match
40476                         verbatimTargetName = "default" /* Default */;
40477                     }
40478                     var targetName = getInternalSymbolName(target, verbatimTargetName);
40479                     includePrivateSymbol(target); // the target may be within the same scope - attempt to serialize it first
40480                     switch (node.kind) {
40481                         case 253 /* ImportEqualsDeclaration */:
40482                             // Could be a local `import localName = ns.member` or
40483                             // an external `import localName = require("whatever")`
40484                             var isLocalImport = !(target.flags & 512 /* ValueModule */);
40485                             addResult(ts.createImportEqualsDeclaration(
40486                             /*decorators*/ undefined, 
40487                             /*modifiers*/ undefined, ts.createIdentifier(localName), isLocalImport
40488                                 ? symbolToName(target, context, 67108863 /* All */, /*expectsIdentifier*/ false)
40489                                 : ts.createExternalModuleReference(ts.createLiteral(getSpecifierForModuleSymbol(symbol, context)))), isLocalImport ? modifierFlags : 0 /* None */);
40490                             break;
40491                         case 252 /* NamespaceExportDeclaration */:
40492                             // export as namespace foo
40493                             // TODO: Not part of a file's local or export symbol tables
40494                             // Is bound into file.symbol.globalExports instead, which we don't currently traverse
40495                             addResult(ts.createNamespaceExportDeclaration(ts.idText(node.name)), 0 /* None */);
40496                             break;
40497                         case 255 /* ImportClause */:
40498                             addResult(ts.createImportDeclaration(
40499                             /*decorators*/ undefined, 
40500                             /*modifiers*/ undefined, ts.createImportClause(ts.createIdentifier(localName), /*namedBindings*/ undefined), 
40501                             // We use `target.parent || target` below as `target.parent` is unset when the target is a module which has been export assigned
40502                             // And then made into a default by the `esModuleInterop` or `allowSyntheticDefaultImports` flag
40503                             // In such cases, the `target` refers to the module itself already
40504                             ts.createLiteral(getSpecifierForModuleSymbol(target.parent || target, context))), 0 /* None */);
40505                             break;
40506                         case 256 /* NamespaceImport */:
40507                             addResult(ts.createImportDeclaration(
40508                             /*decorators*/ undefined, 
40509                             /*modifiers*/ undefined, ts.createImportClause(/*importClause*/ undefined, ts.createNamespaceImport(ts.createIdentifier(localName))), ts.createLiteral(getSpecifierForModuleSymbol(target, context))), 0 /* None */);
40510                             break;
40511                         case 262 /* NamespaceExport */:
40512                             addResult(ts.createExportDeclaration(
40513                             /*decorators*/ undefined, 
40514                             /*modifiers*/ undefined, ts.createNamespaceExport(ts.createIdentifier(localName)), ts.createLiteral(getSpecifierForModuleSymbol(target, context))), 0 /* None */);
40515                             break;
40516                         case 258 /* ImportSpecifier */:
40517                             addResult(ts.createImportDeclaration(
40518                             /*decorators*/ undefined, 
40519                             /*modifiers*/ undefined, ts.createImportClause(/*importClause*/ undefined, ts.createNamedImports([
40520                                 ts.createImportSpecifier(localName !== verbatimTargetName ? ts.createIdentifier(verbatimTargetName) : undefined, ts.createIdentifier(localName))
40521                             ])), ts.createLiteral(getSpecifierForModuleSymbol(target.parent || target, context))), 0 /* None */);
40522                             break;
40523                         case 263 /* ExportSpecifier */:
40524                             // does not use localName because the symbol name in this case refers to the name in the exports table,
40525                             // which we must exactly preserve
40526                             var specifier = node.parent.parent.moduleSpecifier;
40527                             // targetName is only used when the target is local, as otherwise the target is an alias that points at
40528                             // another file
40529                             serializeExportSpecifier(ts.unescapeLeadingUnderscores(symbol.escapedName), specifier ? verbatimTargetName : targetName, specifier && ts.isStringLiteralLike(specifier) ? ts.createLiteral(specifier.text) : undefined);
40530                             break;
40531                         case 259 /* ExportAssignment */:
40532                             serializeMaybeAliasAssignment(symbol);
40533                             break;
40534                         case 209 /* BinaryExpression */:
40535                         case 194 /* PropertyAccessExpression */:
40536                             // Could be best encoded as though an export specifier or as though an export assignment
40537                             // If name is default or export=, do an export assignment
40538                             // Otherwise do an export specifier
40539                             if (symbol.escapedName === "default" /* Default */ || symbol.escapedName === "export=" /* ExportEquals */) {
40540                                 serializeMaybeAliasAssignment(symbol);
40541                             }
40542                             else {
40543                                 serializeExportSpecifier(localName, targetName);
40544                             }
40545                             break;
40546                         default:
40547                             return ts.Debug.failBadSyntaxKind(node, "Unhandled alias declaration kind in symbol serializer!");
40548                     }
40549                 }
40550                 function serializeExportSpecifier(localName, targetName, specifier) {
40551                     addResult(ts.createExportDeclaration(
40552                     /*decorators*/ undefined, 
40553                     /*modifiers*/ undefined, ts.createNamedExports([ts.createExportSpecifier(localName !== targetName ? targetName : undefined, localName)]), specifier), 0 /* None */);
40554                 }
40555                 function serializeMaybeAliasAssignment(symbol) {
40556                     if (symbol.flags & 4194304 /* Prototype */) {
40557                         return;
40558                     }
40559                     var name = ts.unescapeLeadingUnderscores(symbol.escapedName);
40560                     var isExportEquals = name === "export=" /* ExportEquals */;
40561                     var isDefault = name === "default" /* Default */;
40562                     var isExportAssignment = isExportEquals || isDefault;
40563                     // synthesize export = ref
40564                     // ref should refer to either be a locally scoped symbol which we need to emit, or
40565                     // a reference to another namespace/module which we may need to emit an `import` statement for
40566                     var aliasDecl = symbol.declarations && getDeclarationOfAliasSymbol(symbol);
40567                     // serialize what the alias points to, preserve the declaration's initializer
40568                     var target = aliasDecl && getTargetOfAliasDeclaration(aliasDecl, /*dontRecursivelyResolve*/ true);
40569                     // If the target resolves and resolves to a thing defined in this file, emit as an alias, otherwise emit as a const
40570                     if (target && ts.length(target.declarations) && ts.some(target.declarations, function (d) { return ts.getSourceFileOfNode(d) === ts.getSourceFileOfNode(enclosingDeclaration); })) {
40571                         // In case `target` refers to a namespace member, look at the declaration and serialize the leftmost symbol in it
40572                         // eg, `namespace A { export class B {} }; exports = A.B;`
40573                         // Technically, this is all that's required in the case where the assignment is an entity name expression
40574                         var expr = isExportAssignment ? ts.getExportAssignmentExpression(aliasDecl) : ts.getPropertyAssignmentAliasLikeExpression(aliasDecl);
40575                         var first_1 = ts.isEntityNameExpression(expr) ? getFirstNonModuleExportsIdentifier(expr) : undefined;
40576                         var referenced = first_1 && resolveEntityName(first_1, 67108863 /* All */, /*ignoreErrors*/ true, /*dontResolveAlias*/ true, enclosingDeclaration);
40577                         if (referenced || target) {
40578                             includePrivateSymbol(referenced || target);
40579                         }
40580                         // We disable the context's symbol tracker for the duration of this name serialization
40581                         // as, by virtue of being here, the name is required to print something, and we don't want to
40582                         // issue a visibility error on it. Only anonymous classes that an alias points at _would_ issue
40583                         // a visibility error here (as they're not visible within any scope), but we want to hoist them
40584                         // into the containing scope anyway, so we want to skip the visibility checks.
40585                         var oldTrack = context.tracker.trackSymbol;
40586                         context.tracker.trackSymbol = ts.noop;
40587                         if (isExportAssignment) {
40588                             results.push(ts.createExportAssignment(
40589                             /*decorators*/ undefined, 
40590                             /*modifiers*/ undefined, isExportEquals, symbolToExpression(target, context, 67108863 /* All */)));
40591                         }
40592                         else {
40593                             if (first_1 === expr) {
40594                                 // serialize as `export {target as name}`
40595                                 serializeExportSpecifier(name, ts.idText(first_1));
40596                             }
40597                             else if (ts.isClassExpression(expr)) {
40598                                 serializeExportSpecifier(name, getInternalSymbolName(target, ts.symbolName(target)));
40599                             }
40600                             else {
40601                                 // serialize as `import _Ref = t.arg.et; export { _Ref as name }`
40602                                 var varName = getUnusedName(name, symbol);
40603                                 addResult(ts.createImportEqualsDeclaration(
40604                                 /*decorators*/ undefined, 
40605                                 /*modifiers*/ undefined, ts.createIdentifier(varName), symbolToName(target, context, 67108863 /* All */, /*expectsIdentifier*/ false)), 0 /* None */);
40606                                 serializeExportSpecifier(name, varName);
40607                             }
40608                         }
40609                         context.tracker.trackSymbol = oldTrack;
40610                     }
40611                     else {
40612                         // serialize as an anonymous property declaration
40613                         var varName = getUnusedName(name, symbol);
40614                         // We have to use `getWidenedType` here since the object within a json file is unwidened within the file
40615                         // (Unwidened types can only exist in expression contexts and should never be serialized)
40616                         var typeToSerialize = getWidenedType(getTypeOfSymbol(getMergedSymbol(symbol)));
40617                         if (isTypeRepresentableAsFunctionNamespaceMerge(typeToSerialize, symbol)) {
40618                             // If there are no index signatures and `typeToSerialize` is an object type, emit as a namespace instead of a const
40619                             serializeAsFunctionNamespaceMerge(typeToSerialize, symbol, varName, isExportAssignment ? 0 /* None */ : 1 /* Export */);
40620                         }
40621                         else {
40622                             var statement = ts.createVariableStatement(/*modifiers*/ undefined, ts.createVariableDeclarationList([
40623                                 ts.createVariableDeclaration(varName, serializeTypeForDeclaration(context, typeToSerialize, symbol, enclosingDeclaration, includePrivateSymbol, bundled))
40624                             ], 2 /* Const */));
40625                             addResult(statement, name === varName ? 1 /* Export */ : 0 /* None */);
40626                         }
40627                         if (isExportAssignment) {
40628                             results.push(ts.createExportAssignment(
40629                             /*decorators*/ undefined, 
40630                             /*modifiers*/ undefined, isExportEquals, ts.createIdentifier(varName)));
40631                         }
40632                         else if (name !== varName) {
40633                             serializeExportSpecifier(name, varName);
40634                         }
40635                     }
40636                 }
40637                 function isTypeRepresentableAsFunctionNamespaceMerge(typeToSerialize, hostSymbol) {
40638                     // Only object types which are not constructable, or indexable, whose members all come from the
40639                     // context source file, and whose property names are all valid identifiers and not late-bound, _and_
40640                     // whose input is not type annotated (if the input symbol has an annotation we can reuse, we should prefer it)
40641                     var ctxSrc = ts.getSourceFileOfNode(context.enclosingDeclaration);
40642                     return ts.getObjectFlags(typeToSerialize) & (16 /* Anonymous */ | 32 /* Mapped */) &&
40643                         !getIndexInfoOfType(typeToSerialize, 0 /* String */) &&
40644                         !getIndexInfoOfType(typeToSerialize, 1 /* Number */) &&
40645                         !!(ts.length(getPropertiesOfType(typeToSerialize)) || ts.length(getSignaturesOfType(typeToSerialize, 0 /* Call */))) &&
40646                         !ts.length(getSignaturesOfType(typeToSerialize, 1 /* Construct */)) && // TODO: could probably serialize as function + ns + class, now that that's OK
40647                         !getDeclarationWithTypeAnnotation(hostSymbol, enclosingDeclaration) &&
40648                         !(typeToSerialize.symbol && ts.some(typeToSerialize.symbol.declarations, function (d) { return ts.getSourceFileOfNode(d) !== ctxSrc; })) &&
40649                         !ts.some(getPropertiesOfType(typeToSerialize), function (p) { return isLateBoundName(p.escapedName); }) &&
40650                         !ts.some(getPropertiesOfType(typeToSerialize), function (p) { return ts.some(p.declarations, function (d) { return ts.getSourceFileOfNode(d) !== ctxSrc; }); }) &&
40651                         ts.every(getPropertiesOfType(typeToSerialize), function (p) { return ts.isIdentifierText(ts.symbolName(p), languageVersion) && !ts.isStringAKeyword(ts.symbolName(p)); });
40652                 }
40653                 function makeSerializePropertySymbol(createProperty, methodKind, useAccessors) {
40654                     return function serializePropertySymbol(p, isStatic, baseType) {
40655                         var modifierFlags = ts.getDeclarationModifierFlagsFromSymbol(p);
40656                         var isPrivate = !!(modifierFlags & 8 /* Private */);
40657                         if (isStatic && (p.flags & (788968 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */))) {
40658                             // Only value-only-meaning symbols can be correctly encoded as class statics, type/namespace/alias meaning symbols
40659                             // need to be merged namespace members
40660                             return [];
40661                         }
40662                         if (p.flags & 4194304 /* Prototype */ ||
40663                             (baseType && getPropertyOfType(baseType, p.escapedName)
40664                                 && isReadonlySymbol(getPropertyOfType(baseType, p.escapedName)) === isReadonlySymbol(p)
40665                                 && (p.flags & 16777216 /* Optional */) === (getPropertyOfType(baseType, p.escapedName).flags & 16777216 /* Optional */)
40666                                 && isTypeIdenticalTo(getTypeOfSymbol(p), getTypeOfPropertyOfType(baseType, p.escapedName)))) {
40667                             return [];
40668                         }
40669                         var flag = (modifierFlags & ~256 /* Async */) | (isStatic ? 32 /* Static */ : 0);
40670                         var name = getPropertyNameNodeForSymbol(p, context);
40671                         var firstPropertyLikeDecl = ts.find(p.declarations, ts.or(ts.isPropertyDeclaration, ts.isAccessor, ts.isVariableDeclaration, ts.isPropertySignature, ts.isBinaryExpression, ts.isPropertyAccessExpression));
40672                         if (p.flags & 98304 /* Accessor */ && useAccessors) {
40673                             var result = [];
40674                             if (p.flags & 65536 /* SetAccessor */) {
40675                                 result.push(ts.setTextRange(ts.createSetAccessor(
40676                                 /*decorators*/ undefined, ts.createModifiersFromModifierFlags(flag), name, [ts.createParameter(
40677                                     /*decorators*/ undefined, 
40678                                     /*modifiers*/ undefined, 
40679                                     /*dotDotDotToken*/ undefined, "arg", 
40680                                     /*questionToken*/ undefined, isPrivate ? undefined : serializeTypeForDeclaration(context, getTypeOfSymbol(p), p, enclosingDeclaration, includePrivateSymbol, bundled))], 
40681                                 /*body*/ undefined), ts.find(p.declarations, ts.isSetAccessor) || firstPropertyLikeDecl));
40682                             }
40683                             if (p.flags & 32768 /* GetAccessor */) {
40684                                 var isPrivate_1 = modifierFlags & 8 /* Private */;
40685                                 result.push(ts.setTextRange(ts.createGetAccessor(
40686                                 /*decorators*/ undefined, ts.createModifiersFromModifierFlags(flag), name, [], isPrivate_1 ? undefined : serializeTypeForDeclaration(context, getTypeOfSymbol(p), p, enclosingDeclaration, includePrivateSymbol, bundled), 
40687                                 /*body*/ undefined), ts.find(p.declarations, ts.isGetAccessor) || firstPropertyLikeDecl));
40688                             }
40689                             return result;
40690                         }
40691                         // This is an else/if as accessors and properties can't merge in TS, but might in JS
40692                         // If this happens, we assume the accessor takes priority, as it imposes more constraints
40693                         else if (p.flags & (4 /* Property */ | 3 /* Variable */)) {
40694                             return ts.setTextRange(createProperty(
40695                             /*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), 
40696                             // TODO: https://github.com/microsoft/TypeScript/pull/32372#discussion_r328386357
40697                             // interface members can't have initializers, however class members _can_
40698                             /*initializer*/ undefined), ts.find(p.declarations, ts.or(ts.isPropertyDeclaration, ts.isVariableDeclaration)) || firstPropertyLikeDecl);
40699                         }
40700                         if (p.flags & (8192 /* Method */ | 16 /* Function */)) {
40701                             var type = getTypeOfSymbol(p);
40702                             var signatures = getSignaturesOfType(type, 0 /* Call */);
40703                             if (flag & 8 /* Private */) {
40704                                 return ts.setTextRange(createProperty(
40705                                 /*decorators*/ undefined, ts.createModifiersFromModifierFlags((isReadonlySymbol(p) ? 64 /* Readonly */ : 0) | flag), name, p.flags & 16777216 /* Optional */ ? ts.createToken(57 /* QuestionToken */) : undefined, 
40706                                 /*type*/ undefined, 
40707                                 /*initializer*/ undefined), ts.find(p.declarations, ts.isFunctionLikeDeclaration) || signatures[0] && signatures[0].declaration || p.declarations[0]);
40708                             }
40709                             var results_1 = [];
40710                             for (var _i = 0, signatures_3 = signatures; _i < signatures_3.length; _i++) {
40711                                 var sig = signatures_3[_i];
40712                                 // Each overload becomes a separate method declaration, in order
40713                                 var decl = signatureToSignatureDeclarationHelper(sig, methodKind, context);
40714                                 decl.name = name; // TODO: Clone
40715                                 if (flag) {
40716                                     decl.modifiers = ts.createNodeArray(ts.createModifiersFromModifierFlags(flag));
40717                                 }
40718                                 if (p.flags & 16777216 /* Optional */) {
40719                                     decl.questionToken = ts.createToken(57 /* QuestionToken */);
40720                                 }
40721                                 results_1.push(ts.setTextRange(decl, sig.declaration));
40722                             }
40723                             return results_1;
40724                         }
40725                         // The `Constructor`'s symbol isn't in the class's properties lists, obviously, since it's a signature on the static
40726                         return ts.Debug.fail("Unhandled class member kind! " + (p.__debugFlags || p.flags));
40727                     };
40728                 }
40729                 function serializePropertySymbolForInterface(p, baseType) {
40730                     return serializePropertySymbolForInterfaceWorker(p, /*isStatic*/ false, baseType);
40731                 }
40732                 function serializeSignatures(kind, input, baseType, outputKind) {
40733                     var signatures = getSignaturesOfType(input, kind);
40734                     if (kind === 1 /* Construct */) {
40735                         if (!baseType && ts.every(signatures, function (s) { return ts.length(s.parameters) === 0; })) {
40736                             return []; // No base type, every constructor is empty - elide the extraneous `constructor()`
40737                         }
40738                         if (baseType) {
40739                             // If there is a base type, if every signature in the class is identical to a signature in the baseType, elide all the declarations
40740                             var baseSigs = getSignaturesOfType(baseType, 1 /* Construct */);
40741                             if (!ts.length(baseSigs) && ts.every(signatures, function (s) { return ts.length(s.parameters) === 0; })) {
40742                                 return []; // Base had no explicit signatures, if all our signatures are also implicit, return an empty list
40743                             }
40744                             if (baseSigs.length === signatures.length) {
40745                                 var failed = false;
40746                                 for (var i = 0; i < baseSigs.length; i++) {
40747                                     if (!compareSignaturesIdentical(signatures[i], baseSigs[i], /*partialMatch*/ false, /*ignoreThisTypes*/ false, /*ignoreReturnTypes*/ true, compareTypesIdentical)) {
40748                                         failed = true;
40749                                         break;
40750                                     }
40751                                 }
40752                                 if (!failed) {
40753                                     return []; // Every signature was identical - elide constructor list as it is inherited
40754                                 }
40755                             }
40756                         }
40757                         var privateProtected = 0;
40758                         for (var _i = 0, signatures_4 = signatures; _i < signatures_4.length; _i++) {
40759                             var s = signatures_4[_i];
40760                             if (s.declaration) {
40761                                 privateProtected |= ts.getSelectedModifierFlags(s.declaration, 8 /* Private */ | 16 /* Protected */);
40762                             }
40763                         }
40764                         if (privateProtected) {
40765                             return [ts.setTextRange(ts.createConstructor(
40766                                 /*decorators*/ undefined, ts.createModifiersFromModifierFlags(privateProtected), 
40767                                 /*parameters*/ [], 
40768                                 /*body*/ undefined), signatures[0].declaration)];
40769                         }
40770                     }
40771                     var results = [];
40772                     for (var _a = 0, signatures_5 = signatures; _a < signatures_5.length; _a++) {
40773                         var sig = signatures_5[_a];
40774                         // Each overload becomes a separate constructor declaration, in order
40775                         var decl = signatureToSignatureDeclarationHelper(sig, outputKind, context);
40776                         results.push(ts.setTextRange(decl, sig.declaration));
40777                     }
40778                     return results;
40779                 }
40780                 function serializeIndexSignatures(input, baseType) {
40781                     var results = [];
40782                     for (var _i = 0, _a = [0 /* String */, 1 /* Number */]; _i < _a.length; _i++) {
40783                         var type = _a[_i];
40784                         var info = getIndexInfoOfType(input, type);
40785                         if (info) {
40786                             if (baseType) {
40787                                 var baseInfo = getIndexInfoOfType(baseType, type);
40788                                 if (baseInfo) {
40789                                     if (isTypeIdenticalTo(info.type, baseInfo.type)) {
40790                                         continue; // elide identical index signatures
40791                                     }
40792                                 }
40793                             }
40794                             results.push(indexInfoToIndexSignatureDeclarationHelper(info, type, context));
40795                         }
40796                     }
40797                     return results;
40798                 }
40799                 function serializeBaseType(t, staticType, rootName) {
40800                     var ref = trySerializeAsTypeReference(t);
40801                     if (ref) {
40802                         return ref;
40803                     }
40804                     var tempName = getUnusedName(rootName + "_base");
40805                     var statement = ts.createVariableStatement(/*modifiers*/ undefined, ts.createVariableDeclarationList([
40806                         ts.createVariableDeclaration(tempName, typeToTypeNodeHelper(staticType, context))
40807                     ], 2 /* Const */));
40808                     addResult(statement, 0 /* None */);
40809                     return ts.createExpressionWithTypeArguments(/*typeArgs*/ undefined, ts.createIdentifier(tempName));
40810                 }
40811                 function trySerializeAsTypeReference(t) {
40812                     var typeArgs;
40813                     var reference;
40814                     // We don't use `isValueSymbolAccessible` below. since that considers alternative containers (like modules)
40815                     // which we can't write out in a syntactically valid way as an expression
40816                     if (t.target && getAccessibleSymbolChain(t.target.symbol, enclosingDeclaration, 111551 /* Value */, /*useOnlyExternalAliasing*/ false)) {
40817                         typeArgs = ts.map(getTypeArguments(t), function (t) { return typeToTypeNodeHelper(t, context); });
40818                         reference = symbolToExpression(t.target.symbol, context, 788968 /* Type */);
40819                     }
40820                     else if (t.symbol && getAccessibleSymbolChain(t.symbol, enclosingDeclaration, 111551 /* Value */, /*useOnlyExternalAliasing*/ false)) {
40821                         reference = symbolToExpression(t.symbol, context, 788968 /* Type */);
40822                     }
40823                     if (reference) {
40824                         return ts.createExpressionWithTypeArguments(typeArgs, reference);
40825                     }
40826                 }
40827                 function getUnusedName(input, symbol) {
40828                     if (symbol) {
40829                         if (context.remappedSymbolNames.has("" + getSymbolId(symbol))) {
40830                             return context.remappedSymbolNames.get("" + getSymbolId(symbol));
40831                         }
40832                     }
40833                     if (symbol) {
40834                         input = getNameCandidateWorker(symbol, input);
40835                     }
40836                     var i = 0;
40837                     var original = input;
40838                     while (context.usedSymbolNames.has(input)) {
40839                         i++;
40840                         input = original + "_" + i;
40841                     }
40842                     context.usedSymbolNames.set(input, true);
40843                     if (symbol) {
40844                         context.remappedSymbolNames.set("" + getSymbolId(symbol), input);
40845                     }
40846                     return input;
40847                 }
40848                 function getNameCandidateWorker(symbol, localName) {
40849                     if (localName === "default" /* Default */ || localName === "__class" /* Class */ || localName === "__function" /* Function */) {
40850                         var flags = context.flags;
40851                         context.flags |= 16777216 /* InInitialEntityName */;
40852                         var nameCandidate = getNameOfSymbolAsWritten(symbol, context);
40853                         context.flags = flags;
40854                         localName = nameCandidate.length > 0 && ts.isSingleOrDoubleQuote(nameCandidate.charCodeAt(0)) ? ts.stripQuotes(nameCandidate) : nameCandidate;
40855                     }
40856                     if (localName === "default" /* Default */) {
40857                         localName = "_default";
40858                     }
40859                     else if (localName === "export=" /* ExportEquals */) {
40860                         localName = "_exports";
40861                     }
40862                     localName = ts.isIdentifierText(localName, languageVersion) && !ts.isStringANonContextualKeyword(localName) ? localName : "_" + localName.replace(/[^a-zA-Z0-9]/g, "_");
40863                     return localName;
40864                 }
40865                 function getInternalSymbolName(symbol, localName) {
40866                     if (context.remappedSymbolNames.has("" + getSymbolId(symbol))) {
40867                         return context.remappedSymbolNames.get("" + getSymbolId(symbol));
40868                     }
40869                     localName = getNameCandidateWorker(symbol, localName);
40870                     // The result of this is going to be used as the symbol's name - lock it in, so `getUnusedName` will also pick it up
40871                     context.remappedSymbolNames.set("" + getSymbolId(symbol), localName);
40872                     return localName;
40873                 }
40874             }
40875         }
40876         function typePredicateToString(typePredicate, enclosingDeclaration, flags, writer) {
40877             if (flags === void 0) { flags = 16384 /* UseAliasDefinedOutsideCurrentScope */; }
40878             return writer ? typePredicateToStringWorker(writer).getText() : ts.usingSingleLineStringWriter(typePredicateToStringWorker);
40879             function typePredicateToStringWorker(writer) {
40880                 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
40881                 );
40882                 var printer = ts.createPrinter({ removeComments: true });
40883                 var sourceFile = enclosingDeclaration && ts.getSourceFileOfNode(enclosingDeclaration);
40884                 printer.writeNode(4 /* Unspecified */, predicate, /*sourceFile*/ sourceFile, writer);
40885                 return writer;
40886             }
40887         }
40888         function formatUnionTypes(types) {
40889             var result = [];
40890             var flags = 0;
40891             for (var i = 0; i < types.length; i++) {
40892                 var t = types[i];
40893                 flags |= t.flags;
40894                 if (!(t.flags & 98304 /* Nullable */)) {
40895                     if (t.flags & (512 /* BooleanLiteral */ | 1024 /* EnumLiteral */)) {
40896                         var baseType = t.flags & 512 /* BooleanLiteral */ ? booleanType : getBaseTypeOfEnumLiteralType(t);
40897                         if (baseType.flags & 1048576 /* Union */) {
40898                             var count = baseType.types.length;
40899                             if (i + count <= types.length && getRegularTypeOfLiteralType(types[i + count - 1]) === getRegularTypeOfLiteralType(baseType.types[count - 1])) {
40900                                 result.push(baseType);
40901                                 i += count - 1;
40902                                 continue;
40903                             }
40904                         }
40905                     }
40906                     result.push(t);
40907                 }
40908             }
40909             if (flags & 65536 /* Null */)
40910                 result.push(nullType);
40911             if (flags & 32768 /* Undefined */)
40912                 result.push(undefinedType);
40913             return result || types;
40914         }
40915         function visibilityToString(flags) {
40916             if (flags === 8 /* Private */) {
40917                 return "private";
40918             }
40919             if (flags === 16 /* Protected */) {
40920                 return "protected";
40921             }
40922             return "public";
40923         }
40924         function getTypeAliasForTypeLiteral(type) {
40925             if (type.symbol && type.symbol.flags & 2048 /* TypeLiteral */) {
40926                 var node = ts.findAncestor(type.symbol.declarations[0].parent, function (n) { return n.kind !== 182 /* ParenthesizedType */; });
40927                 if (node.kind === 247 /* TypeAliasDeclaration */) {
40928                     return getSymbolOfNode(node);
40929                 }
40930             }
40931             return undefined;
40932         }
40933         function isTopLevelInExternalModuleAugmentation(node) {
40934             return node && node.parent &&
40935                 node.parent.kind === 250 /* ModuleBlock */ &&
40936                 ts.isExternalModuleAugmentation(node.parent.parent);
40937         }
40938         function isDefaultBindingContext(location) {
40939             return location.kind === 290 /* SourceFile */ || ts.isAmbientModule(location);
40940         }
40941         function getNameOfSymbolFromNameType(symbol, context) {
40942             var nameType = getSymbolLinks(symbol).nameType;
40943             if (nameType) {
40944                 if (nameType.flags & 384 /* StringOrNumberLiteral */) {
40945                     var name = "" + nameType.value;
40946                     if (!ts.isIdentifierText(name, compilerOptions.target) && !isNumericLiteralName(name)) {
40947                         return "\"" + ts.escapeString(name, 34 /* doubleQuote */) + "\"";
40948                     }
40949                     if (isNumericLiteralName(name) && ts.startsWith(name, "-")) {
40950                         return "[" + name + "]";
40951                     }
40952                     return name;
40953                 }
40954                 if (nameType.flags & 8192 /* UniqueESSymbol */) {
40955                     return "[" + getNameOfSymbolAsWritten(nameType.symbol, context) + "]";
40956                 }
40957             }
40958         }
40959         /**
40960          * Gets a human-readable name for a symbol.
40961          * Should *not* be used for the right-hand side of a `.` -- use `symbolName(symbol)` for that instead.
40962          *
40963          * Unlike `symbolName(symbol)`, this will include quotes if the name is from a string literal.
40964          * It will also use a representation of a number as written instead of a decimal form, e.g. `0o11` instead of `9`.
40965          */
40966         function getNameOfSymbolAsWritten(symbol, context) {
40967             if (context && symbol.escapedName === "default" /* Default */ && !(context.flags & 16384 /* UseAliasDefinedOutsideCurrentScope */) &&
40968                 // If it's not the first part of an entity name, it must print as `default`
40969                 (!(context.flags & 16777216 /* InInitialEntityName */) ||
40970                     // if the symbol is synthesized, it will only be referenced externally it must print as `default`
40971                     !symbol.declarations ||
40972                     // if not in the same binding context (source file, module declaration), it must print as `default`
40973                     (context.enclosingDeclaration && ts.findAncestor(symbol.declarations[0], isDefaultBindingContext) !== ts.findAncestor(context.enclosingDeclaration, isDefaultBindingContext)))) {
40974                 return "default";
40975             }
40976             if (symbol.declarations && symbol.declarations.length) {
40977                 var declaration = ts.firstDefined(symbol.declarations, function (d) { return ts.getNameOfDeclaration(d) ? d : undefined; }); // Try using a declaration with a name, first
40978                 var name_2 = declaration && ts.getNameOfDeclaration(declaration);
40979                 if (declaration && name_2) {
40980                     if (ts.isCallExpression(declaration) && ts.isBindableObjectDefinePropertyCall(declaration)) {
40981                         return ts.symbolName(symbol);
40982                     }
40983                     if (ts.isComputedPropertyName(name_2) && !(ts.getCheckFlags(symbol) & 4096 /* Late */)) {
40984                         var nameType = getSymbolLinks(symbol).nameType;
40985                         if (nameType && nameType.flags & 384 /* StringOrNumberLiteral */) {
40986                             // Computed property name isn't late bound, but has a well-known name type - use name type to generate a symbol name
40987                             var result = getNameOfSymbolFromNameType(symbol, context);
40988                             if (result !== undefined) {
40989                                 return result;
40990                             }
40991                         }
40992                     }
40993                     return ts.declarationNameToString(name_2);
40994                 }
40995                 if (!declaration) {
40996                     declaration = symbol.declarations[0]; // Declaration may be nameless, but we'll try anyway
40997                 }
40998                 if (declaration.parent && declaration.parent.kind === 242 /* VariableDeclaration */) {
40999                     return ts.declarationNameToString(declaration.parent.name);
41000                 }
41001                 switch (declaration.kind) {
41002                     case 214 /* ClassExpression */:
41003                     case 201 /* FunctionExpression */:
41004                     case 202 /* ArrowFunction */:
41005                         if (context && !context.encounteredError && !(context.flags & 131072 /* AllowAnonymousIdentifier */)) {
41006                             context.encounteredError = true;
41007                         }
41008                         return declaration.kind === 214 /* ClassExpression */ ? "(Anonymous class)" : "(Anonymous function)";
41009                 }
41010             }
41011             var name = getNameOfSymbolFromNameType(symbol, context);
41012             return name !== undefined ? name : ts.symbolName(symbol);
41013         }
41014         function isDeclarationVisible(node) {
41015             if (node) {
41016                 var links = getNodeLinks(node);
41017                 if (links.isVisible === undefined) {
41018                     links.isVisible = !!determineIfDeclarationIsVisible();
41019                 }
41020                 return links.isVisible;
41021             }
41022             return false;
41023             function determineIfDeclarationIsVisible() {
41024                 switch (node.kind) {
41025                     case 315 /* JSDocCallbackTag */:
41026                     case 322 /* JSDocTypedefTag */:
41027                     case 316 /* JSDocEnumTag */:
41028                         // Top-level jsdoc type aliases are considered exported
41029                         // 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
41030                         return !!(node.parent && node.parent.parent && node.parent.parent.parent && ts.isSourceFile(node.parent.parent.parent));
41031                     case 191 /* BindingElement */:
41032                         return isDeclarationVisible(node.parent.parent);
41033                     case 242 /* VariableDeclaration */:
41034                         if (ts.isBindingPattern(node.name) &&
41035                             !node.name.elements.length) {
41036                             // If the binding pattern is empty, this variable declaration is not visible
41037                             return false;
41038                         }
41039                     // falls through
41040                     case 249 /* ModuleDeclaration */:
41041                     case 245 /* ClassDeclaration */:
41042                     case 246 /* InterfaceDeclaration */:
41043                     case 247 /* TypeAliasDeclaration */:
41044                     case 244 /* FunctionDeclaration */:
41045                     case 248 /* EnumDeclaration */:
41046                     case 253 /* ImportEqualsDeclaration */:
41047                         // external module augmentation is always visible
41048                         if (ts.isExternalModuleAugmentation(node)) {
41049                             return true;
41050                         }
41051                         var parent = getDeclarationContainer(node);
41052                         // If the node is not exported or it is not ambient module element (except import declaration)
41053                         if (!(ts.getCombinedModifierFlags(node) & 1 /* Export */) &&
41054                             !(node.kind !== 253 /* ImportEqualsDeclaration */ && parent.kind !== 290 /* SourceFile */ && parent.flags & 8388608 /* Ambient */)) {
41055                             return isGlobalSourceFile(parent);
41056                         }
41057                         // Exported members/ambient module elements (exception import declaration) are visible if parent is visible
41058                         return isDeclarationVisible(parent);
41059                     case 159 /* PropertyDeclaration */:
41060                     case 158 /* PropertySignature */:
41061                     case 163 /* GetAccessor */:
41062                     case 164 /* SetAccessor */:
41063                     case 161 /* MethodDeclaration */:
41064                     case 160 /* MethodSignature */:
41065                         if (ts.hasModifier(node, 8 /* Private */ | 16 /* Protected */)) {
41066                             // Private/protected properties/methods are not visible
41067                             return false;
41068                         }
41069                     // Public properties/methods are visible if its parents are visible, so:
41070                     // falls through
41071                     case 162 /* Constructor */:
41072                     case 166 /* ConstructSignature */:
41073                     case 165 /* CallSignature */:
41074                     case 167 /* IndexSignature */:
41075                     case 156 /* Parameter */:
41076                     case 250 /* ModuleBlock */:
41077                     case 170 /* FunctionType */:
41078                     case 171 /* ConstructorType */:
41079                     case 173 /* TypeLiteral */:
41080                     case 169 /* TypeReference */:
41081                     case 174 /* ArrayType */:
41082                     case 175 /* TupleType */:
41083                     case 178 /* UnionType */:
41084                     case 179 /* IntersectionType */:
41085                     case 182 /* ParenthesizedType */:
41086                         return isDeclarationVisible(node.parent);
41087                     // Default binding, import specifier and namespace import is visible
41088                     // only on demand so by default it is not visible
41089                     case 255 /* ImportClause */:
41090                     case 256 /* NamespaceImport */:
41091                     case 258 /* ImportSpecifier */:
41092                         return false;
41093                     // Type parameters are always visible
41094                     case 155 /* TypeParameter */:
41095                     // Source file and namespace export are always visible
41096                     // falls through
41097                     case 290 /* SourceFile */:
41098                     case 252 /* NamespaceExportDeclaration */:
41099                         return true;
41100                     // Export assignments do not create name bindings outside the module
41101                     case 259 /* ExportAssignment */:
41102                         return false;
41103                     default:
41104                         return false;
41105                 }
41106             }
41107         }
41108         function collectLinkedAliases(node, setVisibility) {
41109             var exportSymbol;
41110             if (node.parent && node.parent.kind === 259 /* ExportAssignment */) {
41111                 exportSymbol = resolveName(node, node.escapedText, 111551 /* Value */ | 788968 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */, /*nameNotFoundMessage*/ undefined, node, /*isUse*/ false);
41112             }
41113             else if (node.parent.kind === 263 /* ExportSpecifier */) {
41114                 exportSymbol = getTargetOfExportSpecifier(node.parent, 111551 /* Value */ | 788968 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */);
41115             }
41116             var result;
41117             var visited;
41118             if (exportSymbol) {
41119                 visited = ts.createMap();
41120                 visited.set("" + getSymbolId(exportSymbol), true);
41121                 buildVisibleNodeList(exportSymbol.declarations);
41122             }
41123             return result;
41124             function buildVisibleNodeList(declarations) {
41125                 ts.forEach(declarations, function (declaration) {
41126                     var resultNode = getAnyImportSyntax(declaration) || declaration;
41127                     if (setVisibility) {
41128                         getNodeLinks(declaration).isVisible = true;
41129                     }
41130                     else {
41131                         result = result || [];
41132                         ts.pushIfUnique(result, resultNode);
41133                     }
41134                     if (ts.isInternalModuleImportEqualsDeclaration(declaration)) {
41135                         // Add the referenced top container visible
41136                         var internalModuleReference = declaration.moduleReference;
41137                         var firstIdentifier = ts.getFirstIdentifier(internalModuleReference);
41138                         var importSymbol = resolveName(declaration, firstIdentifier.escapedText, 111551 /* Value */ | 788968 /* Type */ | 1920 /* Namespace */, undefined, undefined, /*isUse*/ false);
41139                         var id = importSymbol && "" + getSymbolId(importSymbol);
41140                         if (importSymbol && !visited.has(id)) {
41141                             visited.set(id, true);
41142                             buildVisibleNodeList(importSymbol.declarations);
41143                         }
41144                     }
41145                 });
41146             }
41147         }
41148         /**
41149          * Push an entry on the type resolution stack. If an entry with the given target and the given property name
41150          * is already on the stack, and no entries in between already have a type, then a circularity has occurred.
41151          * In this case, the result values of the existing entry and all entries pushed after it are changed to false,
41152          * and the value false is returned. Otherwise, the new entry is just pushed onto the stack, and true is returned.
41153          * In order to see if the same query has already been done before, the target object and the propertyName both
41154          * must match the one passed in.
41155          *
41156          * @param target The symbol, type, or signature whose type is being queried
41157          * @param propertyName The property name that should be used to query the target for its type
41158          */
41159         function pushTypeResolution(target, propertyName) {
41160             var resolutionCycleStartIndex = findResolutionCycleStartIndex(target, propertyName);
41161             if (resolutionCycleStartIndex >= 0) {
41162                 // A cycle was found
41163                 var length_3 = resolutionTargets.length;
41164                 for (var i = resolutionCycleStartIndex; i < length_3; i++) {
41165                     resolutionResults[i] = false;
41166                 }
41167                 return false;
41168             }
41169             resolutionTargets.push(target);
41170             resolutionResults.push(/*items*/ true);
41171             resolutionPropertyNames.push(propertyName);
41172             return true;
41173         }
41174         function findResolutionCycleStartIndex(target, propertyName) {
41175             for (var i = resolutionTargets.length - 1; i >= 0; i--) {
41176                 if (hasType(resolutionTargets[i], resolutionPropertyNames[i])) {
41177                     return -1;
41178                 }
41179                 if (resolutionTargets[i] === target && resolutionPropertyNames[i] === propertyName) {
41180                     return i;
41181                 }
41182             }
41183             return -1;
41184         }
41185         function hasType(target, propertyName) {
41186             switch (propertyName) {
41187                 case 0 /* Type */:
41188                     return !!getSymbolLinks(target).type;
41189                 case 5 /* EnumTagType */:
41190                     return !!(getNodeLinks(target).resolvedEnumType);
41191                 case 2 /* DeclaredType */:
41192                     return !!getSymbolLinks(target).declaredType;
41193                 case 1 /* ResolvedBaseConstructorType */:
41194                     return !!target.resolvedBaseConstructorType;
41195                 case 3 /* ResolvedReturnType */:
41196                     return !!target.resolvedReturnType;
41197                 case 4 /* ImmediateBaseConstraint */:
41198                     return !!target.immediateBaseConstraint;
41199                 case 6 /* ResolvedTypeArguments */:
41200                     return !!target.resolvedTypeArguments;
41201             }
41202             return ts.Debug.assertNever(propertyName);
41203         }
41204         /**
41205          * Pop an entry from the type resolution stack and return its associated result value. The result value will
41206          * be true if no circularities were detected, or false if a circularity was found.
41207          */
41208         function popTypeResolution() {
41209             resolutionTargets.pop();
41210             resolutionPropertyNames.pop();
41211             return resolutionResults.pop();
41212         }
41213         function getDeclarationContainer(node) {
41214             return ts.findAncestor(ts.getRootDeclaration(node), function (node) {
41215                 switch (node.kind) {
41216                     case 242 /* VariableDeclaration */:
41217                     case 243 /* VariableDeclarationList */:
41218                     case 258 /* ImportSpecifier */:
41219                     case 257 /* NamedImports */:
41220                     case 256 /* NamespaceImport */:
41221                     case 255 /* ImportClause */:
41222                         return false;
41223                     default:
41224                         return true;
41225                 }
41226             }).parent;
41227         }
41228         function getTypeOfPrototypeProperty(prototype) {
41229             // TypeScript 1.0 spec (April 2014): 8.4
41230             // Every class automatically contains a static property member named 'prototype',
41231             // the type of which is an instantiation of the class type with type Any supplied as a type argument for each type parameter.
41232             // It is an error to explicitly declare a static property member with the name 'prototype'.
41233             var classType = getDeclaredTypeOfSymbol(getParentOfSymbol(prototype));
41234             return classType.typeParameters ? createTypeReference(classType, ts.map(classType.typeParameters, function (_) { return anyType; })) : classType;
41235         }
41236         // Return the type of the given property in the given type, or undefined if no such property exists
41237         function getTypeOfPropertyOfType(type, name) {
41238             var prop = getPropertyOfType(type, name);
41239             return prop ? getTypeOfSymbol(prop) : undefined;
41240         }
41241         function getTypeOfPropertyOrIndexSignature(type, name) {
41242             return getTypeOfPropertyOfType(type, name) || isNumericLiteralName(name) && getIndexTypeOfType(type, 1 /* Number */) || getIndexTypeOfType(type, 0 /* String */) || unknownType;
41243         }
41244         function isTypeAny(type) {
41245             return type && (type.flags & 1 /* Any */) !== 0;
41246         }
41247         // Return the type of a binding element parent. We check SymbolLinks first to see if a type has been
41248         // assigned by contextual typing.
41249         function getTypeForBindingElementParent(node) {
41250             var symbol = getSymbolOfNode(node);
41251             return symbol && getSymbolLinks(symbol).type || getTypeForVariableLikeDeclaration(node, /*includeOptionality*/ false);
41252         }
41253         function getRestType(source, properties, symbol) {
41254             source = filterType(source, function (t) { return !(t.flags & 98304 /* Nullable */); });
41255             if (source.flags & 131072 /* Never */) {
41256                 return emptyObjectType;
41257             }
41258             if (source.flags & 1048576 /* Union */) {
41259                 return mapType(source, function (t) { return getRestType(t, properties, symbol); });
41260             }
41261             var omitKeyType = getUnionType(ts.map(properties, getLiteralTypeFromPropertyName));
41262             if (isGenericObjectType(source) || isGenericIndexType(omitKeyType)) {
41263                 if (omitKeyType.flags & 131072 /* Never */) {
41264                     return source;
41265                 }
41266                 var omitTypeAlias = getGlobalOmitSymbol();
41267                 if (!omitTypeAlias) {
41268                     return errorType;
41269                 }
41270                 return getTypeAliasInstantiation(omitTypeAlias, [source, omitKeyType]);
41271             }
41272             var members = ts.createSymbolTable();
41273             for (var _i = 0, _a = getPropertiesOfType(source); _i < _a.length; _i++) {
41274                 var prop = _a[_i];
41275                 if (!isTypeAssignableTo(getLiteralTypeFromProperty(prop, 8576 /* StringOrNumberLiteralOrUnique */), omitKeyType)
41276                     && !(ts.getDeclarationModifierFlagsFromSymbol(prop) & (8 /* Private */ | 16 /* Protected */))
41277                     && isSpreadableProperty(prop)) {
41278                     members.set(prop.escapedName, getSpreadSymbol(prop, /*readonly*/ false));
41279                 }
41280             }
41281             var stringIndexInfo = getIndexInfoOfType(source, 0 /* String */);
41282             var numberIndexInfo = getIndexInfoOfType(source, 1 /* Number */);
41283             var result = createAnonymousType(symbol, members, ts.emptyArray, ts.emptyArray, stringIndexInfo, numberIndexInfo);
41284             result.objectFlags |= 131072 /* ObjectRestType */;
41285             return result;
41286         }
41287         // Determine the control flow type associated with a destructuring declaration or assignment. The following
41288         // forms of destructuring are possible:
41289         //   let { x } = obj;  // BindingElement
41290         //   let [ x ] = obj;  // BindingElement
41291         //   { x } = obj;      // ShorthandPropertyAssignment
41292         //   { x: v } = obj;   // PropertyAssignment
41293         //   [ x ] = obj;      // Expression
41294         // We construct a synthetic element access expression corresponding to 'obj.x' such that the control
41295         // flow analyzer doesn't have to handle all the different syntactic forms.
41296         function getFlowTypeOfDestructuring(node, declaredType) {
41297             var reference = getSyntheticElementAccess(node);
41298             return reference ? getFlowTypeOfReference(reference, declaredType) : declaredType;
41299         }
41300         function getSyntheticElementAccess(node) {
41301             var parentAccess = getParentElementAccess(node);
41302             if (parentAccess && parentAccess.flowNode) {
41303                 var propName = getDestructuringPropertyName(node);
41304                 if (propName) {
41305                     var result = ts.createNode(195 /* ElementAccessExpression */, node.pos, node.end);
41306                     result.parent = node;
41307                     result.expression = parentAccess;
41308                     var literal = ts.createNode(10 /* StringLiteral */, node.pos, node.end);
41309                     literal.parent = result;
41310                     literal.text = propName;
41311                     result.argumentExpression = literal;
41312                     result.flowNode = parentAccess.flowNode;
41313                     return result;
41314                 }
41315             }
41316         }
41317         function getParentElementAccess(node) {
41318             var ancestor = node.parent.parent;
41319             switch (ancestor.kind) {
41320                 case 191 /* BindingElement */:
41321                 case 281 /* PropertyAssignment */:
41322                     return getSyntheticElementAccess(ancestor);
41323                 case 192 /* ArrayLiteralExpression */:
41324                     return getSyntheticElementAccess(node.parent);
41325                 case 242 /* VariableDeclaration */:
41326                     return ancestor.initializer;
41327                 case 209 /* BinaryExpression */:
41328                     return ancestor.right;
41329             }
41330         }
41331         function getDestructuringPropertyName(node) {
41332             var parent = node.parent;
41333             if (node.kind === 191 /* BindingElement */ && parent.kind === 189 /* ObjectBindingPattern */) {
41334                 return getLiteralPropertyNameText(node.propertyName || node.name);
41335             }
41336             if (node.kind === 281 /* PropertyAssignment */ || node.kind === 282 /* ShorthandPropertyAssignment */) {
41337                 return getLiteralPropertyNameText(node.name);
41338             }
41339             return "" + parent.elements.indexOf(node);
41340         }
41341         function getLiteralPropertyNameText(name) {
41342             var type = getLiteralTypeFromPropertyName(name);
41343             return type.flags & (128 /* StringLiteral */ | 256 /* NumberLiteral */) ? "" + type.value : undefined;
41344         }
41345         /** Return the inferred type for a binding element */
41346         function getTypeForBindingElement(declaration) {
41347             var pattern = declaration.parent;
41348             var parentType = getTypeForBindingElementParent(pattern.parent);
41349             // If no type or an any type was inferred for parent, infer that for the binding element
41350             if (!parentType || isTypeAny(parentType)) {
41351                 return parentType;
41352             }
41353             // Relax null check on ambient destructuring parameters, since the parameters have no implementation and are just documentation
41354             if (strictNullChecks && declaration.flags & 8388608 /* Ambient */ && ts.isParameterDeclaration(declaration)) {
41355                 parentType = getNonNullableType(parentType);
41356             }
41357             // Filter `undefined` from the type we check against if the parent has an initializer and that initializer is not possibly `undefined`
41358             else if (strictNullChecks && pattern.parent.initializer && !(getTypeFacts(getTypeOfInitializer(pattern.parent.initializer)) & 65536 /* EQUndefined */)) {
41359                 parentType = getTypeWithFacts(parentType, 524288 /* NEUndefined */);
41360             }
41361             var type;
41362             if (pattern.kind === 189 /* ObjectBindingPattern */) {
41363                 if (declaration.dotDotDotToken) {
41364                     parentType = getReducedType(parentType);
41365                     if (parentType.flags & 2 /* Unknown */ || !isValidSpreadType(parentType)) {
41366                         error(declaration, ts.Diagnostics.Rest_types_may_only_be_created_from_object_types);
41367                         return errorType;
41368                     }
41369                     var literalMembers = [];
41370                     for (var _i = 0, _a = pattern.elements; _i < _a.length; _i++) {
41371                         var element = _a[_i];
41372                         if (!element.dotDotDotToken) {
41373                             literalMembers.push(element.propertyName || element.name);
41374                         }
41375                     }
41376                     type = getRestType(parentType, literalMembers, declaration.symbol);
41377                 }
41378                 else {
41379                     // Use explicitly specified property name ({ p: xxx } form), or otherwise the implied name ({ p } form)
41380                     var name = declaration.propertyName || declaration.name;
41381                     var indexType = getLiteralTypeFromPropertyName(name);
41382                     var declaredType = getConstraintForLocation(getIndexedAccessType(parentType, indexType, name), declaration.name);
41383                     type = getFlowTypeOfDestructuring(declaration, declaredType);
41384                 }
41385             }
41386             else {
41387                 // This elementType will be used if the specific property corresponding to this index is not
41388                 // present (aka the tuple element property). This call also checks that the parentType is in
41389                 // fact an iterable or array (depending on target language).
41390                 var elementType = checkIteratedTypeOrElementType(65 /* Destructuring */, parentType, undefinedType, pattern);
41391                 var index_1 = pattern.elements.indexOf(declaration);
41392                 if (declaration.dotDotDotToken) {
41393                     // If the parent is a tuple type, the rest element has a tuple type of the
41394                     // remaining tuple element types. Otherwise, the rest element has an array type with same
41395                     // element type as the parent type.
41396                     type = everyType(parentType, isTupleType) ?
41397                         mapType(parentType, function (t) { return sliceTupleType(t, index_1); }) :
41398                         createArrayType(elementType);
41399                 }
41400                 else if (isArrayLikeType(parentType)) {
41401                     var indexType = getLiteralType(index_1);
41402                     var accessFlags = hasDefaultValue(declaration) ? 8 /* NoTupleBoundsCheck */ : 0;
41403                     var declaredType = getConstraintForLocation(getIndexedAccessTypeOrUndefined(parentType, indexType, declaration.name, accessFlags) || errorType, declaration.name);
41404                     type = getFlowTypeOfDestructuring(declaration, declaredType);
41405                 }
41406                 else {
41407                     type = elementType;
41408                 }
41409             }
41410             if (!declaration.initializer) {
41411                 return type;
41412             }
41413             if (ts.getEffectiveTypeAnnotationNode(ts.walkUpBindingElementsAndPatterns(declaration))) {
41414                 // In strict null checking mode, if a default value of a non-undefined type is specified, remove
41415                 // undefined from the final type.
41416                 return strictNullChecks && !(getFalsyFlags(checkDeclarationInitializer(declaration)) & 32768 /* Undefined */) ?
41417                     getTypeWithFacts(type, 524288 /* NEUndefined */) :
41418                     type;
41419             }
41420             return widenTypeInferredFromInitializer(declaration, getUnionType([getTypeWithFacts(type, 524288 /* NEUndefined */), checkDeclarationInitializer(declaration)], 2 /* Subtype */));
41421         }
41422         function getTypeForDeclarationFromJSDocComment(declaration) {
41423             var jsdocType = ts.getJSDocType(declaration);
41424             if (jsdocType) {
41425                 return getTypeFromTypeNode(jsdocType);
41426             }
41427             return undefined;
41428         }
41429         function isNullOrUndefined(node) {
41430             var expr = ts.skipParentheses(node);
41431             return expr.kind === 100 /* NullKeyword */ || expr.kind === 75 /* Identifier */ && getResolvedSymbol(expr) === undefinedSymbol;
41432         }
41433         function isEmptyArrayLiteral(node) {
41434             var expr = ts.skipParentheses(node);
41435             return expr.kind === 192 /* ArrayLiteralExpression */ && expr.elements.length === 0;
41436         }
41437         function addOptionality(type, optional) {
41438             if (optional === void 0) { optional = true; }
41439             return strictNullChecks && optional ? getOptionalType(type) : type;
41440         }
41441         // Return the inferred type for a variable, parameter, or property declaration
41442         function getTypeForVariableLikeDeclaration(declaration, includeOptionality) {
41443             // A variable declared in a for..in statement is of type string, or of type keyof T when the
41444             // right hand expression is of a type parameter type.
41445             if (ts.isVariableDeclaration(declaration) && declaration.parent.parent.kind === 231 /* ForInStatement */) {
41446                 var indexType = getIndexType(getNonNullableTypeIfNeeded(checkExpression(declaration.parent.parent.expression)));
41447                 return indexType.flags & (262144 /* TypeParameter */ | 4194304 /* Index */) ? getExtractStringType(indexType) : stringType;
41448             }
41449             if (ts.isVariableDeclaration(declaration) && declaration.parent.parent.kind === 232 /* ForOfStatement */) {
41450                 // checkRightHandSideOfForOf will return undefined if the for-of expression type was
41451                 // missing properties/signatures required to get its iteratedType (like
41452                 // [Symbol.iterator] or next). This may be because we accessed properties from anyType,
41453                 // or it may have led to an error inside getElementTypeOfIterable.
41454                 var forOfStatement = declaration.parent.parent;
41455                 return checkRightHandSideOfForOf(forOfStatement) || anyType;
41456             }
41457             if (ts.isBindingPattern(declaration.parent)) {
41458                 return getTypeForBindingElement(declaration);
41459             }
41460             var isOptional = includeOptionality && (ts.isParameter(declaration) && isJSDocOptionalParameter(declaration)
41461                 || !ts.isBindingElement(declaration) && !ts.isVariableDeclaration(declaration) && !!declaration.questionToken);
41462             // Use type from type annotation if one is present
41463             var declaredType = tryGetTypeFromEffectiveTypeNode(declaration);
41464             if (declaredType) {
41465                 return addOptionality(declaredType, isOptional);
41466             }
41467             if ((noImplicitAny || ts.isInJSFile(declaration)) &&
41468                 declaration.kind === 242 /* VariableDeclaration */ && !ts.isBindingPattern(declaration.name) &&
41469                 !(ts.getCombinedModifierFlags(declaration) & 1 /* Export */) && !(declaration.flags & 8388608 /* Ambient */)) {
41470                 // If --noImplicitAny is on or the declaration is in a Javascript file,
41471                 // use control flow tracked 'any' type for non-ambient, non-exported var or let variables with no
41472                 // initializer or a 'null' or 'undefined' initializer.
41473                 if (!(ts.getCombinedNodeFlags(declaration) & 2 /* Const */) && (!declaration.initializer || isNullOrUndefined(declaration.initializer))) {
41474                     return autoType;
41475                 }
41476                 // Use control flow tracked 'any[]' type for non-ambient, non-exported variables with an empty array
41477                 // literal initializer.
41478                 if (declaration.initializer && isEmptyArrayLiteral(declaration.initializer)) {
41479                     return autoArrayType;
41480                 }
41481             }
41482             if (declaration.kind === 156 /* Parameter */) {
41483                 var func = declaration.parent;
41484                 // For a parameter of a set accessor, use the type of the get accessor if one is present
41485                 if (func.kind === 164 /* SetAccessor */ && !hasNonBindableDynamicName(func)) {
41486                     var getter = ts.getDeclarationOfKind(getSymbolOfNode(declaration.parent), 163 /* GetAccessor */);
41487                     if (getter) {
41488                         var getterSignature = getSignatureFromDeclaration(getter);
41489                         var thisParameter = getAccessorThisParameter(func);
41490                         if (thisParameter && declaration === thisParameter) {
41491                             // Use the type from the *getter*
41492                             ts.Debug.assert(!thisParameter.type);
41493                             return getTypeOfSymbol(getterSignature.thisParameter);
41494                         }
41495                         return getReturnTypeOfSignature(getterSignature);
41496                     }
41497                 }
41498                 if (ts.isInJSFile(declaration)) {
41499                     var typeTag = ts.getJSDocType(func);
41500                     if (typeTag && ts.isFunctionTypeNode(typeTag)) {
41501                         return getTypeAtPosition(getSignatureFromDeclaration(typeTag), func.parameters.indexOf(declaration));
41502                     }
41503                 }
41504                 // Use contextual parameter type if one is available
41505                 var type = declaration.symbol.escapedName === "this" /* This */ ? getContextualThisParameterType(func) : getContextuallyTypedParameterType(declaration);
41506                 if (type) {
41507                     return addOptionality(type, isOptional);
41508                 }
41509             }
41510             else if (ts.isInJSFile(declaration)) {
41511                 var containerObjectType = getJSContainerObjectType(declaration, getSymbolOfNode(declaration), ts.getDeclaredExpandoInitializer(declaration));
41512                 if (containerObjectType) {
41513                     return containerObjectType;
41514                 }
41515             }
41516             // Use the type of the initializer expression if one is present and the declaration is
41517             // not a parameter of a contextually typed function
41518             if (declaration.initializer) {
41519                 var type = widenTypeInferredFromInitializer(declaration, checkDeclarationInitializer(declaration));
41520                 return addOptionality(type, isOptional);
41521             }
41522             if (ts.isJsxAttribute(declaration)) {
41523                 // if JSX attribute doesn't have initializer, by default the attribute will have boolean value of true.
41524                 // I.e <Elem attr /> is sugar for <Elem attr={true} />
41525                 return trueType;
41526             }
41527             // If the declaration specifies a binding pattern and is not a parameter of a contextually
41528             // typed function, use the type implied by the binding pattern
41529             if (ts.isBindingPattern(declaration.name)) {
41530                 return getTypeFromBindingPattern(declaration.name, /*includePatternInType*/ false, /*reportErrors*/ true);
41531             }
41532             // No type specified and nothing can be inferred
41533             return undefined;
41534         }
41535         function getWidenedTypeForAssignmentDeclaration(symbol, resolvedSymbol) {
41536             // function/class/{} initializers are themselves containers, so they won't merge in the same way as other initializers
41537             var container = ts.getAssignedExpandoInitializer(symbol.valueDeclaration);
41538             if (container) {
41539                 var tag = ts.getJSDocTypeTag(container);
41540                 if (tag && tag.typeExpression) {
41541                     return getTypeFromTypeNode(tag.typeExpression);
41542                 }
41543                 var containerObjectType = getJSContainerObjectType(symbol.valueDeclaration, symbol, container);
41544                 return containerObjectType || getWidenedLiteralType(checkExpressionCached(container));
41545             }
41546             var definedInConstructor = false;
41547             var definedInMethod = false;
41548             var jsdocType;
41549             var types;
41550             for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) {
41551                 var declaration = _a[_i];
41552                 var expression = (ts.isBinaryExpression(declaration) || ts.isCallExpression(declaration)) ? declaration :
41553                     ts.isAccessExpression(declaration) ? ts.isBinaryExpression(declaration.parent) ? declaration.parent : declaration :
41554                         undefined;
41555                 if (!expression) {
41556                     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
41557                 }
41558                 var kind = ts.isAccessExpression(expression)
41559                     ? ts.getAssignmentDeclarationPropertyAccessKind(expression)
41560                     : ts.getAssignmentDeclarationKind(expression);
41561                 if (kind === 4 /* ThisProperty */) {
41562                     if (isDeclarationInConstructor(expression)) {
41563                         definedInConstructor = true;
41564                     }
41565                     else {
41566                         definedInMethod = true;
41567                     }
41568                 }
41569                 if (!ts.isCallExpression(expression)) {
41570                     jsdocType = getAnnotatedTypeForAssignmentDeclaration(jsdocType, expression, symbol, declaration);
41571                 }
41572                 if (!jsdocType) {
41573                     (types || (types = [])).push((ts.isBinaryExpression(expression) || ts.isCallExpression(expression)) ? getInitializerTypeFromAssignmentDeclaration(symbol, resolvedSymbol, expression, kind) : neverType);
41574                 }
41575             }
41576             var type = jsdocType;
41577             if (!type) {
41578                 if (!ts.length(types)) {
41579                     return errorType; // No types from any declarations :(
41580                 }
41581                 var constructorTypes = definedInConstructor ? getConstructorDefinedThisAssignmentTypes(types, symbol.declarations) : undefined;
41582                 // use only the constructor types unless they were only assigned null | undefined (including widening variants)
41583                 if (definedInMethod) {
41584                     var propType = getTypeOfAssignmentDeclarationPropertyOfBaseType(symbol);
41585                     if (propType) {
41586                         (constructorTypes || (constructorTypes = [])).push(propType);
41587                         definedInConstructor = true;
41588                     }
41589                 }
41590                 var sourceTypes = ts.some(constructorTypes, function (t) { return !!(t.flags & ~98304 /* Nullable */); }) ? constructorTypes : types; // TODO: GH#18217
41591                 type = getUnionType(sourceTypes, 2 /* Subtype */);
41592             }
41593             var widened = getWidenedType(addOptionality(type, definedInMethod && !definedInConstructor));
41594             if (filterType(widened, function (t) { return !!(t.flags & ~98304 /* Nullable */); }) === neverType) {
41595                 reportImplicitAny(symbol.valueDeclaration, anyType);
41596                 return anyType;
41597             }
41598             return widened;
41599         }
41600         function getJSContainerObjectType(decl, symbol, init) {
41601             if (!ts.isInJSFile(decl) || !init || !ts.isObjectLiteralExpression(init) || init.properties.length) {
41602                 return undefined;
41603             }
41604             var exports = ts.createSymbolTable();
41605             while (ts.isBinaryExpression(decl) || ts.isPropertyAccessExpression(decl)) {
41606                 var s_2 = getSymbolOfNode(decl);
41607                 if (s_2 && ts.hasEntries(s_2.exports)) {
41608                     mergeSymbolTable(exports, s_2.exports);
41609                 }
41610                 decl = ts.isBinaryExpression(decl) ? decl.parent : decl.parent.parent;
41611             }
41612             var s = getSymbolOfNode(decl);
41613             if (s && ts.hasEntries(s.exports)) {
41614                 mergeSymbolTable(exports, s.exports);
41615             }
41616             var type = createAnonymousType(symbol, exports, ts.emptyArray, ts.emptyArray, undefined, undefined);
41617             type.objectFlags |= 16384 /* JSLiteral */;
41618             return type;
41619         }
41620         function getAnnotatedTypeForAssignmentDeclaration(declaredType, expression, symbol, declaration) {
41621             var typeNode = ts.getEffectiveTypeAnnotationNode(expression.parent);
41622             if (typeNode) {
41623                 var type = getWidenedType(getTypeFromTypeNode(typeNode));
41624                 if (!declaredType) {
41625                     return type;
41626                 }
41627                 else if (declaredType !== errorType && type !== errorType && !isTypeIdenticalTo(declaredType, type)) {
41628                     errorNextVariableOrPropertyDeclarationMustHaveSameType(/*firstDeclaration*/ undefined, declaredType, declaration, type);
41629                 }
41630             }
41631             if (symbol.parent) {
41632                 var typeNode_2 = ts.getEffectiveTypeAnnotationNode(symbol.parent.valueDeclaration);
41633                 if (typeNode_2) {
41634                     return getTypeOfPropertyOfType(getTypeFromTypeNode(typeNode_2), symbol.escapedName);
41635                 }
41636             }
41637             return declaredType;
41638         }
41639         /** If we don't have an explicit JSDoc type, get the type from the initializer. */
41640         function getInitializerTypeFromAssignmentDeclaration(symbol, resolvedSymbol, expression, kind) {
41641             if (ts.isCallExpression(expression)) {
41642                 if (resolvedSymbol) {
41643                     return getTypeOfSymbol(resolvedSymbol); // This shouldn't happen except under some hopefully forbidden merges of export assignments and object define assignments
41644                 }
41645                 var objectLitType = checkExpressionCached(expression.arguments[2]);
41646                 var valueType = getTypeOfPropertyOfType(objectLitType, "value");
41647                 if (valueType) {
41648                     return valueType;
41649                 }
41650                 var getFunc = getTypeOfPropertyOfType(objectLitType, "get");
41651                 if (getFunc) {
41652                     var getSig = getSingleCallSignature(getFunc);
41653                     if (getSig) {
41654                         return getReturnTypeOfSignature(getSig);
41655                     }
41656                 }
41657                 var setFunc = getTypeOfPropertyOfType(objectLitType, "set");
41658                 if (setFunc) {
41659                     var setSig = getSingleCallSignature(setFunc);
41660                     if (setSig) {
41661                         return getTypeOfFirstParameterOfSignature(setSig);
41662                     }
41663                 }
41664                 return anyType;
41665             }
41666             if (containsSameNamedThisProperty(expression.left, expression.right)) {
41667                 return anyType;
41668             }
41669             var type = resolvedSymbol ? getTypeOfSymbol(resolvedSymbol) : getWidenedLiteralType(checkExpressionCached(expression.right));
41670             if (type.flags & 524288 /* Object */ &&
41671                 kind === 2 /* ModuleExports */ &&
41672                 symbol.escapedName === "export=" /* ExportEquals */) {
41673                 var exportedType = resolveStructuredTypeMembers(type);
41674                 var members_4 = ts.createSymbolTable();
41675                 ts.copyEntries(exportedType.members, members_4);
41676                 if (resolvedSymbol && !resolvedSymbol.exports) {
41677                     resolvedSymbol.exports = ts.createSymbolTable();
41678                 }
41679                 (resolvedSymbol || symbol).exports.forEach(function (s, name) {
41680                     var _a;
41681                     var exportedMember = members_4.get(name);
41682                     if (exportedMember && exportedMember !== s) {
41683                         if (s.flags & 111551 /* Value */) {
41684                             // If the member has an additional value-like declaration, union the types from the two declarations,
41685                             // but issue an error if they occurred in two different files. The purpose is to support a JS file with
41686                             // a pattern like:
41687                             //
41688                             // module.exports = { a: true };
41689                             // module.exports.a = 3;
41690                             //
41691                             // but we may have a JS file with `module.exports = { a: true }` along with a TypeScript module augmentation
41692                             // declaring an `export const a: number`. In that case, we issue a duplicate identifier error, because
41693                             // it's unclear what that's supposed to mean, so it's probably a mistake.
41694                             if (ts.getSourceFileOfNode(s.valueDeclaration) !== ts.getSourceFileOfNode(exportedMember.valueDeclaration)) {
41695                                 var unescapedName = ts.unescapeLeadingUnderscores(s.escapedName);
41696                                 var exportedMemberName = ((_a = ts.tryCast(exportedMember.valueDeclaration, ts.isNamedDeclaration)) === null || _a === void 0 ? void 0 : _a.name) || exportedMember.valueDeclaration;
41697                                 ts.addRelatedInfo(error(s.valueDeclaration, ts.Diagnostics.Duplicate_identifier_0, unescapedName), ts.createDiagnosticForNode(exportedMemberName, ts.Diagnostics._0_was_also_declared_here, unescapedName));
41698                                 ts.addRelatedInfo(error(exportedMemberName, ts.Diagnostics.Duplicate_identifier_0, unescapedName), ts.createDiagnosticForNode(s.valueDeclaration, ts.Diagnostics._0_was_also_declared_here, unescapedName));
41699                             }
41700                             var union = createSymbol(s.flags | exportedMember.flags, name);
41701                             union.type = getUnionType([getTypeOfSymbol(s), getTypeOfSymbol(exportedMember)]);
41702                             union.valueDeclaration = exportedMember.valueDeclaration;
41703                             union.declarations = ts.concatenate(exportedMember.declarations, s.declarations);
41704                             members_4.set(name, union);
41705                         }
41706                         else {
41707                             members_4.set(name, mergeSymbol(s, exportedMember));
41708                         }
41709                     }
41710                     else {
41711                         members_4.set(name, s);
41712                     }
41713                 });
41714                 var result = createAnonymousType(exportedType.symbol, members_4, exportedType.callSignatures, exportedType.constructSignatures, exportedType.stringIndexInfo, exportedType.numberIndexInfo);
41715                 result.objectFlags |= (ts.getObjectFlags(type) & 16384 /* JSLiteral */); // Propagate JSLiteral flag
41716                 return result;
41717             }
41718             if (isEmptyArrayLiteralType(type)) {
41719                 reportImplicitAny(expression, anyArrayType);
41720                 return anyArrayType;
41721             }
41722             return type;
41723         }
41724         function containsSameNamedThisProperty(thisProperty, expression) {
41725             return ts.isPropertyAccessExpression(thisProperty)
41726                 && thisProperty.expression.kind === 104 /* ThisKeyword */
41727                 && ts.forEachChildRecursively(expression, function (n) { return isMatchingReference(thisProperty, n); });
41728         }
41729         function isDeclarationInConstructor(expression) {
41730             var thisContainer = ts.getThisContainer(expression, /*includeArrowFunctions*/ false);
41731             // Properties defined in a constructor (or base constructor, or javascript constructor function) don't get undefined added.
41732             // Function expressions that are assigned to the prototype count as methods.
41733             return thisContainer.kind === 162 /* Constructor */ ||
41734                 thisContainer.kind === 244 /* FunctionDeclaration */ ||
41735                 (thisContainer.kind === 201 /* FunctionExpression */ && !ts.isPrototypePropertyAssignment(thisContainer.parent));
41736         }
41737         function getConstructorDefinedThisAssignmentTypes(types, declarations) {
41738             ts.Debug.assert(types.length === declarations.length);
41739             return types.filter(function (_, i) {
41740                 var declaration = declarations[i];
41741                 var expression = ts.isBinaryExpression(declaration) ? declaration :
41742                     ts.isBinaryExpression(declaration.parent) ? declaration.parent : undefined;
41743                 return expression && isDeclarationInConstructor(expression);
41744             });
41745         }
41746         /** check for definition in base class if any declaration is in a class */
41747         function getTypeOfAssignmentDeclarationPropertyOfBaseType(property) {
41748             var parentDeclaration = ts.forEach(property.declarations, function (d) {
41749                 var parent = ts.getThisContainer(d, /*includeArrowFunctions*/ false).parent;
41750                 return ts.isClassLike(parent) && parent;
41751             });
41752             if (parentDeclaration) {
41753                 var classType = getDeclaredTypeOfSymbol(getSymbolOfNode(parentDeclaration));
41754                 var baseClassType = classType && getBaseTypes(classType)[0];
41755                 if (baseClassType) {
41756                     return getTypeOfPropertyOfType(baseClassType, property.escapedName);
41757                 }
41758             }
41759         }
41760         // Return the type implied by a binding pattern element. This is the type of the initializer of the element if
41761         // one is present. Otherwise, if the element is itself a binding pattern, it is the type implied by the binding
41762         // pattern. Otherwise, it is the type any.
41763         function getTypeFromBindingElement(element, includePatternInType, reportErrors) {
41764             if (element.initializer) {
41765                 // The type implied by a binding pattern is independent of context, so we check the initializer with no
41766                 // contextual type or, if the element itself is a binding pattern, with the type implied by that binding
41767                 // pattern.
41768                 var contextualType = ts.isBindingPattern(element.name) ? getTypeFromBindingPattern(element.name, /*includePatternInType*/ true, /*reportErrors*/ false) : unknownType;
41769                 return addOptionality(widenTypeInferredFromInitializer(element, checkDeclarationInitializer(element, contextualType)));
41770             }
41771             if (ts.isBindingPattern(element.name)) {
41772                 return getTypeFromBindingPattern(element.name, includePatternInType, reportErrors);
41773             }
41774             if (reportErrors && !declarationBelongsToPrivateAmbientMember(element)) {
41775                 reportImplicitAny(element, anyType);
41776             }
41777             // When we're including the pattern in the type (an indication we're obtaining a contextual type), we
41778             // use the non-inferrable any type. Inference will never directly infer this type, but it is possible
41779             // to infer a type that contains it, e.g. for a binding pattern like [foo] or { foo }. In such cases,
41780             // widening of the binding pattern type substitutes a regular any for the non-inferrable any.
41781             return includePatternInType ? nonInferrableAnyType : anyType;
41782         }
41783         // Return the type implied by an object binding pattern
41784         function getTypeFromObjectBindingPattern(pattern, includePatternInType, reportErrors) {
41785             var members = ts.createSymbolTable();
41786             var stringIndexInfo;
41787             var objectFlags = 128 /* ObjectLiteral */ | 1048576 /* ContainsObjectOrArrayLiteral */;
41788             ts.forEach(pattern.elements, function (e) {
41789                 var name = e.propertyName || e.name;
41790                 if (e.dotDotDotToken) {
41791                     stringIndexInfo = createIndexInfo(anyType, /*isReadonly*/ false);
41792                     return;
41793                 }
41794                 var exprType = getLiteralTypeFromPropertyName(name);
41795                 if (!isTypeUsableAsPropertyName(exprType)) {
41796                     // do not include computed properties in the implied type
41797                     objectFlags |= 512 /* ObjectLiteralPatternWithComputedProperties */;
41798                     return;
41799                 }
41800                 var text = getPropertyNameFromType(exprType);
41801                 var flags = 4 /* Property */ | (e.initializer ? 16777216 /* Optional */ : 0);
41802                 var symbol = createSymbol(flags, text);
41803                 symbol.type = getTypeFromBindingElement(e, includePatternInType, reportErrors);
41804                 symbol.bindingElement = e;
41805                 members.set(symbol.escapedName, symbol);
41806             });
41807             var result = createAnonymousType(undefined, members, ts.emptyArray, ts.emptyArray, stringIndexInfo, undefined);
41808             result.objectFlags |= objectFlags;
41809             if (includePatternInType) {
41810                 result.pattern = pattern;
41811                 result.objectFlags |= 1048576 /* ContainsObjectOrArrayLiteral */;
41812             }
41813             return result;
41814         }
41815         // Return the type implied by an array binding pattern
41816         function getTypeFromArrayBindingPattern(pattern, includePatternInType, reportErrors) {
41817             var elements = pattern.elements;
41818             var lastElement = ts.lastOrUndefined(elements);
41819             var hasRestElement = !!(lastElement && lastElement.kind === 191 /* BindingElement */ && lastElement.dotDotDotToken);
41820             if (elements.length === 0 || elements.length === 1 && hasRestElement) {
41821                 return languageVersion >= 2 /* ES2015 */ ? createIterableType(anyType) : anyArrayType;
41822             }
41823             var elementTypes = ts.map(elements, function (e) { return ts.isOmittedExpression(e) ? anyType : getTypeFromBindingElement(e, includePatternInType, reportErrors); });
41824             var minLength = ts.findLastIndex(elements, function (e) { return !ts.isOmittedExpression(e) && !hasDefaultValue(e); }, elements.length - (hasRestElement ? 2 : 1)) + 1;
41825             var result = createTupleType(elementTypes, minLength, hasRestElement);
41826             if (includePatternInType) {
41827                 result = cloneTypeReference(result);
41828                 result.pattern = pattern;
41829                 result.objectFlags |= 1048576 /* ContainsObjectOrArrayLiteral */;
41830             }
41831             return result;
41832         }
41833         // Return the type implied by a binding pattern. This is the type implied purely by the binding pattern itself
41834         // and without regard to its context (i.e. without regard any type annotation or initializer associated with the
41835         // declaration in which the binding pattern is contained). For example, the implied type of [x, y] is [any, any]
41836         // and the implied type of { x, y: z = 1 } is { x: any; y: number; }. The type implied by a binding pattern is
41837         // used as the contextual type of an initializer associated with the binding pattern. Also, for a destructuring
41838         // parameter with no type annotation or initializer, the type implied by the binding pattern becomes the type of
41839         // the parameter.
41840         function getTypeFromBindingPattern(pattern, includePatternInType, reportErrors) {
41841             if (includePatternInType === void 0) { includePatternInType = false; }
41842             if (reportErrors === void 0) { reportErrors = false; }
41843             return pattern.kind === 189 /* ObjectBindingPattern */
41844                 ? getTypeFromObjectBindingPattern(pattern, includePatternInType, reportErrors)
41845                 : getTypeFromArrayBindingPattern(pattern, includePatternInType, reportErrors);
41846         }
41847         // Return the type associated with a variable, parameter, or property declaration. In the simple case this is the type
41848         // specified in a type annotation or inferred from an initializer. However, in the case of a destructuring declaration it
41849         // is a bit more involved. For example:
41850         //
41851         //   var [x, s = ""] = [1, "one"];
41852         //
41853         // Here, the array literal [1, "one"] is contextually typed by the type [any, string], which is the implied type of the
41854         // binding pattern [x, s = ""]. Because the contextual type is a tuple type, the resulting type of [1, "one"] is the
41855         // tuple type [number, string]. Thus, the type inferred for 'x' is number and the type inferred for 's' is string.
41856         function getWidenedTypeForVariableLikeDeclaration(declaration, reportErrors) {
41857             return widenTypeForVariableLikeDeclaration(getTypeForVariableLikeDeclaration(declaration, /*includeOptionality*/ true), declaration, reportErrors);
41858         }
41859         function widenTypeForVariableLikeDeclaration(type, declaration, reportErrors) {
41860             if (type) {
41861                 if (reportErrors) {
41862                     reportErrorsFromWidening(declaration, type);
41863                 }
41864                 // always widen a 'unique symbol' type if the type was created for a different declaration.
41865                 if (type.flags & 8192 /* UniqueESSymbol */ && (ts.isBindingElement(declaration) || !declaration.type) && type.symbol !== getSymbolOfNode(declaration)) {
41866                     type = esSymbolType;
41867                 }
41868                 return getWidenedType(type);
41869             }
41870             // Rest parameters default to type any[], other parameters default to type any
41871             type = ts.isParameter(declaration) && declaration.dotDotDotToken ? anyArrayType : anyType;
41872             // Report implicit any errors unless this is a private property within an ambient declaration
41873             if (reportErrors) {
41874                 if (!declarationBelongsToPrivateAmbientMember(declaration)) {
41875                     reportImplicitAny(declaration, type);
41876                 }
41877             }
41878             return type;
41879         }
41880         function declarationBelongsToPrivateAmbientMember(declaration) {
41881             var root = ts.getRootDeclaration(declaration);
41882             var memberDeclaration = root.kind === 156 /* Parameter */ ? root.parent : root;
41883             return isPrivateWithinAmbient(memberDeclaration);
41884         }
41885         function tryGetTypeFromEffectiveTypeNode(declaration) {
41886             var typeNode = ts.getEffectiveTypeAnnotationNode(declaration);
41887             if (typeNode) {
41888                 return getTypeFromTypeNode(typeNode);
41889             }
41890         }
41891         function getTypeOfVariableOrParameterOrProperty(symbol) {
41892             var links = getSymbolLinks(symbol);
41893             if (!links.type) {
41894                 var type = getTypeOfVariableOrParameterOrPropertyWorker(symbol);
41895                 // For a contextually typed parameter it is possible that a type has already
41896                 // been assigned (in assignTypeToParameterAndFixTypeParameters), and we want
41897                 // to preserve this type.
41898                 if (!links.type) {
41899                     links.type = type;
41900                 }
41901             }
41902             return links.type;
41903         }
41904         function getTypeOfVariableOrParameterOrPropertyWorker(symbol) {
41905             // Handle prototype property
41906             if (symbol.flags & 4194304 /* Prototype */) {
41907                 return getTypeOfPrototypeProperty(symbol);
41908             }
41909             // CommonsJS require and module both have type any.
41910             if (symbol === requireSymbol) {
41911                 return anyType;
41912             }
41913             if (symbol.flags & 134217728 /* ModuleExports */) {
41914                 var fileSymbol = getSymbolOfNode(ts.getSourceFileOfNode(symbol.valueDeclaration));
41915                 var members = ts.createSymbolTable();
41916                 members.set("exports", fileSymbol);
41917                 return createAnonymousType(symbol, members, ts.emptyArray, ts.emptyArray, undefined, undefined);
41918             }
41919             // Handle catch clause variables
41920             var declaration = symbol.valueDeclaration;
41921             if (ts.isCatchClauseVariableDeclarationOrBindingElement(declaration)) {
41922                 return anyType;
41923             }
41924             // Handle export default expressions
41925             if (ts.isSourceFile(declaration) && ts.isJsonSourceFile(declaration)) {
41926                 if (!declaration.statements.length) {
41927                     return emptyObjectType;
41928                 }
41929                 return getWidenedType(getWidenedLiteralType(checkExpression(declaration.statements[0].expression)));
41930             }
41931             // Handle variable, parameter or property
41932             if (!pushTypeResolution(symbol, 0 /* Type */)) {
41933                 // Symbol is property of some kind that is merged with something - should use `getTypeOfFuncClassEnumModule` and not `getTypeOfVariableOrParameterOrProperty`
41934                 if (symbol.flags & 512 /* ValueModule */ && !(symbol.flags & 67108864 /* Assignment */)) {
41935                     return getTypeOfFuncClassEnumModule(symbol);
41936                 }
41937                 return reportCircularityError(symbol);
41938             }
41939             var type;
41940             if (declaration.kind === 259 /* ExportAssignment */) {
41941                 type = widenTypeForVariableLikeDeclaration(checkExpressionCached(declaration.expression), declaration);
41942             }
41943             else if (ts.isBinaryExpression(declaration) ||
41944                 (ts.isInJSFile(declaration) &&
41945                     (ts.isCallExpression(declaration) || (ts.isPropertyAccessExpression(declaration) || ts.isBindableStaticElementAccessExpression(declaration)) && ts.isBinaryExpression(declaration.parent)))) {
41946                 type = getWidenedTypeForAssignmentDeclaration(symbol);
41947             }
41948             else if (ts.isJSDocPropertyLikeTag(declaration)
41949                 || ts.isPropertyAccessExpression(declaration)
41950                 || ts.isElementAccessExpression(declaration)
41951                 || ts.isIdentifier(declaration)
41952                 || ts.isStringLiteralLike(declaration)
41953                 || ts.isNumericLiteral(declaration)
41954                 || ts.isClassDeclaration(declaration)
41955                 || ts.isFunctionDeclaration(declaration)
41956                 || (ts.isMethodDeclaration(declaration) && !ts.isObjectLiteralMethod(declaration))
41957                 || ts.isMethodSignature(declaration)
41958                 || ts.isSourceFile(declaration)) {
41959                 // Symbol is property of some kind that is merged with something - should use `getTypeOfFuncClassEnumModule` and not `getTypeOfVariableOrParameterOrProperty`
41960                 if (symbol.flags & (16 /* Function */ | 8192 /* Method */ | 32 /* Class */ | 384 /* Enum */ | 512 /* ValueModule */)) {
41961                     return getTypeOfFuncClassEnumModule(symbol);
41962                 }
41963                 type = ts.isBinaryExpression(declaration.parent) ?
41964                     getWidenedTypeForAssignmentDeclaration(symbol) :
41965                     tryGetTypeFromEffectiveTypeNode(declaration) || anyType;
41966             }
41967             else if (ts.isPropertyAssignment(declaration)) {
41968                 type = tryGetTypeFromEffectiveTypeNode(declaration) || checkPropertyAssignment(declaration);
41969             }
41970             else if (ts.isJsxAttribute(declaration)) {
41971                 type = tryGetTypeFromEffectiveTypeNode(declaration) || checkJsxAttribute(declaration);
41972             }
41973             else if (ts.isShorthandPropertyAssignment(declaration)) {
41974                 type = tryGetTypeFromEffectiveTypeNode(declaration) || checkExpressionForMutableLocation(declaration.name, 0 /* Normal */);
41975             }
41976             else if (ts.isObjectLiteralMethod(declaration)) {
41977                 type = tryGetTypeFromEffectiveTypeNode(declaration) || checkObjectLiteralMethod(declaration, 0 /* Normal */);
41978             }
41979             else if (ts.isParameter(declaration)
41980                 || ts.isPropertyDeclaration(declaration)
41981                 || ts.isPropertySignature(declaration)
41982                 || ts.isVariableDeclaration(declaration)
41983                 || ts.isBindingElement(declaration)) {
41984                 type = getWidenedTypeForVariableLikeDeclaration(declaration, /*includeOptionality*/ true);
41985             }
41986             // getTypeOfSymbol dispatches some JS merges incorrectly because their symbol flags are not mutually exclusive.
41987             // Re-dispatch based on valueDeclaration.kind instead.
41988             else if (ts.isEnumDeclaration(declaration)) {
41989                 type = getTypeOfFuncClassEnumModule(symbol);
41990             }
41991             else if (ts.isEnumMember(declaration)) {
41992                 type = getTypeOfEnumMember(symbol);
41993             }
41994             else if (ts.isAccessor(declaration)) {
41995                 type = resolveTypeOfAccessors(symbol);
41996             }
41997             else {
41998                 return ts.Debug.fail("Unhandled declaration kind! " + ts.Debug.formatSyntaxKind(declaration.kind) + " for " + ts.Debug.formatSymbol(symbol));
41999             }
42000             if (!popTypeResolution()) {
42001                 // Symbol is property of some kind that is merged with something - should use `getTypeOfFuncClassEnumModule` and not `getTypeOfVariableOrParameterOrProperty`
42002                 if (symbol.flags & 512 /* ValueModule */ && !(symbol.flags & 67108864 /* Assignment */)) {
42003                     return getTypeOfFuncClassEnumModule(symbol);
42004                 }
42005                 return reportCircularityError(symbol);
42006             }
42007             return type;
42008         }
42009         function getAnnotatedAccessorTypeNode(accessor) {
42010             if (accessor) {
42011                 if (accessor.kind === 163 /* GetAccessor */) {
42012                     var getterTypeAnnotation = ts.getEffectiveReturnTypeNode(accessor);
42013                     return getterTypeAnnotation;
42014                 }
42015                 else {
42016                     var setterTypeAnnotation = ts.getEffectiveSetAccessorTypeAnnotationNode(accessor);
42017                     return setterTypeAnnotation;
42018                 }
42019             }
42020             return undefined;
42021         }
42022         function getAnnotatedAccessorType(accessor) {
42023             var node = getAnnotatedAccessorTypeNode(accessor);
42024             return node && getTypeFromTypeNode(node);
42025         }
42026         function getAnnotatedAccessorThisParameter(accessor) {
42027             var parameter = getAccessorThisParameter(accessor);
42028             return parameter && parameter.symbol;
42029         }
42030         function getThisTypeOfDeclaration(declaration) {
42031             return getThisTypeOfSignature(getSignatureFromDeclaration(declaration));
42032         }
42033         function getTypeOfAccessors(symbol) {
42034             var links = getSymbolLinks(symbol);
42035             return links.type || (links.type = getTypeOfAccessorsWorker(symbol));
42036         }
42037         function getTypeOfAccessorsWorker(symbol) {
42038             if (!pushTypeResolution(symbol, 0 /* Type */)) {
42039                 return errorType;
42040             }
42041             var type = resolveTypeOfAccessors(symbol);
42042             if (!popTypeResolution()) {
42043                 type = anyType;
42044                 if (noImplicitAny) {
42045                     var getter = ts.getDeclarationOfKind(symbol, 163 /* GetAccessor */);
42046                     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));
42047                 }
42048             }
42049             return type;
42050         }
42051         function resolveTypeOfAccessors(symbol) {
42052             var getter = ts.getDeclarationOfKind(symbol, 163 /* GetAccessor */);
42053             var setter = ts.getDeclarationOfKind(symbol, 164 /* SetAccessor */);
42054             if (getter && ts.isInJSFile(getter)) {
42055                 var jsDocType = getTypeForDeclarationFromJSDocComment(getter);
42056                 if (jsDocType) {
42057                     return jsDocType;
42058                 }
42059             }
42060             // First try to see if the user specified a return type on the get-accessor.
42061             var getterReturnType = getAnnotatedAccessorType(getter);
42062             if (getterReturnType) {
42063                 return getterReturnType;
42064             }
42065             else {
42066                 // If the user didn't specify a return type, try to use the set-accessor's parameter type.
42067                 var setterParameterType = getAnnotatedAccessorType(setter);
42068                 if (setterParameterType) {
42069                     return setterParameterType;
42070                 }
42071                 else {
42072                     // If there are no specified types, try to infer it from the body of the get accessor if it exists.
42073                     if (getter && getter.body) {
42074                         return getReturnTypeFromBody(getter);
42075                     }
42076                     // Otherwise, fall back to 'any'.
42077                     else {
42078                         if (setter) {
42079                             if (!isPrivateWithinAmbient(setter)) {
42080                                 errorOrSuggestion(noImplicitAny, setter, ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation, symbolToString(symbol));
42081                             }
42082                         }
42083                         else {
42084                             ts.Debug.assert(!!getter, "there must exist a getter as we are current checking either setter or getter in this function");
42085                             if (!isPrivateWithinAmbient(getter)) {
42086                                 errorOrSuggestion(noImplicitAny, getter, ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation, symbolToString(symbol));
42087                             }
42088                         }
42089                         return anyType;
42090                     }
42091                 }
42092             }
42093         }
42094         function getBaseTypeVariableOfClass(symbol) {
42095             var baseConstructorType = getBaseConstructorTypeOfClass(getDeclaredTypeOfClassOrInterface(symbol));
42096             return baseConstructorType.flags & 8650752 /* TypeVariable */ ? baseConstructorType :
42097                 baseConstructorType.flags & 2097152 /* Intersection */ ? ts.find(baseConstructorType.types, function (t) { return !!(t.flags & 8650752 /* TypeVariable */); }) :
42098                     undefined;
42099         }
42100         function getTypeOfFuncClassEnumModule(symbol) {
42101             var links = getSymbolLinks(symbol);
42102             var originalLinks = links;
42103             if (!links.type) {
42104                 var jsDeclaration = symbol.valueDeclaration && ts.getDeclarationOfExpando(symbol.valueDeclaration);
42105                 if (jsDeclaration) {
42106                     var merged = mergeJSSymbols(symbol, getSymbolOfNode(jsDeclaration));
42107                     if (merged) {
42108                         // note:we overwrite links because we just cloned the symbol
42109                         symbol = links = merged;
42110                     }
42111                 }
42112                 originalLinks.type = links.type = getTypeOfFuncClassEnumModuleWorker(symbol);
42113             }
42114             return links.type;
42115         }
42116         function getTypeOfFuncClassEnumModuleWorker(symbol) {
42117             var declaration = symbol.valueDeclaration;
42118             if (symbol.flags & 1536 /* Module */ && ts.isShorthandAmbientModuleSymbol(symbol)) {
42119                 return anyType;
42120             }
42121             else if (declaration && (declaration.kind === 209 /* BinaryExpression */ ||
42122                 ts.isAccessExpression(declaration) &&
42123                     declaration.parent.kind === 209 /* BinaryExpression */)) {
42124                 return getWidenedTypeForAssignmentDeclaration(symbol);
42125             }
42126             else if (symbol.flags & 512 /* ValueModule */ && declaration && ts.isSourceFile(declaration) && declaration.commonJsModuleIndicator) {
42127                 var resolvedModule = resolveExternalModuleSymbol(symbol);
42128                 if (resolvedModule !== symbol) {
42129                     if (!pushTypeResolution(symbol, 0 /* Type */)) {
42130                         return errorType;
42131                     }
42132                     var exportEquals = getMergedSymbol(symbol.exports.get("export=" /* ExportEquals */));
42133                     var type_1 = getWidenedTypeForAssignmentDeclaration(exportEquals, exportEquals === resolvedModule ? undefined : resolvedModule);
42134                     if (!popTypeResolution()) {
42135                         return reportCircularityError(symbol);
42136                     }
42137                     return type_1;
42138                 }
42139             }
42140             var type = createObjectType(16 /* Anonymous */, symbol);
42141             if (symbol.flags & 32 /* Class */) {
42142                 var baseTypeVariable = getBaseTypeVariableOfClass(symbol);
42143                 return baseTypeVariable ? getIntersectionType([type, baseTypeVariable]) : type;
42144             }
42145             else {
42146                 return strictNullChecks && symbol.flags & 16777216 /* Optional */ ? getOptionalType(type) : type;
42147             }
42148         }
42149         function getTypeOfEnumMember(symbol) {
42150             var links = getSymbolLinks(symbol);
42151             return links.type || (links.type = getDeclaredTypeOfEnumMember(symbol));
42152         }
42153         function getTypeOfAlias(symbol) {
42154             var links = getSymbolLinks(symbol);
42155             if (!links.type) {
42156                 var targetSymbol = resolveAlias(symbol);
42157                 // It only makes sense to get the type of a value symbol. If the result of resolving
42158                 // the alias is not a value, then it has no type. To get the type associated with a
42159                 // type symbol, call getDeclaredTypeOfSymbol.
42160                 // This check is important because without it, a call to getTypeOfSymbol could end
42161                 // up recursively calling getTypeOfAlias, causing a stack overflow.
42162                 links.type = targetSymbol.flags & 111551 /* Value */
42163                     ? getTypeOfSymbol(targetSymbol)
42164                     : errorType;
42165             }
42166             return links.type;
42167         }
42168         function getTypeOfInstantiatedSymbol(symbol) {
42169             var links = getSymbolLinks(symbol);
42170             if (!links.type) {
42171                 if (!pushTypeResolution(symbol, 0 /* Type */)) {
42172                     return links.type = errorType;
42173                 }
42174                 var type = instantiateType(getTypeOfSymbol(links.target), links.mapper);
42175                 if (!popTypeResolution()) {
42176                     type = reportCircularityError(symbol);
42177                 }
42178                 links.type = type;
42179             }
42180             return links.type;
42181         }
42182         function reportCircularityError(symbol) {
42183             var declaration = symbol.valueDeclaration;
42184             // Check if variable has type annotation that circularly references the variable itself
42185             if (ts.getEffectiveTypeAnnotationNode(declaration)) {
42186                 error(symbol.valueDeclaration, ts.Diagnostics._0_is_referenced_directly_or_indirectly_in_its_own_type_annotation, symbolToString(symbol));
42187                 return errorType;
42188             }
42189             // Check if variable has initializer that circularly references the variable itself
42190             if (noImplicitAny && (declaration.kind !== 156 /* Parameter */ || declaration.initializer)) {
42191                 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));
42192             }
42193             // Circularities could also result from parameters in function expressions that end up
42194             // having themselves as contextual types following type argument inference. In those cases
42195             // we have already reported an implicit any error so we don't report anything here.
42196             return anyType;
42197         }
42198         function getTypeOfSymbolWithDeferredType(symbol) {
42199             var links = getSymbolLinks(symbol);
42200             if (!links.type) {
42201                 ts.Debug.assertIsDefined(links.deferralParent);
42202                 ts.Debug.assertIsDefined(links.deferralConstituents);
42203                 links.type = links.deferralParent.flags & 1048576 /* Union */ ? getUnionType(links.deferralConstituents) : getIntersectionType(links.deferralConstituents);
42204             }
42205             return links.type;
42206         }
42207         function getTypeOfSymbol(symbol) {
42208             var checkFlags = ts.getCheckFlags(symbol);
42209             if (checkFlags & 65536 /* DeferredType */) {
42210                 return getTypeOfSymbolWithDeferredType(symbol);
42211             }
42212             if (checkFlags & 1 /* Instantiated */) {
42213                 return getTypeOfInstantiatedSymbol(symbol);
42214             }
42215             if (checkFlags & 262144 /* Mapped */) {
42216                 return getTypeOfMappedSymbol(symbol);
42217             }
42218             if (checkFlags & 8192 /* ReverseMapped */) {
42219                 return getTypeOfReverseMappedSymbol(symbol);
42220             }
42221             if (symbol.flags & (3 /* Variable */ | 4 /* Property */)) {
42222                 return getTypeOfVariableOrParameterOrProperty(symbol);
42223             }
42224             if (symbol.flags & (16 /* Function */ | 8192 /* Method */ | 32 /* Class */ | 384 /* Enum */ | 512 /* ValueModule */)) {
42225                 return getTypeOfFuncClassEnumModule(symbol);
42226             }
42227             if (symbol.flags & 8 /* EnumMember */) {
42228                 return getTypeOfEnumMember(symbol);
42229             }
42230             if (symbol.flags & 98304 /* Accessor */) {
42231                 return getTypeOfAccessors(symbol);
42232             }
42233             if (symbol.flags & 2097152 /* Alias */) {
42234                 return getTypeOfAlias(symbol);
42235             }
42236             return errorType;
42237         }
42238         function isReferenceToType(type, target) {
42239             return type !== undefined
42240                 && target !== undefined
42241                 && (ts.getObjectFlags(type) & 4 /* Reference */) !== 0
42242                 && type.target === target;
42243         }
42244         function getTargetType(type) {
42245             return ts.getObjectFlags(type) & 4 /* Reference */ ? type.target : type;
42246         }
42247         // TODO: GH#18217 If `checkBase` is undefined, we should not call this because this will always return false.
42248         function hasBaseType(type, checkBase) {
42249             return check(type);
42250             function check(type) {
42251                 if (ts.getObjectFlags(type) & (3 /* ClassOrInterface */ | 4 /* Reference */)) {
42252                     var target = getTargetType(type);
42253                     return target === checkBase || ts.some(getBaseTypes(target), check);
42254                 }
42255                 else if (type.flags & 2097152 /* Intersection */) {
42256                     return ts.some(type.types, check);
42257                 }
42258                 return false;
42259             }
42260         }
42261         // Appends the type parameters given by a list of declarations to a set of type parameters and returns the resulting set.
42262         // The function allocates a new array if the input type parameter set is undefined, but otherwise it modifies the set
42263         // in-place and returns the same array.
42264         function appendTypeParameters(typeParameters, declarations) {
42265             for (var _i = 0, declarations_2 = declarations; _i < declarations_2.length; _i++) {
42266                 var declaration = declarations_2[_i];
42267                 typeParameters = ts.appendIfUnique(typeParameters, getDeclaredTypeOfTypeParameter(getSymbolOfNode(declaration)));
42268             }
42269             return typeParameters;
42270         }
42271         // Return the outer type parameters of a node or undefined if the node has no outer type parameters.
42272         function getOuterTypeParameters(node, includeThisTypes) {
42273             while (true) {
42274                 node = node.parent; // TODO: GH#18217 Use SourceFile kind check instead
42275                 if (node && ts.isBinaryExpression(node)) {
42276                     // prototype assignments get the outer type parameters of their constructor function
42277                     var assignmentKind = ts.getAssignmentDeclarationKind(node);
42278                     if (assignmentKind === 6 /* Prototype */ || assignmentKind === 3 /* PrototypeProperty */) {
42279                         var symbol = getSymbolOfNode(node.left);
42280                         if (symbol && symbol.parent && !ts.findAncestor(symbol.parent.valueDeclaration, function (d) { return node === d; })) {
42281                             node = symbol.parent.valueDeclaration;
42282                         }
42283                     }
42284                 }
42285                 if (!node) {
42286                     return undefined;
42287                 }
42288                 switch (node.kind) {
42289                     case 225 /* VariableStatement */:
42290                     case 245 /* ClassDeclaration */:
42291                     case 214 /* ClassExpression */:
42292                     case 246 /* InterfaceDeclaration */:
42293                     case 165 /* CallSignature */:
42294                     case 166 /* ConstructSignature */:
42295                     case 160 /* MethodSignature */:
42296                     case 170 /* FunctionType */:
42297                     case 171 /* ConstructorType */:
42298                     case 300 /* JSDocFunctionType */:
42299                     case 244 /* FunctionDeclaration */:
42300                     case 161 /* MethodDeclaration */:
42301                     case 201 /* FunctionExpression */:
42302                     case 202 /* ArrowFunction */:
42303                     case 247 /* TypeAliasDeclaration */:
42304                     case 321 /* JSDocTemplateTag */:
42305                     case 322 /* JSDocTypedefTag */:
42306                     case 316 /* JSDocEnumTag */:
42307                     case 315 /* JSDocCallbackTag */:
42308                     case 186 /* MappedType */:
42309                     case 180 /* ConditionalType */:
42310                         var outerTypeParameters = getOuterTypeParameters(node, includeThisTypes);
42311                         if (node.kind === 186 /* MappedType */) {
42312                             return ts.append(outerTypeParameters, getDeclaredTypeOfTypeParameter(getSymbolOfNode(node.typeParameter)));
42313                         }
42314                         else if (node.kind === 180 /* ConditionalType */) {
42315                             return ts.concatenate(outerTypeParameters, getInferTypeParameters(node));
42316                         }
42317                         else if (node.kind === 225 /* VariableStatement */ && !ts.isInJSFile(node)) {
42318                             break;
42319                         }
42320                         var outerAndOwnTypeParameters = appendTypeParameters(outerTypeParameters, ts.getEffectiveTypeParameterDeclarations(node));
42321                         var thisType = includeThisTypes &&
42322                             (node.kind === 245 /* ClassDeclaration */ || node.kind === 214 /* ClassExpression */ || node.kind === 246 /* InterfaceDeclaration */ || isJSConstructor(node)) &&
42323                             getDeclaredTypeOfClassOrInterface(getSymbolOfNode(node)).thisType;
42324                         return thisType ? ts.append(outerAndOwnTypeParameters, thisType) : outerAndOwnTypeParameters;
42325                 }
42326             }
42327         }
42328         // The outer type parameters are those defined by enclosing generic classes, methods, or functions.
42329         function getOuterTypeParametersOfClassOrInterface(symbol) {
42330             var declaration = symbol.flags & 32 /* Class */ ? symbol.valueDeclaration : ts.getDeclarationOfKind(symbol, 246 /* InterfaceDeclaration */);
42331             ts.Debug.assert(!!declaration, "Class was missing valueDeclaration -OR- non-class had no interface declarations");
42332             return getOuterTypeParameters(declaration);
42333         }
42334         // The local type parameters are the combined set of type parameters from all declarations of the class,
42335         // interface, or type alias.
42336         function getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol) {
42337             var result;
42338             for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) {
42339                 var node = _a[_i];
42340                 if (node.kind === 246 /* InterfaceDeclaration */ ||
42341                     node.kind === 245 /* ClassDeclaration */ ||
42342                     node.kind === 214 /* ClassExpression */ ||
42343                     isJSConstructor(node) ||
42344                     ts.isTypeAlias(node)) {
42345                     var declaration = node;
42346                     result = appendTypeParameters(result, ts.getEffectiveTypeParameterDeclarations(declaration));
42347                 }
42348             }
42349             return result;
42350         }
42351         // The full set of type parameters for a generic class or interface type consists of its outer type parameters plus
42352         // its locally declared type parameters.
42353         function getTypeParametersOfClassOrInterface(symbol) {
42354             return ts.concatenate(getOuterTypeParametersOfClassOrInterface(symbol), getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol));
42355         }
42356         // A type is a mixin constructor if it has a single construct signature taking no type parameters and a single
42357         // rest parameter of type any[].
42358         function isMixinConstructorType(type) {
42359             var signatures = getSignaturesOfType(type, 1 /* Construct */);
42360             if (signatures.length === 1) {
42361                 var s = signatures[0];
42362                 return !s.typeParameters && s.parameters.length === 1 && signatureHasRestParameter(s) && getElementTypeOfArrayType(getTypeOfParameter(s.parameters[0])) === anyType;
42363             }
42364             return false;
42365         }
42366         function isConstructorType(type) {
42367             if (getSignaturesOfType(type, 1 /* Construct */).length > 0) {
42368                 return true;
42369             }
42370             if (type.flags & 8650752 /* TypeVariable */) {
42371                 var constraint = getBaseConstraintOfType(type);
42372                 return !!constraint && isMixinConstructorType(constraint);
42373             }
42374             return false;
42375         }
42376         function getBaseTypeNodeOfClass(type) {
42377             return ts.getEffectiveBaseTypeNode(type.symbol.valueDeclaration);
42378         }
42379         function getConstructorsForTypeArguments(type, typeArgumentNodes, location) {
42380             var typeArgCount = ts.length(typeArgumentNodes);
42381             var isJavascript = ts.isInJSFile(location);
42382             return ts.filter(getSignaturesOfType(type, 1 /* Construct */), function (sig) { return (isJavascript || typeArgCount >= getMinTypeArgumentCount(sig.typeParameters)) && typeArgCount <= ts.length(sig.typeParameters); });
42383         }
42384         function getInstantiatedConstructorsForTypeArguments(type, typeArgumentNodes, location) {
42385             var signatures = getConstructorsForTypeArguments(type, typeArgumentNodes, location);
42386             var typeArguments = ts.map(typeArgumentNodes, getTypeFromTypeNode);
42387             return ts.sameMap(signatures, function (sig) { return ts.some(sig.typeParameters) ? getSignatureInstantiation(sig, typeArguments, ts.isInJSFile(location)) : sig; });
42388         }
42389         /**
42390          * The base constructor of a class can resolve to
42391          * * undefinedType if the class has no extends clause,
42392          * * unknownType if an error occurred during resolution of the extends expression,
42393          * * nullType if the extends expression is the null value,
42394          * * anyType if the extends expression has type any, or
42395          * * an object type with at least one construct signature.
42396          */
42397         function getBaseConstructorTypeOfClass(type) {
42398             if (!type.resolvedBaseConstructorType) {
42399                 var decl = type.symbol.valueDeclaration;
42400                 var extended = ts.getEffectiveBaseTypeNode(decl);
42401                 var baseTypeNode = getBaseTypeNodeOfClass(type);
42402                 if (!baseTypeNode) {
42403                     return type.resolvedBaseConstructorType = undefinedType;
42404                 }
42405                 if (!pushTypeResolution(type, 1 /* ResolvedBaseConstructorType */)) {
42406                     return errorType;
42407                 }
42408                 var baseConstructorType = checkExpression(baseTypeNode.expression);
42409                 if (extended && baseTypeNode !== extended) {
42410                     ts.Debug.assert(!extended.typeArguments); // Because this is in a JS file, and baseTypeNode is in an @extends tag
42411                     checkExpression(extended.expression);
42412                 }
42413                 if (baseConstructorType.flags & (524288 /* Object */ | 2097152 /* Intersection */)) {
42414                     // Resolving the members of a class requires us to resolve the base class of that class.
42415                     // We force resolution here such that we catch circularities now.
42416                     resolveStructuredTypeMembers(baseConstructorType);
42417                 }
42418                 if (!popTypeResolution()) {
42419                     error(type.symbol.valueDeclaration, ts.Diagnostics._0_is_referenced_directly_or_indirectly_in_its_own_base_expression, symbolToString(type.symbol));
42420                     return type.resolvedBaseConstructorType = errorType;
42421                 }
42422                 if (!(baseConstructorType.flags & 1 /* Any */) && baseConstructorType !== nullWideningType && !isConstructorType(baseConstructorType)) {
42423                     var err = error(baseTypeNode.expression, ts.Diagnostics.Type_0_is_not_a_constructor_function_type, typeToString(baseConstructorType));
42424                     if (baseConstructorType.flags & 262144 /* TypeParameter */) {
42425                         var constraint = getConstraintFromTypeParameter(baseConstructorType);
42426                         var ctorReturn = unknownType;
42427                         if (constraint) {
42428                             var ctorSig = getSignaturesOfType(constraint, 1 /* Construct */);
42429                             if (ctorSig[0]) {
42430                                 ctorReturn = getReturnTypeOfSignature(ctorSig[0]);
42431                             }
42432                         }
42433                         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)));
42434                     }
42435                     return type.resolvedBaseConstructorType = errorType;
42436                 }
42437                 type.resolvedBaseConstructorType = baseConstructorType;
42438             }
42439             return type.resolvedBaseConstructorType;
42440         }
42441         function getImplementsTypes(type) {
42442             var resolvedImplementsTypes = ts.emptyArray;
42443             for (var _i = 0, _a = type.symbol.declarations; _i < _a.length; _i++) {
42444                 var declaration = _a[_i];
42445                 var implementsTypeNodes = ts.getEffectiveImplementsTypeNodes(declaration);
42446                 if (!implementsTypeNodes)
42447                     continue;
42448                 for (var _b = 0, implementsTypeNodes_1 = implementsTypeNodes; _b < implementsTypeNodes_1.length; _b++) {
42449                     var node = implementsTypeNodes_1[_b];
42450                     var implementsType = getTypeFromTypeNode(node);
42451                     if (implementsType !== errorType) {
42452                         if (resolvedImplementsTypes === ts.emptyArray) {
42453                             resolvedImplementsTypes = [implementsType];
42454                         }
42455                         else {
42456                             resolvedImplementsTypes.push(implementsType);
42457                         }
42458                     }
42459                 }
42460             }
42461             return resolvedImplementsTypes;
42462         }
42463         function getBaseTypes(type) {
42464             if (!type.resolvedBaseTypes) {
42465                 if (type.objectFlags & 8 /* Tuple */) {
42466                     type.resolvedBaseTypes = [createArrayType(getUnionType(type.typeParameters || ts.emptyArray), type.readonly)];
42467                 }
42468                 else if (type.symbol.flags & (32 /* Class */ | 64 /* Interface */)) {
42469                     if (type.symbol.flags & 32 /* Class */) {
42470                         resolveBaseTypesOfClass(type);
42471                     }
42472                     if (type.symbol.flags & 64 /* Interface */) {
42473                         resolveBaseTypesOfInterface(type);
42474                     }
42475                 }
42476                 else {
42477                     ts.Debug.fail("type must be class or interface");
42478                 }
42479             }
42480             return type.resolvedBaseTypes;
42481         }
42482         function resolveBaseTypesOfClass(type) {
42483             type.resolvedBaseTypes = ts.resolvingEmptyArray;
42484             var baseConstructorType = getApparentType(getBaseConstructorTypeOfClass(type));
42485             if (!(baseConstructorType.flags & (524288 /* Object */ | 2097152 /* Intersection */ | 1 /* Any */))) {
42486                 return type.resolvedBaseTypes = ts.emptyArray;
42487             }
42488             var baseTypeNode = getBaseTypeNodeOfClass(type);
42489             var baseType;
42490             var originalBaseType = baseConstructorType.symbol ? getDeclaredTypeOfSymbol(baseConstructorType.symbol) : undefined;
42491             if (baseConstructorType.symbol && baseConstructorType.symbol.flags & 32 /* Class */ &&
42492                 areAllOuterTypeParametersApplied(originalBaseType)) {
42493                 // 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
42494                 // class and all return the instance type of the class. There is no need for further checks and we can apply the
42495                 // type arguments in the same manner as a type reference to get the same error reporting experience.
42496                 baseType = getTypeFromClassOrInterfaceReference(baseTypeNode, baseConstructorType.symbol);
42497             }
42498             else if (baseConstructorType.flags & 1 /* Any */) {
42499                 baseType = baseConstructorType;
42500             }
42501             else {
42502                 // The class derives from a "class-like" constructor function, check that we have at least one construct signature
42503                 // with a matching number of type parameters and use the return type of the first instantiated signature. Elsewhere
42504                 // we check that all instantiated signatures return the same type.
42505                 var constructors = getInstantiatedConstructorsForTypeArguments(baseConstructorType, baseTypeNode.typeArguments, baseTypeNode);
42506                 if (!constructors.length) {
42507                     error(baseTypeNode.expression, ts.Diagnostics.No_base_constructor_has_the_specified_number_of_type_arguments);
42508                     return type.resolvedBaseTypes = ts.emptyArray;
42509                 }
42510                 baseType = getReturnTypeOfSignature(constructors[0]);
42511             }
42512             if (baseType === errorType) {
42513                 return type.resolvedBaseTypes = ts.emptyArray;
42514             }
42515             var reducedBaseType = getReducedType(baseType);
42516             if (!isValidBaseType(reducedBaseType)) {
42517                 var elaboration = elaborateNeverIntersection(/*errorInfo*/ undefined, baseType);
42518                 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));
42519                 diagnostics.add(ts.createDiagnosticForNodeFromMessageChain(baseTypeNode.expression, diagnostic));
42520                 return type.resolvedBaseTypes = ts.emptyArray;
42521             }
42522             if (type === reducedBaseType || hasBaseType(reducedBaseType, type)) {
42523                 error(type.symbol.valueDeclaration, ts.Diagnostics.Type_0_recursively_references_itself_as_a_base_type, typeToString(type, /*enclosingDeclaration*/ undefined, 2 /* WriteArrayAsGenericType */));
42524                 return type.resolvedBaseTypes = ts.emptyArray;
42525             }
42526             if (type.resolvedBaseTypes === ts.resolvingEmptyArray) {
42527                 // Circular reference, likely through instantiation of default parameters
42528                 // (otherwise there'd be an error from hasBaseType) - this is fine, but `.members` should be reset
42529                 // as `getIndexedAccessType` via `instantiateType` via `getTypeFromClassOrInterfaceReference` forces a
42530                 // partial instantiation of the members without the base types fully resolved
42531                 type.members = undefined;
42532             }
42533             return type.resolvedBaseTypes = [reducedBaseType];
42534         }
42535         function areAllOuterTypeParametersApplied(type) {
42536             // An unapplied type parameter has its symbol still the same as the matching argument symbol.
42537             // Since parameters are applied outer-to-inner, only the last outer parameter needs to be checked.
42538             var outerTypeParameters = type.outerTypeParameters;
42539             if (outerTypeParameters) {
42540                 var last_1 = outerTypeParameters.length - 1;
42541                 var typeArguments = getTypeArguments(type);
42542                 return outerTypeParameters[last_1].symbol !== typeArguments[last_1].symbol;
42543             }
42544             return true;
42545         }
42546         // A valid base type is `any`, an object type or intersection of object types.
42547         function isValidBaseType(type) {
42548             if (type.flags & 262144 /* TypeParameter */) {
42549                 var constraint = getBaseConstraintOfType(type);
42550                 if (constraint) {
42551                     return isValidBaseType(constraint);
42552                 }
42553             }
42554             // TODO: Given that we allow type parmeters here now, is this `!isGenericMappedType(type)` check really needed?
42555             // There's no reason a `T` should be allowed while a `Readonly<T>` should not.
42556             return !!(type.flags & (524288 /* Object */ | 67108864 /* NonPrimitive */ | 1 /* Any */) && !isGenericMappedType(type) ||
42557                 type.flags & 2097152 /* Intersection */ && ts.every(type.types, isValidBaseType));
42558         }
42559         function resolveBaseTypesOfInterface(type) {
42560             type.resolvedBaseTypes = type.resolvedBaseTypes || ts.emptyArray;
42561             for (var _i = 0, _a = type.symbol.declarations; _i < _a.length; _i++) {
42562                 var declaration = _a[_i];
42563                 if (declaration.kind === 246 /* InterfaceDeclaration */ && ts.getInterfaceBaseTypeNodes(declaration)) {
42564                     for (var _b = 0, _c = ts.getInterfaceBaseTypeNodes(declaration); _b < _c.length; _b++) {
42565                         var node = _c[_b];
42566                         var baseType = getReducedType(getTypeFromTypeNode(node));
42567                         if (baseType !== errorType) {
42568                             if (isValidBaseType(baseType)) {
42569                                 if (type !== baseType && !hasBaseType(baseType, type)) {
42570                                     if (type.resolvedBaseTypes === ts.emptyArray) {
42571                                         type.resolvedBaseTypes = [baseType];
42572                                     }
42573                                     else {
42574                                         type.resolvedBaseTypes.push(baseType);
42575                                     }
42576                                 }
42577                                 else {
42578                                     error(declaration, ts.Diagnostics.Type_0_recursively_references_itself_as_a_base_type, typeToString(type, /*enclosingDeclaration*/ undefined, 2 /* WriteArrayAsGenericType */));
42579                                 }
42580                             }
42581                             else {
42582                                 error(node, ts.Diagnostics.An_interface_can_only_extend_an_object_type_or_intersection_of_object_types_with_statically_known_members);
42583                             }
42584                         }
42585                     }
42586                 }
42587             }
42588         }
42589         /**
42590          * Returns true if the interface given by the symbol is free of "this" references.
42591          *
42592          * Specifically, the result is true if the interface itself contains no references
42593          * to "this" in its body, if all base types are interfaces,
42594          * and if none of the base interfaces have a "this" type.
42595          */
42596         function isThislessInterface(symbol) {
42597             for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) {
42598                 var declaration = _a[_i];
42599                 if (declaration.kind === 246 /* InterfaceDeclaration */) {
42600                     if (declaration.flags & 128 /* ContainsThis */) {
42601                         return false;
42602                     }
42603                     var baseTypeNodes = ts.getInterfaceBaseTypeNodes(declaration);
42604                     if (baseTypeNodes) {
42605                         for (var _b = 0, baseTypeNodes_1 = baseTypeNodes; _b < baseTypeNodes_1.length; _b++) {
42606                             var node = baseTypeNodes_1[_b];
42607                             if (ts.isEntityNameExpression(node.expression)) {
42608                                 var baseSymbol = resolveEntityName(node.expression, 788968 /* Type */, /*ignoreErrors*/ true);
42609                                 if (!baseSymbol || !(baseSymbol.flags & 64 /* Interface */) || getDeclaredTypeOfClassOrInterface(baseSymbol).thisType) {
42610                                     return false;
42611                                 }
42612                             }
42613                         }
42614                     }
42615                 }
42616             }
42617             return true;
42618         }
42619         function getDeclaredTypeOfClassOrInterface(symbol) {
42620             var links = getSymbolLinks(symbol);
42621             var originalLinks = links;
42622             if (!links.declaredType) {
42623                 var kind = symbol.flags & 32 /* Class */ ? 1 /* Class */ : 2 /* Interface */;
42624                 var merged = mergeJSSymbols(symbol, getAssignedClassSymbol(symbol.valueDeclaration));
42625                 if (merged) {
42626                     // note:we overwrite links because we just cloned the symbol
42627                     symbol = links = merged;
42628                 }
42629                 var type = originalLinks.declaredType = links.declaredType = createObjectType(kind, symbol);
42630                 var outerTypeParameters = getOuterTypeParametersOfClassOrInterface(symbol);
42631                 var localTypeParameters = getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol);
42632                 // A class or interface is generic if it has type parameters or a "this" type. We always give classes a "this" type
42633                 // because it is not feasible to analyze all members to determine if the "this" type escapes the class (in particular,
42634                 // property types inferred from initializers and method return types inferred from return statements are very hard
42635                 // to exhaustively analyze). We give interfaces a "this" type if we can't definitely determine that they are free of
42636                 // "this" references.
42637                 if (outerTypeParameters || localTypeParameters || kind === 1 /* Class */ || !isThislessInterface(symbol)) {
42638                     type.objectFlags |= 4 /* Reference */;
42639                     type.typeParameters = ts.concatenate(outerTypeParameters, localTypeParameters);
42640                     type.outerTypeParameters = outerTypeParameters;
42641                     type.localTypeParameters = localTypeParameters;
42642                     type.instantiations = ts.createMap();
42643                     type.instantiations.set(getTypeListId(type.typeParameters), type);
42644                     type.target = type;
42645                     type.resolvedTypeArguments = type.typeParameters;
42646                     type.thisType = createTypeParameter(symbol);
42647                     type.thisType.isThisType = true;
42648                     type.thisType.constraint = type;
42649                 }
42650             }
42651             return links.declaredType;
42652         }
42653         function getDeclaredTypeOfTypeAlias(symbol) {
42654             var links = getSymbolLinks(symbol);
42655             if (!links.declaredType) {
42656                 // Note that we use the links object as the target here because the symbol object is used as the unique
42657                 // identity for resolution of the 'type' property in SymbolLinks.
42658                 if (!pushTypeResolution(symbol, 2 /* DeclaredType */)) {
42659                     return errorType;
42660                 }
42661                 var declaration = ts.Debug.checkDefined(ts.find(symbol.declarations, ts.isTypeAlias), "Type alias symbol with no valid declaration found");
42662                 var typeNode = ts.isJSDocTypeAlias(declaration) ? declaration.typeExpression : declaration.type;
42663                 // If typeNode is missing, we will error in checkJSDocTypedefTag.
42664                 var type = typeNode ? getTypeFromTypeNode(typeNode) : errorType;
42665                 if (popTypeResolution()) {
42666                     var typeParameters = getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol);
42667                     if (typeParameters) {
42668                         // Initialize the instantiation cache for generic type aliases. The declared type corresponds to
42669                         // an instantiation of the type alias with the type parameters supplied as type arguments.
42670                         links.typeParameters = typeParameters;
42671                         links.instantiations = ts.createMap();
42672                         links.instantiations.set(getTypeListId(typeParameters), type);
42673                     }
42674                 }
42675                 else {
42676                     type = errorType;
42677                     error(ts.isNamedDeclaration(declaration) ? declaration.name : declaration || declaration, ts.Diagnostics.Type_alias_0_circularly_references_itself, symbolToString(symbol));
42678                 }
42679                 links.declaredType = type;
42680             }
42681             return links.declaredType;
42682         }
42683         function isStringConcatExpression(expr) {
42684             if (ts.isStringLiteralLike(expr)) {
42685                 return true;
42686             }
42687             else if (expr.kind === 209 /* BinaryExpression */) {
42688                 return isStringConcatExpression(expr.left) && isStringConcatExpression(expr.right);
42689             }
42690             return false;
42691         }
42692         function isLiteralEnumMember(member) {
42693             var expr = member.initializer;
42694             if (!expr) {
42695                 return !(member.flags & 8388608 /* Ambient */);
42696             }
42697             switch (expr.kind) {
42698                 case 10 /* StringLiteral */:
42699                 case 8 /* NumericLiteral */:
42700                 case 14 /* NoSubstitutionTemplateLiteral */:
42701                     return true;
42702                 case 207 /* PrefixUnaryExpression */:
42703                     return expr.operator === 40 /* MinusToken */ &&
42704                         expr.operand.kind === 8 /* NumericLiteral */;
42705                 case 75 /* Identifier */:
42706                     return ts.nodeIsMissing(expr) || !!getSymbolOfNode(member.parent).exports.get(expr.escapedText);
42707                 case 209 /* BinaryExpression */:
42708                     return isStringConcatExpression(expr);
42709                 default:
42710                     return false;
42711             }
42712         }
42713         function getEnumKind(symbol) {
42714             var links = getSymbolLinks(symbol);
42715             if (links.enumKind !== undefined) {
42716                 return links.enumKind;
42717             }
42718             var hasNonLiteralMember = false;
42719             for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) {
42720                 var declaration = _a[_i];
42721                 if (declaration.kind === 248 /* EnumDeclaration */) {
42722                     for (var _b = 0, _c = declaration.members; _b < _c.length; _b++) {
42723                         var member = _c[_b];
42724                         if (member.initializer && ts.isStringLiteralLike(member.initializer)) {
42725                             return links.enumKind = 1 /* Literal */;
42726                         }
42727                         if (!isLiteralEnumMember(member)) {
42728                             hasNonLiteralMember = true;
42729                         }
42730                     }
42731                 }
42732             }
42733             return links.enumKind = hasNonLiteralMember ? 0 /* Numeric */ : 1 /* Literal */;
42734         }
42735         function getBaseTypeOfEnumLiteralType(type) {
42736             return type.flags & 1024 /* EnumLiteral */ && !(type.flags & 1048576 /* Union */) ? getDeclaredTypeOfSymbol(getParentOfSymbol(type.symbol)) : type;
42737         }
42738         function getDeclaredTypeOfEnum(symbol) {
42739             var links = getSymbolLinks(symbol);
42740             if (links.declaredType) {
42741                 return links.declaredType;
42742             }
42743             if (getEnumKind(symbol) === 1 /* Literal */) {
42744                 enumCount++;
42745                 var memberTypeList = [];
42746                 for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) {
42747                     var declaration = _a[_i];
42748                     if (declaration.kind === 248 /* EnumDeclaration */) {
42749                         for (var _b = 0, _c = declaration.members; _b < _c.length; _b++) {
42750                             var member = _c[_b];
42751                             var value = getEnumMemberValue(member);
42752                             var memberType = getFreshTypeOfLiteralType(getLiteralType(value !== undefined ? value : 0, enumCount, getSymbolOfNode(member)));
42753                             getSymbolLinks(getSymbolOfNode(member)).declaredType = memberType;
42754                             memberTypeList.push(getRegularTypeOfLiteralType(memberType));
42755                         }
42756                     }
42757                 }
42758                 if (memberTypeList.length) {
42759                     var enumType_1 = getUnionType(memberTypeList, 1 /* Literal */, symbol, /*aliasTypeArguments*/ undefined);
42760                     if (enumType_1.flags & 1048576 /* Union */) {
42761                         enumType_1.flags |= 1024 /* EnumLiteral */;
42762                         enumType_1.symbol = symbol;
42763                     }
42764                     return links.declaredType = enumType_1;
42765                 }
42766             }
42767             var enumType = createType(32 /* Enum */);
42768             enumType.symbol = symbol;
42769             return links.declaredType = enumType;
42770         }
42771         function getDeclaredTypeOfEnumMember(symbol) {
42772             var links = getSymbolLinks(symbol);
42773             if (!links.declaredType) {
42774                 var enumType = getDeclaredTypeOfEnum(getParentOfSymbol(symbol));
42775                 if (!links.declaredType) {
42776                     links.declaredType = enumType;
42777                 }
42778             }
42779             return links.declaredType;
42780         }
42781         function getDeclaredTypeOfTypeParameter(symbol) {
42782             var links = getSymbolLinks(symbol);
42783             return links.declaredType || (links.declaredType = createTypeParameter(symbol));
42784         }
42785         function getDeclaredTypeOfAlias(symbol) {
42786             var links = getSymbolLinks(symbol);
42787             return links.declaredType || (links.declaredType = getDeclaredTypeOfSymbol(resolveAlias(symbol)));
42788         }
42789         function getDeclaredTypeOfSymbol(symbol) {
42790             return tryGetDeclaredTypeOfSymbol(symbol) || errorType;
42791         }
42792         function tryGetDeclaredTypeOfSymbol(symbol) {
42793             if (symbol.flags & (32 /* Class */ | 64 /* Interface */)) {
42794                 return getDeclaredTypeOfClassOrInterface(symbol);
42795             }
42796             if (symbol.flags & 524288 /* TypeAlias */) {
42797                 return getDeclaredTypeOfTypeAlias(symbol);
42798             }
42799             if (symbol.flags & 262144 /* TypeParameter */) {
42800                 return getDeclaredTypeOfTypeParameter(symbol);
42801             }
42802             if (symbol.flags & 384 /* Enum */) {
42803                 return getDeclaredTypeOfEnum(symbol);
42804             }
42805             if (symbol.flags & 8 /* EnumMember */) {
42806                 return getDeclaredTypeOfEnumMember(symbol);
42807             }
42808             if (symbol.flags & 2097152 /* Alias */) {
42809                 return getDeclaredTypeOfAlias(symbol);
42810             }
42811             return undefined;
42812         }
42813         /**
42814          * A type is free of this references if it's the any, string, number, boolean, symbol, or void keyword, a string
42815          * literal type, an array with an element type that is free of this references, or a type reference that is
42816          * free of this references.
42817          */
42818         function isThislessType(node) {
42819             switch (node.kind) {
42820                 case 125 /* AnyKeyword */:
42821                 case 148 /* UnknownKeyword */:
42822                 case 143 /* StringKeyword */:
42823                 case 140 /* NumberKeyword */:
42824                 case 151 /* BigIntKeyword */:
42825                 case 128 /* BooleanKeyword */:
42826                 case 144 /* SymbolKeyword */:
42827                 case 141 /* ObjectKeyword */:
42828                 case 110 /* VoidKeyword */:
42829                 case 146 /* UndefinedKeyword */:
42830                 case 100 /* NullKeyword */:
42831                 case 137 /* NeverKeyword */:
42832                 case 187 /* LiteralType */:
42833                     return true;
42834                 case 174 /* ArrayType */:
42835                     return isThislessType(node.elementType);
42836                 case 169 /* TypeReference */:
42837                     return !node.typeArguments || node.typeArguments.every(isThislessType);
42838             }
42839             return false;
42840         }
42841         /** A type parameter is thisless if its constraint is thisless, or if it has no constraint. */
42842         function isThislessTypeParameter(node) {
42843             var constraint = ts.getEffectiveConstraintOfTypeParameter(node);
42844             return !constraint || isThislessType(constraint);
42845         }
42846         /**
42847          * A variable-like declaration is free of this references if it has a type annotation
42848          * that is thisless, or if it has no type annotation and no initializer (and is thus of type any).
42849          */
42850         function isThislessVariableLikeDeclaration(node) {
42851             var typeNode = ts.getEffectiveTypeAnnotationNode(node);
42852             return typeNode ? isThislessType(typeNode) : !ts.hasInitializer(node);
42853         }
42854         /**
42855          * A function-like declaration is considered free of `this` references if it has a return type
42856          * annotation that is free of this references and if each parameter is thisless and if
42857          * each type parameter (if present) is thisless.
42858          */
42859         function isThislessFunctionLikeDeclaration(node) {
42860             var returnType = ts.getEffectiveReturnTypeNode(node);
42861             var typeParameters = ts.getEffectiveTypeParameterDeclarations(node);
42862             return (node.kind === 162 /* Constructor */ || (!!returnType && isThislessType(returnType))) &&
42863                 node.parameters.every(isThislessVariableLikeDeclaration) &&
42864                 typeParameters.every(isThislessTypeParameter);
42865         }
42866         /**
42867          * Returns true if the class or interface member given by the symbol is free of "this" references. The
42868          * function may return false for symbols that are actually free of "this" references because it is not
42869          * feasible to perform a complete analysis in all cases. In particular, property members with types
42870          * inferred from their initializers and function members with inferred return types are conservatively
42871          * assumed not to be free of "this" references.
42872          */
42873         function isThisless(symbol) {
42874             if (symbol.declarations && symbol.declarations.length === 1) {
42875                 var declaration = symbol.declarations[0];
42876                 if (declaration) {
42877                     switch (declaration.kind) {
42878                         case 159 /* PropertyDeclaration */:
42879                         case 158 /* PropertySignature */:
42880                             return isThislessVariableLikeDeclaration(declaration);
42881                         case 161 /* MethodDeclaration */:
42882                         case 160 /* MethodSignature */:
42883                         case 162 /* Constructor */:
42884                         case 163 /* GetAccessor */:
42885                         case 164 /* SetAccessor */:
42886                             return isThislessFunctionLikeDeclaration(declaration);
42887                     }
42888                 }
42889             }
42890             return false;
42891         }
42892         // The mappingThisOnly flag indicates that the only type parameter being mapped is "this". When the flag is true,
42893         // we check symbols to see if we can quickly conclude they are free of "this" references, thus needing no instantiation.
42894         function createInstantiatedSymbolTable(symbols, mapper, mappingThisOnly) {
42895             var result = ts.createSymbolTable();
42896             for (var _i = 0, symbols_2 = symbols; _i < symbols_2.length; _i++) {
42897                 var symbol = symbols_2[_i];
42898                 result.set(symbol.escapedName, mappingThisOnly && isThisless(symbol) ? symbol : instantiateSymbol(symbol, mapper));
42899             }
42900             return result;
42901         }
42902         function addInheritedMembers(symbols, baseSymbols) {
42903             for (var _i = 0, baseSymbols_1 = baseSymbols; _i < baseSymbols_1.length; _i++) {
42904                 var s = baseSymbols_1[_i];
42905                 if (!symbols.has(s.escapedName) && !isStaticPrivateIdentifierProperty(s)) {
42906                     symbols.set(s.escapedName, s);
42907                 }
42908             }
42909         }
42910         function isStaticPrivateIdentifierProperty(s) {
42911             return !!s.valueDeclaration && ts.isPrivateIdentifierPropertyDeclaration(s.valueDeclaration) && ts.hasModifier(s.valueDeclaration, 32 /* Static */);
42912         }
42913         function resolveDeclaredMembers(type) {
42914             if (!type.declaredProperties) {
42915                 var symbol = type.symbol;
42916                 var members = getMembersOfSymbol(symbol);
42917                 type.declaredProperties = getNamedMembers(members);
42918                 // Start with signatures at empty array in case of recursive types
42919                 type.declaredCallSignatures = ts.emptyArray;
42920                 type.declaredConstructSignatures = ts.emptyArray;
42921                 type.declaredCallSignatures = getSignaturesOfSymbol(members.get("__call" /* Call */));
42922                 type.declaredConstructSignatures = getSignaturesOfSymbol(members.get("__new" /* New */));
42923                 type.declaredStringIndexInfo = getIndexInfoOfSymbol(symbol, 0 /* String */);
42924                 type.declaredNumberIndexInfo = getIndexInfoOfSymbol(symbol, 1 /* Number */);
42925             }
42926             return type;
42927         }
42928         /**
42929          * Indicates whether a type can be used as a property name.
42930          */
42931         function isTypeUsableAsPropertyName(type) {
42932             return !!(type.flags & 8576 /* StringOrNumberLiteralOrUnique */);
42933         }
42934         /**
42935          * Indicates whether a declaration name is definitely late-bindable.
42936          * A declaration name is only late-bindable if:
42937          * - It is a `ComputedPropertyName`.
42938          * - Its expression is an `Identifier` or either a `PropertyAccessExpression` an
42939          * `ElementAccessExpression` consisting only of these same three types of nodes.
42940          * - The type of its expression is a string or numeric literal type, or is a `unique symbol` type.
42941          */
42942         function isLateBindableName(node) {
42943             if (!ts.isComputedPropertyName(node) && !ts.isElementAccessExpression(node)) {
42944                 return false;
42945             }
42946             var expr = ts.isComputedPropertyName(node) ? node.expression : node.argumentExpression;
42947             return ts.isEntityNameExpression(expr)
42948                 && isTypeUsableAsPropertyName(ts.isComputedPropertyName(node) ? checkComputedPropertyName(node) : checkExpressionCached(expr));
42949         }
42950         function isLateBoundName(name) {
42951             return name.charCodeAt(0) === 95 /* _ */ &&
42952                 name.charCodeAt(1) === 95 /* _ */ &&
42953                 name.charCodeAt(2) === 64 /* at */;
42954         }
42955         /**
42956          * Indicates whether a declaration has a late-bindable dynamic name.
42957          */
42958         function hasLateBindableName(node) {
42959             var name = ts.getNameOfDeclaration(node);
42960             return !!name && isLateBindableName(name);
42961         }
42962         /**
42963          * Indicates whether a declaration has a dynamic name that cannot be late-bound.
42964          */
42965         function hasNonBindableDynamicName(node) {
42966             return ts.hasDynamicName(node) && !hasLateBindableName(node);
42967         }
42968         /**
42969          * Indicates whether a declaration name is a dynamic name that cannot be late-bound.
42970          */
42971         function isNonBindableDynamicName(node) {
42972             return ts.isDynamicName(node) && !isLateBindableName(node);
42973         }
42974         /**
42975          * Gets the symbolic name for a member from its type.
42976          */
42977         function getPropertyNameFromType(type) {
42978             if (type.flags & 8192 /* UniqueESSymbol */) {
42979                 return type.escapedName;
42980             }
42981             if (type.flags & (128 /* StringLiteral */ | 256 /* NumberLiteral */)) {
42982                 return ts.escapeLeadingUnderscores("" + type.value);
42983             }
42984             return ts.Debug.fail();
42985         }
42986         /**
42987          * Adds a declaration to a late-bound dynamic member. This performs the same function for
42988          * late-bound members that `addDeclarationToSymbol` in binder.ts performs for early-bound
42989          * members.
42990          */
42991         function addDeclarationToLateBoundSymbol(symbol, member, symbolFlags) {
42992             ts.Debug.assert(!!(ts.getCheckFlags(symbol) & 4096 /* Late */), "Expected a late-bound symbol.");
42993             symbol.flags |= symbolFlags;
42994             getSymbolLinks(member.symbol).lateSymbol = symbol;
42995             if (!symbol.declarations) {
42996                 symbol.declarations = [member];
42997             }
42998             else {
42999                 symbol.declarations.push(member);
43000             }
43001             if (symbolFlags & 111551 /* Value */) {
43002                 if (!symbol.valueDeclaration || symbol.valueDeclaration.kind !== member.kind) {
43003                     symbol.valueDeclaration = member;
43004                 }
43005             }
43006         }
43007         /**
43008          * Performs late-binding of a dynamic member. This performs the same function for
43009          * late-bound members that `declareSymbol` in binder.ts performs for early-bound
43010          * members.
43011          *
43012          * If a symbol is a dynamic name from a computed property, we perform an additional "late"
43013          * binding phase to attempt to resolve the name for the symbol from the type of the computed
43014          * property's expression. If the type of the expression is a string-literal, numeric-literal,
43015          * or unique symbol type, we can use that type as the name of the symbol.
43016          *
43017          * For example, given:
43018          *
43019          *   const x = Symbol();
43020          *
43021          *   interface I {
43022          *     [x]: number;
43023          *   }
43024          *
43025          * The binder gives the property `[x]: number` a special symbol with the name "__computed".
43026          * In the late-binding phase we can type-check the expression `x` and see that it has a
43027          * unique symbol type which we can then use as the name of the member. This allows users
43028          * to define custom symbols that can be used in the members of an object type.
43029          *
43030          * @param parent The containing symbol for the member.
43031          * @param earlySymbols The early-bound symbols of the parent.
43032          * @param lateSymbols The late-bound symbols of the parent.
43033          * @param decl The member to bind.
43034          */
43035         function lateBindMember(parent, earlySymbols, lateSymbols, decl) {
43036             ts.Debug.assert(!!decl.symbol, "The member is expected to have a symbol.");
43037             var links = getNodeLinks(decl);
43038             if (!links.resolvedSymbol) {
43039                 // In the event we attempt to resolve the late-bound name of this member recursively,
43040                 // fall back to the early-bound name of this member.
43041                 links.resolvedSymbol = decl.symbol;
43042                 var declName = ts.isBinaryExpression(decl) ? decl.left : decl.name;
43043                 var type = ts.isElementAccessExpression(declName) ? checkExpressionCached(declName.argumentExpression) : checkComputedPropertyName(declName);
43044                 if (isTypeUsableAsPropertyName(type)) {
43045                     var memberName = getPropertyNameFromType(type);
43046                     var symbolFlags = decl.symbol.flags;
43047                     // Get or add a late-bound symbol for the member. This allows us to merge late-bound accessor declarations.
43048                     var lateSymbol = lateSymbols.get(memberName);
43049                     if (!lateSymbol)
43050                         lateSymbols.set(memberName, lateSymbol = createSymbol(0 /* None */, memberName, 4096 /* Late */));
43051                     // Report an error if a late-bound member has the same name as an early-bound member,
43052                     // or if we have another early-bound symbol declaration with the same name and
43053                     // conflicting flags.
43054                     var earlySymbol = earlySymbols && earlySymbols.get(memberName);
43055                     if (lateSymbol.flags & getExcludedSymbolFlags(symbolFlags) || earlySymbol) {
43056                         // If we have an existing early-bound member, combine its declarations so that we can
43057                         // report an error at each declaration.
43058                         var declarations = earlySymbol ? ts.concatenate(earlySymbol.declarations, lateSymbol.declarations) : lateSymbol.declarations;
43059                         var name_3 = !(type.flags & 8192 /* UniqueESSymbol */) && ts.unescapeLeadingUnderscores(memberName) || ts.declarationNameToString(declName);
43060                         ts.forEach(declarations, function (declaration) { return error(ts.getNameOfDeclaration(declaration) || declaration, ts.Diagnostics.Property_0_was_also_declared_here, name_3); });
43061                         error(declName || decl, ts.Diagnostics.Duplicate_property_0, name_3);
43062                         lateSymbol = createSymbol(0 /* None */, memberName, 4096 /* Late */);
43063                     }
43064                     lateSymbol.nameType = type;
43065                     addDeclarationToLateBoundSymbol(lateSymbol, decl, symbolFlags);
43066                     if (lateSymbol.parent) {
43067                         ts.Debug.assert(lateSymbol.parent === parent, "Existing symbol parent should match new one");
43068                     }
43069                     else {
43070                         lateSymbol.parent = parent;
43071                     }
43072                     return links.resolvedSymbol = lateSymbol;
43073                 }
43074             }
43075             return links.resolvedSymbol;
43076         }
43077         function getResolvedMembersOrExportsOfSymbol(symbol, resolutionKind) {
43078             var links = getSymbolLinks(symbol);
43079             if (!links[resolutionKind]) {
43080                 var isStatic = resolutionKind === "resolvedExports" /* resolvedExports */;
43081                 var earlySymbols = !isStatic ? symbol.members :
43082                     symbol.flags & 1536 /* Module */ ? getExportsOfModuleWorker(symbol) :
43083                         symbol.exports;
43084                 // In the event we recursively resolve the members/exports of the symbol, we
43085                 // set the initial value of resolvedMembers/resolvedExports to the early-bound
43086                 // members/exports of the symbol.
43087                 links[resolutionKind] = earlySymbols || emptySymbols;
43088                 // fill in any as-yet-unresolved late-bound members.
43089                 var lateSymbols = ts.createSymbolTable();
43090                 for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) {
43091                     var decl = _a[_i];
43092                     var members = ts.getMembersOfDeclaration(decl);
43093                     if (members) {
43094                         for (var _b = 0, members_5 = members; _b < members_5.length; _b++) {
43095                             var member = members_5[_b];
43096                             if (isStatic === ts.hasStaticModifier(member) && hasLateBindableName(member)) {
43097                                 lateBindMember(symbol, earlySymbols, lateSymbols, member);
43098                             }
43099                         }
43100                     }
43101                 }
43102                 var assignments = symbol.assignmentDeclarationMembers;
43103                 if (assignments) {
43104                     var decls = ts.arrayFrom(assignments.values());
43105                     for (var _c = 0, decls_1 = decls; _c < decls_1.length; _c++) {
43106                         var member = decls_1[_c];
43107                         var assignmentKind = ts.getAssignmentDeclarationKind(member);
43108                         var isInstanceMember = assignmentKind === 3 /* PrototypeProperty */
43109                             || assignmentKind === 4 /* ThisProperty */
43110                             || assignmentKind === 9 /* ObjectDefinePrototypeProperty */
43111                             || assignmentKind === 6 /* Prototype */; // A straight `Prototype` assignment probably can never have a computed name
43112                         if (isStatic === !isInstanceMember && hasLateBindableName(member)) {
43113                             lateBindMember(symbol, earlySymbols, lateSymbols, member);
43114                         }
43115                     }
43116                 }
43117                 links[resolutionKind] = combineSymbolTables(earlySymbols, lateSymbols) || emptySymbols;
43118             }
43119             return links[resolutionKind];
43120         }
43121         /**
43122          * Gets a SymbolTable containing both the early- and late-bound members of a symbol.
43123          *
43124          * For a description of late-binding, see `lateBindMember`.
43125          */
43126         function getMembersOfSymbol(symbol) {
43127             return symbol.flags & 6256 /* LateBindingContainer */
43128                 ? getResolvedMembersOrExportsOfSymbol(symbol, "resolvedMembers" /* resolvedMembers */)
43129                 : symbol.members || emptySymbols;
43130         }
43131         /**
43132          * If a symbol is the dynamic name of the member of an object type, get the late-bound
43133          * symbol of the member.
43134          *
43135          * For a description of late-binding, see `lateBindMember`.
43136          */
43137         function getLateBoundSymbol(symbol) {
43138             if (symbol.flags & 106500 /* ClassMember */ && symbol.escapedName === "__computed" /* Computed */) {
43139                 var links = getSymbolLinks(symbol);
43140                 if (!links.lateSymbol && ts.some(symbol.declarations, hasLateBindableName)) {
43141                     // force late binding of members/exports. This will set the late-bound symbol
43142                     var parent = getMergedSymbol(symbol.parent);
43143                     if (ts.some(symbol.declarations, ts.hasStaticModifier)) {
43144                         getExportsOfSymbol(parent);
43145                     }
43146                     else {
43147                         getMembersOfSymbol(parent);
43148                     }
43149                 }
43150                 return links.lateSymbol || (links.lateSymbol = symbol);
43151             }
43152             return symbol;
43153         }
43154         function getTypeWithThisArgument(type, thisArgument, needApparentType) {
43155             if (ts.getObjectFlags(type) & 4 /* Reference */) {
43156                 var target = type.target;
43157                 var typeArguments = getTypeArguments(type);
43158                 if (ts.length(target.typeParameters) === ts.length(typeArguments)) {
43159                     var ref = createTypeReference(target, ts.concatenate(typeArguments, [thisArgument || target.thisType]));
43160                     return needApparentType ? getApparentType(ref) : ref;
43161                 }
43162             }
43163             else if (type.flags & 2097152 /* Intersection */) {
43164                 return getIntersectionType(ts.map(type.types, function (t) { return getTypeWithThisArgument(t, thisArgument, needApparentType); }));
43165             }
43166             return needApparentType ? getApparentType(type) : type;
43167         }
43168         function resolveObjectTypeMembers(type, source, typeParameters, typeArguments) {
43169             var mapper;
43170             var members;
43171             var callSignatures;
43172             var constructSignatures;
43173             var stringIndexInfo;
43174             var numberIndexInfo;
43175             if (ts.rangeEquals(typeParameters, typeArguments, 0, typeParameters.length)) {
43176                 members = source.symbol ? getMembersOfSymbol(source.symbol) : ts.createSymbolTable(source.declaredProperties);
43177                 callSignatures = source.declaredCallSignatures;
43178                 constructSignatures = source.declaredConstructSignatures;
43179                 stringIndexInfo = source.declaredStringIndexInfo;
43180                 numberIndexInfo = source.declaredNumberIndexInfo;
43181             }
43182             else {
43183                 mapper = createTypeMapper(typeParameters, typeArguments);
43184                 members = createInstantiatedSymbolTable(source.declaredProperties, mapper, /*mappingThisOnly*/ typeParameters.length === 1);
43185                 callSignatures = instantiateSignatures(source.declaredCallSignatures, mapper);
43186                 constructSignatures = instantiateSignatures(source.declaredConstructSignatures, mapper);
43187                 stringIndexInfo = instantiateIndexInfo(source.declaredStringIndexInfo, mapper);
43188                 numberIndexInfo = instantiateIndexInfo(source.declaredNumberIndexInfo, mapper);
43189             }
43190             var baseTypes = getBaseTypes(source);
43191             if (baseTypes.length) {
43192                 if (source.symbol && members === getMembersOfSymbol(source.symbol)) {
43193                     members = ts.createSymbolTable(source.declaredProperties);
43194                 }
43195                 setStructuredTypeMembers(type, members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo);
43196                 var thisArgument = ts.lastOrUndefined(typeArguments);
43197                 for (var _i = 0, baseTypes_1 = baseTypes; _i < baseTypes_1.length; _i++) {
43198                     var baseType = baseTypes_1[_i];
43199                     var instantiatedBaseType = thisArgument ? getTypeWithThisArgument(instantiateType(baseType, mapper), thisArgument) : baseType;
43200                     addInheritedMembers(members, getPropertiesOfType(instantiatedBaseType));
43201                     callSignatures = ts.concatenate(callSignatures, getSignaturesOfType(instantiatedBaseType, 0 /* Call */));
43202                     constructSignatures = ts.concatenate(constructSignatures, getSignaturesOfType(instantiatedBaseType, 1 /* Construct */));
43203                     if (!stringIndexInfo) {
43204                         stringIndexInfo = instantiatedBaseType === anyType ?
43205                             createIndexInfo(anyType, /*isReadonly*/ false) :
43206                             getIndexInfoOfType(instantiatedBaseType, 0 /* String */);
43207                     }
43208                     numberIndexInfo = numberIndexInfo || getIndexInfoOfType(instantiatedBaseType, 1 /* Number */);
43209                 }
43210             }
43211             setStructuredTypeMembers(type, members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo);
43212         }
43213         function resolveClassOrInterfaceMembers(type) {
43214             resolveObjectTypeMembers(type, resolveDeclaredMembers(type), ts.emptyArray, ts.emptyArray);
43215         }
43216         function resolveTypeReferenceMembers(type) {
43217             var source = resolveDeclaredMembers(type.target);
43218             var typeParameters = ts.concatenate(source.typeParameters, [source.thisType]);
43219             var typeArguments = getTypeArguments(type);
43220             var paddedTypeArguments = typeArguments.length === typeParameters.length ? typeArguments : ts.concatenate(typeArguments, [type]);
43221             resolveObjectTypeMembers(type, source, typeParameters, paddedTypeArguments);
43222         }
43223         function createSignature(declaration, typeParameters, thisParameter, parameters, resolvedReturnType, resolvedTypePredicate, minArgumentCount, flags) {
43224             var sig = new Signature(checker, flags);
43225             sig.declaration = declaration;
43226             sig.typeParameters = typeParameters;
43227             sig.parameters = parameters;
43228             sig.thisParameter = thisParameter;
43229             sig.resolvedReturnType = resolvedReturnType;
43230             sig.resolvedTypePredicate = resolvedTypePredicate;
43231             sig.minArgumentCount = minArgumentCount;
43232             sig.target = undefined;
43233             sig.mapper = undefined;
43234             sig.unionSignatures = undefined;
43235             return sig;
43236         }
43237         function cloneSignature(sig) {
43238             var result = createSignature(sig.declaration, sig.typeParameters, sig.thisParameter, sig.parameters, /*resolvedReturnType*/ undefined, 
43239             /*resolvedTypePredicate*/ undefined, sig.minArgumentCount, sig.flags & 3 /* PropagatingFlags */);
43240             result.target = sig.target;
43241             result.mapper = sig.mapper;
43242             result.unionSignatures = sig.unionSignatures;
43243             return result;
43244         }
43245         function createUnionSignature(signature, unionSignatures) {
43246             var result = cloneSignature(signature);
43247             result.unionSignatures = unionSignatures;
43248             result.target = undefined;
43249             result.mapper = undefined;
43250             return result;
43251         }
43252         function getOptionalCallSignature(signature, callChainFlags) {
43253             if ((signature.flags & 12 /* CallChainFlags */) === callChainFlags) {
43254                 return signature;
43255             }
43256             if (!signature.optionalCallSignatureCache) {
43257                 signature.optionalCallSignatureCache = {};
43258             }
43259             var key = callChainFlags === 4 /* IsInnerCallChain */ ? "inner" : "outer";
43260             return signature.optionalCallSignatureCache[key]
43261                 || (signature.optionalCallSignatureCache[key] = createOptionalCallSignature(signature, callChainFlags));
43262         }
43263         function createOptionalCallSignature(signature, callChainFlags) {
43264             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.");
43265             var result = cloneSignature(signature);
43266             result.flags |= callChainFlags;
43267             return result;
43268         }
43269         function getExpandedParameters(sig) {
43270             if (signatureHasRestParameter(sig)) {
43271                 var restIndex_1 = sig.parameters.length - 1;
43272                 var restParameter = sig.parameters[restIndex_1];
43273                 var restType = getTypeOfSymbol(restParameter);
43274                 if (isTupleType(restType)) {
43275                     var elementTypes = getTypeArguments(restType);
43276                     var minLength_1 = restType.target.minLength;
43277                     var tupleRestIndex_1 = restType.target.hasRestElement ? elementTypes.length - 1 : -1;
43278                     var restParams = ts.map(elementTypes, function (t, i) {
43279                         var name = getParameterNameAtPosition(sig, restIndex_1 + i);
43280                         var checkFlags = i === tupleRestIndex_1 ? 32768 /* RestParameter */ :
43281                             i >= minLength_1 ? 16384 /* OptionalParameter */ : 0;
43282                         var symbol = createSymbol(1 /* FunctionScopedVariable */, name, checkFlags);
43283                         symbol.type = i === tupleRestIndex_1 ? createArrayType(t) : t;
43284                         return symbol;
43285                     });
43286                     return ts.concatenate(sig.parameters.slice(0, restIndex_1), restParams);
43287                 }
43288             }
43289             return sig.parameters;
43290         }
43291         function getDefaultConstructSignatures(classType) {
43292             var baseConstructorType = getBaseConstructorTypeOfClass(classType);
43293             var baseSignatures = getSignaturesOfType(baseConstructorType, 1 /* Construct */);
43294             if (baseSignatures.length === 0) {
43295                 return [createSignature(undefined, classType.localTypeParameters, undefined, ts.emptyArray, classType, /*resolvedTypePredicate*/ undefined, 0, 0 /* None */)];
43296             }
43297             var baseTypeNode = getBaseTypeNodeOfClass(classType);
43298             var isJavaScript = ts.isInJSFile(baseTypeNode);
43299             var typeArguments = typeArgumentsFromTypeReferenceNode(baseTypeNode);
43300             var typeArgCount = ts.length(typeArguments);
43301             var result = [];
43302             for (var _i = 0, baseSignatures_1 = baseSignatures; _i < baseSignatures_1.length; _i++) {
43303                 var baseSig = baseSignatures_1[_i];
43304                 var minTypeArgumentCount = getMinTypeArgumentCount(baseSig.typeParameters);
43305                 var typeParamCount = ts.length(baseSig.typeParameters);
43306                 if (isJavaScript || typeArgCount >= minTypeArgumentCount && typeArgCount <= typeParamCount) {
43307                     var sig = typeParamCount ? createSignatureInstantiation(baseSig, fillMissingTypeArguments(typeArguments, baseSig.typeParameters, minTypeArgumentCount, isJavaScript)) : cloneSignature(baseSig);
43308                     sig.typeParameters = classType.localTypeParameters;
43309                     sig.resolvedReturnType = classType;
43310                     result.push(sig);
43311                 }
43312             }
43313             return result;
43314         }
43315         function findMatchingSignature(signatureList, signature, partialMatch, ignoreThisTypes, ignoreReturnTypes) {
43316             for (var _i = 0, signatureList_1 = signatureList; _i < signatureList_1.length; _i++) {
43317                 var s = signatureList_1[_i];
43318                 if (compareSignaturesIdentical(s, signature, partialMatch, ignoreThisTypes, ignoreReturnTypes, partialMatch ? compareTypesSubtypeOf : compareTypesIdentical)) {
43319                     return s;
43320                 }
43321             }
43322         }
43323         function findMatchingSignatures(signatureLists, signature, listIndex) {
43324             if (signature.typeParameters) {
43325                 // We require an exact match for generic signatures, so we only return signatures from the first
43326                 // signature list and only if they have exact matches in the other signature lists.
43327                 if (listIndex > 0) {
43328                     return undefined;
43329                 }
43330                 for (var i = 1; i < signatureLists.length; i++) {
43331                     if (!findMatchingSignature(signatureLists[i], signature, /*partialMatch*/ false, /*ignoreThisTypes*/ false, /*ignoreReturnTypes*/ false)) {
43332                         return undefined;
43333                     }
43334                 }
43335                 return [signature];
43336             }
43337             var result;
43338             for (var i = 0; i < signatureLists.length; i++) {
43339                 // Allow matching non-generic signatures to have excess parameters and different return types.
43340                 // Prefer matching this types if possible.
43341                 var match = i === listIndex ? signature : findMatchingSignature(signatureLists[i], signature, /*partialMatch*/ true, /*ignoreThisTypes*/ false, /*ignoreReturnTypes*/ true);
43342                 if (!match) {
43343                     return undefined;
43344                 }
43345                 result = ts.appendIfUnique(result, match);
43346             }
43347             return result;
43348         }
43349         // The signatures of a union type are those signatures that are present in each of the constituent types.
43350         // Generic signatures must match exactly, but non-generic signatures are allowed to have extra optional
43351         // parameters and may differ in return types. When signatures differ in return types, the resulting return
43352         // type is the union of the constituent return types.
43353         function getUnionSignatures(signatureLists) {
43354             var result;
43355             var indexWithLengthOverOne;
43356             for (var i = 0; i < signatureLists.length; i++) {
43357                 if (signatureLists[i].length === 0)
43358                     return ts.emptyArray;
43359                 if (signatureLists[i].length > 1) {
43360                     indexWithLengthOverOne = indexWithLengthOverOne === undefined ? i : -1; // -1 is a signal there are multiple overload sets
43361                 }
43362                 for (var _i = 0, _a = signatureLists[i]; _i < _a.length; _i++) {
43363                     var signature = _a[_i];
43364                     // Only process signatures with parameter lists that aren't already in the result list
43365                     if (!result || !findMatchingSignature(result, signature, /*partialMatch*/ false, /*ignoreThisTypes*/ false, /*ignoreReturnTypes*/ true)) {
43366                         var unionSignatures = findMatchingSignatures(signatureLists, signature, i);
43367                         if (unionSignatures) {
43368                             var s = signature;
43369                             // Union the result types when more than one signature matches
43370                             if (unionSignatures.length > 1) {
43371                                 var thisParameter = signature.thisParameter;
43372                                 var firstThisParameterOfUnionSignatures = ts.forEach(unionSignatures, function (sig) { return sig.thisParameter; });
43373                                 if (firstThisParameterOfUnionSignatures) {
43374                                     var thisType = getIntersectionType(ts.mapDefined(unionSignatures, function (sig) { return sig.thisParameter && getTypeOfSymbol(sig.thisParameter); }));
43375                                     thisParameter = createSymbolWithType(firstThisParameterOfUnionSignatures, thisType);
43376                                 }
43377                                 s = createUnionSignature(signature, unionSignatures);
43378                                 s.thisParameter = thisParameter;
43379                             }
43380                             (result || (result = [])).push(s);
43381                         }
43382                     }
43383                 }
43384             }
43385             if (!ts.length(result) && indexWithLengthOverOne !== -1) {
43386                 // No sufficiently similar signature existed to subsume all the other signatures in the union - time to see if we can make a single
43387                 // signature that handles all over them. We only do this when there are overloads in only one constituent.
43388                 // (Overloads are conditional in nature and having overloads in multiple constituents would necessitate making a power set of
43389                 // signatures from the type, whose ordering would be non-obvious)
43390                 var masterList = signatureLists[indexWithLengthOverOne !== undefined ? indexWithLengthOverOne : 0];
43391                 var results = masterList.slice();
43392                 var _loop_9 = function (signatures) {
43393                     if (signatures !== masterList) {
43394                         var signature_1 = signatures[0];
43395                         ts.Debug.assert(!!signature_1, "getUnionSignatures bails early on empty signature lists and should not have empty lists on second pass");
43396                         results = signature_1.typeParameters && ts.some(results, function (s) { return !!s.typeParameters; }) ? undefined : ts.map(results, function (sig) { return combineSignaturesOfUnionMembers(sig, signature_1); });
43397                         if (!results) {
43398                             return "break";
43399                         }
43400                     }
43401                 };
43402                 for (var _b = 0, signatureLists_1 = signatureLists; _b < signatureLists_1.length; _b++) {
43403                     var signatures = signatureLists_1[_b];
43404                     var state_3 = _loop_9(signatures);
43405                     if (state_3 === "break")
43406                         break;
43407                 }
43408                 result = results;
43409             }
43410             return result || ts.emptyArray;
43411         }
43412         function combineUnionThisParam(left, right) {
43413             if (!left || !right) {
43414                 return left || right;
43415             }
43416             // A signature `this` type might be a read or a write position... It's very possible that it should be invariant
43417             // and we should refuse to merge signatures if there are `this` types and they do not match. However, so as to be
43418             // permissive when calling, for now, we'll intersect the `this` types just like we do for param types in union signatures.
43419             var thisType = getIntersectionType([getTypeOfSymbol(left), getTypeOfSymbol(right)]);
43420             return createSymbolWithType(left, thisType);
43421         }
43422         function combineUnionParameters(left, right) {
43423             var leftCount = getParameterCount(left);
43424             var rightCount = getParameterCount(right);
43425             var longest = leftCount >= rightCount ? left : right;
43426             var shorter = longest === left ? right : left;
43427             var longestCount = longest === left ? leftCount : rightCount;
43428             var eitherHasEffectiveRest = (hasEffectiveRestParameter(left) || hasEffectiveRestParameter(right));
43429             var needsExtraRestElement = eitherHasEffectiveRest && !hasEffectiveRestParameter(longest);
43430             var params = new Array(longestCount + (needsExtraRestElement ? 1 : 0));
43431             for (var i = 0; i < longestCount; i++) {
43432                 var longestParamType = tryGetTypeAtPosition(longest, i);
43433                 var shorterParamType = tryGetTypeAtPosition(shorter, i) || unknownType;
43434                 var unionParamType = getIntersectionType([longestParamType, shorterParamType]);
43435                 var isRestParam = eitherHasEffectiveRest && !needsExtraRestElement && i === (longestCount - 1);
43436                 var isOptional = i >= getMinArgumentCount(longest) && i >= getMinArgumentCount(shorter);
43437                 var leftName = i >= leftCount ? undefined : getParameterNameAtPosition(left, i);
43438                 var rightName = i >= rightCount ? undefined : getParameterNameAtPosition(right, i);
43439                 var paramName = leftName === rightName ? leftName :
43440                     !leftName ? rightName :
43441                         !rightName ? leftName :
43442                             undefined;
43443                 var paramSymbol = createSymbol(1 /* FunctionScopedVariable */ | (isOptional && !isRestParam ? 16777216 /* Optional */ : 0), paramName || "arg" + i);
43444                 paramSymbol.type = isRestParam ? createArrayType(unionParamType) : unionParamType;
43445                 params[i] = paramSymbol;
43446             }
43447             if (needsExtraRestElement) {
43448                 var restParamSymbol = createSymbol(1 /* FunctionScopedVariable */, "args");
43449                 restParamSymbol.type = createArrayType(getTypeAtPosition(shorter, longestCount));
43450                 params[longestCount] = restParamSymbol;
43451             }
43452             return params;
43453         }
43454         function combineSignaturesOfUnionMembers(left, right) {
43455             var declaration = left.declaration;
43456             var params = combineUnionParameters(left, right);
43457             var thisParam = combineUnionThisParam(left.thisParameter, right.thisParameter);
43458             var minArgCount = Math.max(left.minArgumentCount, right.minArgumentCount);
43459             var result = createSignature(declaration, left.typeParameters || right.typeParameters, thisParam, params, 
43460             /*resolvedReturnType*/ undefined, 
43461             /*resolvedTypePredicate*/ undefined, minArgCount, (left.flags | right.flags) & 3 /* PropagatingFlags */);
43462             result.unionSignatures = ts.concatenate(left.unionSignatures || [left], [right]);
43463             return result;
43464         }
43465         function getUnionIndexInfo(types, kind) {
43466             var indexTypes = [];
43467             var isAnyReadonly = false;
43468             for (var _i = 0, types_3 = types; _i < types_3.length; _i++) {
43469                 var type = types_3[_i];
43470                 var indexInfo = getIndexInfoOfType(getApparentType(type), kind);
43471                 if (!indexInfo) {
43472                     return undefined;
43473                 }
43474                 indexTypes.push(indexInfo.type);
43475                 isAnyReadonly = isAnyReadonly || indexInfo.isReadonly;
43476             }
43477             return createIndexInfo(getUnionType(indexTypes, 2 /* Subtype */), isAnyReadonly);
43478         }
43479         function resolveUnionTypeMembers(type) {
43480             // The members and properties collections are empty for union types. To get all properties of a union
43481             // type use getPropertiesOfType (only the language service uses this).
43482             var callSignatures = getUnionSignatures(ts.map(type.types, function (t) { return t === globalFunctionType ? [unknownSignature] : getSignaturesOfType(t, 0 /* Call */); }));
43483             var constructSignatures = getUnionSignatures(ts.map(type.types, function (t) { return getSignaturesOfType(t, 1 /* Construct */); }));
43484             var stringIndexInfo = getUnionIndexInfo(type.types, 0 /* String */);
43485             var numberIndexInfo = getUnionIndexInfo(type.types, 1 /* Number */);
43486             setStructuredTypeMembers(type, emptySymbols, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo);
43487         }
43488         function intersectTypes(type1, type2) {
43489             return !type1 ? type2 : !type2 ? type1 : getIntersectionType([type1, type2]);
43490         }
43491         function intersectIndexInfos(info1, info2) {
43492             return !info1 ? info2 : !info2 ? info1 : createIndexInfo(getIntersectionType([info1.type, info2.type]), info1.isReadonly && info2.isReadonly);
43493         }
43494         function unionSpreadIndexInfos(info1, info2) {
43495             return info1 && info2 && createIndexInfo(getUnionType([info1.type, info2.type]), info1.isReadonly || info2.isReadonly);
43496         }
43497         function findMixins(types) {
43498             var constructorTypeCount = ts.countWhere(types, function (t) { return getSignaturesOfType(t, 1 /* Construct */).length > 0; });
43499             var mixinFlags = ts.map(types, isMixinConstructorType);
43500             if (constructorTypeCount > 0 && constructorTypeCount === ts.countWhere(mixinFlags, function (b) { return b; })) {
43501                 var firstMixinIndex = mixinFlags.indexOf(/*searchElement*/ true);
43502                 mixinFlags[firstMixinIndex] = false;
43503             }
43504             return mixinFlags;
43505         }
43506         function includeMixinType(type, types, mixinFlags, index) {
43507             var mixedTypes = [];
43508             for (var i = 0; i < types.length; i++) {
43509                 if (i === index) {
43510                     mixedTypes.push(type);
43511                 }
43512                 else if (mixinFlags[i]) {
43513                     mixedTypes.push(getReturnTypeOfSignature(getSignaturesOfType(types[i], 1 /* Construct */)[0]));
43514                 }
43515             }
43516             return getIntersectionType(mixedTypes);
43517         }
43518         function resolveIntersectionTypeMembers(type) {
43519             // The members and properties collections are empty for intersection types. To get all properties of an
43520             // intersection type use getPropertiesOfType (only the language service uses this).
43521             var callSignatures;
43522             var constructSignatures;
43523             var stringIndexInfo;
43524             var numberIndexInfo;
43525             var types = type.types;
43526             var mixinFlags = findMixins(types);
43527             var mixinCount = ts.countWhere(mixinFlags, function (b) { return b; });
43528             var _loop_10 = function (i) {
43529                 var t = type.types[i];
43530                 // When an intersection type contains mixin constructor types, the construct signatures from
43531                 // those types are discarded and their return types are mixed into the return types of all
43532                 // other construct signatures in the intersection type. For example, the intersection type
43533                 // '{ new(...args: any[]) => A } & { new(s: string) => B }' has a single construct signature
43534                 // 'new(s: string) => A & B'.
43535                 if (!mixinFlags[i]) {
43536                     var signatures = getSignaturesOfType(t, 1 /* Construct */);
43537                     if (signatures.length && mixinCount > 0) {
43538                         signatures = ts.map(signatures, function (s) {
43539                             var clone = cloneSignature(s);
43540                             clone.resolvedReturnType = includeMixinType(getReturnTypeOfSignature(s), types, mixinFlags, i);
43541                             return clone;
43542                         });
43543                     }
43544                     constructSignatures = appendSignatures(constructSignatures, signatures);
43545                 }
43546                 callSignatures = appendSignatures(callSignatures, getSignaturesOfType(t, 0 /* Call */));
43547                 stringIndexInfo = intersectIndexInfos(stringIndexInfo, getIndexInfoOfType(t, 0 /* String */));
43548                 numberIndexInfo = intersectIndexInfos(numberIndexInfo, getIndexInfoOfType(t, 1 /* Number */));
43549             };
43550             for (var i = 0; i < types.length; i++) {
43551                 _loop_10(i);
43552             }
43553             setStructuredTypeMembers(type, emptySymbols, callSignatures || ts.emptyArray, constructSignatures || ts.emptyArray, stringIndexInfo, numberIndexInfo);
43554         }
43555         function appendSignatures(signatures, newSignatures) {
43556             var _loop_11 = function (sig) {
43557                 if (!signatures || ts.every(signatures, function (s) { return !compareSignaturesIdentical(s, sig, /*partialMatch*/ false, /*ignoreThisTypes*/ false, /*ignoreReturnTypes*/ false, compareTypesIdentical); })) {
43558                     signatures = ts.append(signatures, sig);
43559                 }
43560             };
43561             for (var _i = 0, newSignatures_1 = newSignatures; _i < newSignatures_1.length; _i++) {
43562                 var sig = newSignatures_1[_i];
43563                 _loop_11(sig);
43564             }
43565             return signatures;
43566         }
43567         /**
43568          * Converts an AnonymousType to a ResolvedType.
43569          */
43570         function resolveAnonymousTypeMembers(type) {
43571             var symbol = getMergedSymbol(type.symbol);
43572             if (type.target) {
43573                 setStructuredTypeMembers(type, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined);
43574                 var members = createInstantiatedSymbolTable(getPropertiesOfObjectType(type.target), type.mapper, /*mappingThisOnly*/ false);
43575                 var callSignatures = instantiateSignatures(getSignaturesOfType(type.target, 0 /* Call */), type.mapper);
43576                 var constructSignatures = instantiateSignatures(getSignaturesOfType(type.target, 1 /* Construct */), type.mapper);
43577                 var stringIndexInfo = instantiateIndexInfo(getIndexInfoOfType(type.target, 0 /* String */), type.mapper);
43578                 var numberIndexInfo = instantiateIndexInfo(getIndexInfoOfType(type.target, 1 /* Number */), type.mapper);
43579                 setStructuredTypeMembers(type, members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo);
43580             }
43581             else if (symbol.flags & 2048 /* TypeLiteral */) {
43582                 setStructuredTypeMembers(type, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined);
43583                 var members = getMembersOfSymbol(symbol);
43584                 var callSignatures = getSignaturesOfSymbol(members.get("__call" /* Call */));
43585                 var constructSignatures = getSignaturesOfSymbol(members.get("__new" /* New */));
43586                 var stringIndexInfo = getIndexInfoOfSymbol(symbol, 0 /* String */);
43587                 var numberIndexInfo = getIndexInfoOfSymbol(symbol, 1 /* Number */);
43588                 setStructuredTypeMembers(type, members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo);
43589             }
43590             else {
43591                 // Combinations of function, class, enum and module
43592                 var members = emptySymbols;
43593                 var stringIndexInfo = void 0;
43594                 if (symbol.exports) {
43595                     members = getExportsOfSymbol(symbol);
43596                     if (symbol === globalThisSymbol) {
43597                         var varsOnly_1 = ts.createMap();
43598                         members.forEach(function (p) {
43599                             if (!(p.flags & 418 /* BlockScoped */)) {
43600                                 varsOnly_1.set(p.escapedName, p);
43601                             }
43602                         });
43603                         members = varsOnly_1;
43604                     }
43605                 }
43606                 setStructuredTypeMembers(type, members, ts.emptyArray, ts.emptyArray, undefined, undefined);
43607                 if (symbol.flags & 32 /* Class */) {
43608                     var classType = getDeclaredTypeOfClassOrInterface(symbol);
43609                     var baseConstructorType = getBaseConstructorTypeOfClass(classType);
43610                     if (baseConstructorType.flags & (524288 /* Object */ | 2097152 /* Intersection */ | 8650752 /* TypeVariable */)) {
43611                         members = ts.createSymbolTable(getNamedMembers(members));
43612                         addInheritedMembers(members, getPropertiesOfType(baseConstructorType));
43613                     }
43614                     else if (baseConstructorType === anyType) {
43615                         stringIndexInfo = createIndexInfo(anyType, /*isReadonly*/ false);
43616                     }
43617                 }
43618                 var numberIndexInfo = symbol.flags & 384 /* Enum */ && (getDeclaredTypeOfSymbol(symbol).flags & 32 /* Enum */ ||
43619                     ts.some(type.properties, function (prop) { return !!(getTypeOfSymbol(prop).flags & 296 /* NumberLike */); })) ? enumNumberIndexInfo : undefined;
43620                 setStructuredTypeMembers(type, members, ts.emptyArray, ts.emptyArray, stringIndexInfo, numberIndexInfo);
43621                 // We resolve the members before computing the signatures because a signature may use
43622                 // typeof with a qualified name expression that circularly references the type we are
43623                 // in the process of resolving (see issue #6072). The temporarily empty signature list
43624                 // will never be observed because a qualified name can't reference signatures.
43625                 if (symbol.flags & (16 /* Function */ | 8192 /* Method */)) {
43626                     type.callSignatures = getSignaturesOfSymbol(symbol);
43627                 }
43628                 // And likewise for construct signatures for classes
43629                 if (symbol.flags & 32 /* Class */) {
43630                     var classType_1 = getDeclaredTypeOfClassOrInterface(symbol);
43631                     var constructSignatures = symbol.members ? getSignaturesOfSymbol(symbol.members.get("__constructor" /* Constructor */)) : ts.emptyArray;
43632                     if (symbol.flags & 16 /* Function */) {
43633                         constructSignatures = ts.addRange(constructSignatures.slice(), ts.mapDefined(type.callSignatures, function (sig) { return isJSConstructor(sig.declaration) ?
43634                             createSignature(sig.declaration, sig.typeParameters, sig.thisParameter, sig.parameters, classType_1, /*resolvedTypePredicate*/ undefined, sig.minArgumentCount, sig.flags & 3 /* PropagatingFlags */) :
43635                             undefined; }));
43636                     }
43637                     if (!constructSignatures.length) {
43638                         constructSignatures = getDefaultConstructSignatures(classType_1);
43639                     }
43640                     type.constructSignatures = constructSignatures;
43641                 }
43642             }
43643         }
43644         function resolveReverseMappedTypeMembers(type) {
43645             var indexInfo = getIndexInfoOfType(type.source, 0 /* String */);
43646             var modifiers = getMappedTypeModifiers(type.mappedType);
43647             var readonlyMask = modifiers & 1 /* IncludeReadonly */ ? false : true;
43648             var optionalMask = modifiers & 4 /* IncludeOptional */ ? 0 : 16777216 /* Optional */;
43649             var stringIndexInfo = indexInfo && createIndexInfo(inferReverseMappedType(indexInfo.type, type.mappedType, type.constraintType), readonlyMask && indexInfo.isReadonly);
43650             var members = ts.createSymbolTable();
43651             for (var _i = 0, _a = getPropertiesOfType(type.source); _i < _a.length; _i++) {
43652                 var prop = _a[_i];
43653                 var checkFlags = 8192 /* ReverseMapped */ | (readonlyMask && isReadonlySymbol(prop) ? 8 /* Readonly */ : 0);
43654                 var inferredProp = createSymbol(4 /* Property */ | prop.flags & optionalMask, prop.escapedName, checkFlags);
43655                 inferredProp.declarations = prop.declarations;
43656                 inferredProp.nameType = getSymbolLinks(prop).nameType;
43657                 inferredProp.propertyType = getTypeOfSymbol(prop);
43658                 inferredProp.mappedType = type.mappedType;
43659                 inferredProp.constraintType = type.constraintType;
43660                 members.set(prop.escapedName, inferredProp);
43661             }
43662             setStructuredTypeMembers(type, members, ts.emptyArray, ts.emptyArray, stringIndexInfo, undefined);
43663         }
43664         // Return the lower bound of the key type in a mapped type. Intuitively, the lower
43665         // bound includes those keys that are known to always be present, for example because
43666         // because of constraints on type parameters (e.g. 'keyof T' for a constrained T).
43667         function getLowerBoundOfKeyType(type) {
43668             if (type.flags & (1 /* Any */ | 131068 /* Primitive */)) {
43669                 return type;
43670             }
43671             if (type.flags & 4194304 /* Index */) {
43672                 return getIndexType(getApparentType(type.type));
43673             }
43674             if (type.flags & 16777216 /* Conditional */) {
43675                 if (type.root.isDistributive) {
43676                     var checkType = type.checkType;
43677                     var constraint = getLowerBoundOfKeyType(checkType);
43678                     if (constraint !== checkType) {
43679                         return getConditionalTypeInstantiation(type, prependTypeMapping(type.root.checkType, constraint, type.mapper));
43680                     }
43681                 }
43682                 return type;
43683             }
43684             if (type.flags & 1048576 /* Union */) {
43685                 return getUnionType(ts.sameMap(type.types, getLowerBoundOfKeyType));
43686             }
43687             if (type.flags & 2097152 /* Intersection */) {
43688                 return getIntersectionType(ts.sameMap(type.types, getLowerBoundOfKeyType));
43689             }
43690             return neverType;
43691         }
43692         /** Resolve the members of a mapped type { [P in K]: T } */
43693         function resolveMappedTypeMembers(type) {
43694             var members = ts.createSymbolTable();
43695             var stringIndexInfo;
43696             var numberIndexInfo;
43697             // Resolve upfront such that recursive references see an empty object type.
43698             setStructuredTypeMembers(type, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined);
43699             // In { [P in K]: T }, we refer to P as the type parameter type, K as the constraint type,
43700             // and T as the template type.
43701             var typeParameter = getTypeParameterFromMappedType(type);
43702             var constraintType = getConstraintTypeFromMappedType(type);
43703             var templateType = getTemplateTypeFromMappedType(type.target || type);
43704             var modifiersType = getApparentType(getModifiersTypeFromMappedType(type)); // The 'T' in 'keyof T'
43705             var templateModifiers = getMappedTypeModifiers(type);
43706             var include = keyofStringsOnly ? 128 /* StringLiteral */ : 8576 /* StringOrNumberLiteralOrUnique */;
43707             if (isMappedTypeWithKeyofConstraintDeclaration(type)) {
43708                 // We have a { [P in keyof T]: X }
43709                 for (var _i = 0, _a = getPropertiesOfType(modifiersType); _i < _a.length; _i++) {
43710                     var prop = _a[_i];
43711                     addMemberForKeyType(getLiteralTypeFromProperty(prop, include));
43712                 }
43713                 if (modifiersType.flags & 1 /* Any */ || getIndexInfoOfType(modifiersType, 0 /* String */)) {
43714                     addMemberForKeyType(stringType);
43715                 }
43716                 if (!keyofStringsOnly && getIndexInfoOfType(modifiersType, 1 /* Number */)) {
43717                     addMemberForKeyType(numberType);
43718                 }
43719             }
43720             else {
43721                 forEachType(getLowerBoundOfKeyType(constraintType), addMemberForKeyType);
43722             }
43723             setStructuredTypeMembers(type, members, ts.emptyArray, ts.emptyArray, stringIndexInfo, numberIndexInfo);
43724             function addMemberForKeyType(t) {
43725                 // Create a mapper from T to the current iteration type constituent. Then, if the
43726                 // mapped type is itself an instantiated type, combine the iteration mapper with the
43727                 // instantiation mapper.
43728                 var templateMapper = appendTypeMapping(type.mapper, typeParameter, t);
43729                 // If the current iteration type constituent is a string literal type, create a property.
43730                 // Otherwise, for type string create a string index signature.
43731                 if (isTypeUsableAsPropertyName(t)) {
43732                     var propName = getPropertyNameFromType(t);
43733                     var modifiersProp = getPropertyOfType(modifiersType, propName);
43734                     var isOptional = !!(templateModifiers & 4 /* IncludeOptional */ ||
43735                         !(templateModifiers & 8 /* ExcludeOptional */) && modifiersProp && modifiersProp.flags & 16777216 /* Optional */);
43736                     var isReadonly = !!(templateModifiers & 1 /* IncludeReadonly */ ||
43737                         !(templateModifiers & 2 /* ExcludeReadonly */) && modifiersProp && isReadonlySymbol(modifiersProp));
43738                     var stripOptional = strictNullChecks && !isOptional && modifiersProp && modifiersProp.flags & 16777216 /* Optional */;
43739                     var prop = createSymbol(4 /* Property */ | (isOptional ? 16777216 /* Optional */ : 0), propName, 262144 /* Mapped */ | (isReadonly ? 8 /* Readonly */ : 0) | (stripOptional ? 524288 /* StripOptional */ : 0));
43740                     prop.mappedType = type;
43741                     prop.mapper = templateMapper;
43742                     if (modifiersProp) {
43743                         prop.syntheticOrigin = modifiersProp;
43744                         prop.declarations = modifiersProp.declarations;
43745                     }
43746                     prop.nameType = t;
43747                     members.set(propName, prop);
43748                 }
43749                 else if (t.flags & (1 /* Any */ | 4 /* String */ | 8 /* Number */ | 32 /* Enum */)) {
43750                     var propType = instantiateType(templateType, templateMapper);
43751                     if (t.flags & (1 /* Any */ | 4 /* String */)) {
43752                         stringIndexInfo = createIndexInfo(propType, !!(templateModifiers & 1 /* IncludeReadonly */));
43753                     }
43754                     else {
43755                         numberIndexInfo = createIndexInfo(numberIndexInfo ? getUnionType([numberIndexInfo.type, propType]) : propType, !!(templateModifiers & 1 /* IncludeReadonly */));
43756                     }
43757                 }
43758             }
43759         }
43760         function getTypeOfMappedSymbol(symbol) {
43761             if (!symbol.type) {
43762                 if (!pushTypeResolution(symbol, 0 /* Type */)) {
43763                     return errorType;
43764                 }
43765                 var templateType = getTemplateTypeFromMappedType(symbol.mappedType.target || symbol.mappedType);
43766                 var propType = instantiateType(templateType, symbol.mapper);
43767                 // When creating an optional property in strictNullChecks mode, if 'undefined' isn't assignable to the
43768                 // type, we include 'undefined' in the type. Similarly, when creating a non-optional property in strictNullChecks
43769                 // mode, if the underlying property is optional we remove 'undefined' from the type.
43770                 var type = strictNullChecks && symbol.flags & 16777216 /* Optional */ && !maybeTypeOfKind(propType, 32768 /* Undefined */ | 16384 /* Void */) ? getOptionalType(propType) :
43771                     symbol.checkFlags & 524288 /* StripOptional */ ? getTypeWithFacts(propType, 524288 /* NEUndefined */) :
43772                         propType;
43773                 if (!popTypeResolution()) {
43774                     error(currentNode, ts.Diagnostics.Type_of_property_0_circularly_references_itself_in_mapped_type_1, symbolToString(symbol), typeToString(symbol.mappedType));
43775                     type = errorType;
43776                 }
43777                 symbol.type = type;
43778                 symbol.mapper = undefined;
43779             }
43780             return symbol.type;
43781         }
43782         function getTypeParameterFromMappedType(type) {
43783             return type.typeParameter ||
43784                 (type.typeParameter = getDeclaredTypeOfTypeParameter(getSymbolOfNode(type.declaration.typeParameter)));
43785         }
43786         function getConstraintTypeFromMappedType(type) {
43787             return type.constraintType ||
43788                 (type.constraintType = getConstraintOfTypeParameter(getTypeParameterFromMappedType(type)) || errorType);
43789         }
43790         function getTemplateTypeFromMappedType(type) {
43791             return type.templateType ||
43792                 (type.templateType = type.declaration.type ?
43793                     instantiateType(addOptionality(getTypeFromTypeNode(type.declaration.type), !!(getMappedTypeModifiers(type) & 4 /* IncludeOptional */)), type.mapper) :
43794                     errorType);
43795         }
43796         function getConstraintDeclarationForMappedType(type) {
43797             return ts.getEffectiveConstraintOfTypeParameter(type.declaration.typeParameter);
43798         }
43799         function isMappedTypeWithKeyofConstraintDeclaration(type) {
43800             var constraintDeclaration = getConstraintDeclarationForMappedType(type); // TODO: GH#18217
43801             return constraintDeclaration.kind === 184 /* TypeOperator */ &&
43802                 constraintDeclaration.operator === 134 /* KeyOfKeyword */;
43803         }
43804         function getModifiersTypeFromMappedType(type) {
43805             if (!type.modifiersType) {
43806                 if (isMappedTypeWithKeyofConstraintDeclaration(type)) {
43807                     // If the constraint declaration is a 'keyof T' node, the modifiers type is T. We check
43808                     // AST nodes here because, when T is a non-generic type, the logic below eagerly resolves
43809                     // 'keyof T' to a literal union type and we can't recover T from that type.
43810                     type.modifiersType = instantiateType(getTypeFromTypeNode(getConstraintDeclarationForMappedType(type).type), type.mapper);
43811                 }
43812                 else {
43813                     // Otherwise, get the declared constraint type, and if the constraint type is a type parameter,
43814                     // get the constraint of that type parameter. If the resulting type is an indexed type 'keyof T',
43815                     // the modifiers type is T. Otherwise, the modifiers type is unknown.
43816                     var declaredType = getTypeFromMappedTypeNode(type.declaration);
43817                     var constraint = getConstraintTypeFromMappedType(declaredType);
43818                     var extendedConstraint = constraint && constraint.flags & 262144 /* TypeParameter */ ? getConstraintOfTypeParameter(constraint) : constraint;
43819                     type.modifiersType = extendedConstraint && extendedConstraint.flags & 4194304 /* Index */ ? instantiateType(extendedConstraint.type, type.mapper) : unknownType;
43820                 }
43821             }
43822             return type.modifiersType;
43823         }
43824         function getMappedTypeModifiers(type) {
43825             var declaration = type.declaration;
43826             return (declaration.readonlyToken ? declaration.readonlyToken.kind === 40 /* MinusToken */ ? 2 /* ExcludeReadonly */ : 1 /* IncludeReadonly */ : 0) |
43827                 (declaration.questionToken ? declaration.questionToken.kind === 40 /* MinusToken */ ? 8 /* ExcludeOptional */ : 4 /* IncludeOptional */ : 0);
43828         }
43829         function getMappedTypeOptionality(type) {
43830             var modifiers = getMappedTypeModifiers(type);
43831             return modifiers & 8 /* ExcludeOptional */ ? -1 : modifiers & 4 /* IncludeOptional */ ? 1 : 0;
43832         }
43833         function getCombinedMappedTypeOptionality(type) {
43834             var optionality = getMappedTypeOptionality(type);
43835             var modifiersType = getModifiersTypeFromMappedType(type);
43836             return optionality || (isGenericMappedType(modifiersType) ? getMappedTypeOptionality(modifiersType) : 0);
43837         }
43838         function isPartialMappedType(type) {
43839             return !!(ts.getObjectFlags(type) & 32 /* Mapped */ && getMappedTypeModifiers(type) & 4 /* IncludeOptional */);
43840         }
43841         function isGenericMappedType(type) {
43842             return !!(ts.getObjectFlags(type) & 32 /* Mapped */) && isGenericIndexType(getConstraintTypeFromMappedType(type));
43843         }
43844         function resolveStructuredTypeMembers(type) {
43845             if (!type.members) {
43846                 if (type.flags & 524288 /* Object */) {
43847                     if (type.objectFlags & 4 /* Reference */) {
43848                         resolveTypeReferenceMembers(type);
43849                     }
43850                     else if (type.objectFlags & 3 /* ClassOrInterface */) {
43851                         resolveClassOrInterfaceMembers(type);
43852                     }
43853                     else if (type.objectFlags & 2048 /* ReverseMapped */) {
43854                         resolveReverseMappedTypeMembers(type);
43855                     }
43856                     else if (type.objectFlags & 16 /* Anonymous */) {
43857                         resolveAnonymousTypeMembers(type);
43858                     }
43859                     else if (type.objectFlags & 32 /* Mapped */) {
43860                         resolveMappedTypeMembers(type);
43861                     }
43862                 }
43863                 else if (type.flags & 1048576 /* Union */) {
43864                     resolveUnionTypeMembers(type);
43865                 }
43866                 else if (type.flags & 2097152 /* Intersection */) {
43867                     resolveIntersectionTypeMembers(type);
43868                 }
43869             }
43870             return type;
43871         }
43872         /** Return properties of an object type or an empty array for other types */
43873         function getPropertiesOfObjectType(type) {
43874             if (type.flags & 524288 /* Object */) {
43875                 return resolveStructuredTypeMembers(type).properties;
43876             }
43877             return ts.emptyArray;
43878         }
43879         /** If the given type is an object type and that type has a property by the given name,
43880          * return the symbol for that property. Otherwise return undefined.
43881          */
43882         function getPropertyOfObjectType(type, name) {
43883             if (type.flags & 524288 /* Object */) {
43884                 var resolved = resolveStructuredTypeMembers(type);
43885                 var symbol = resolved.members.get(name);
43886                 if (symbol && symbolIsValue(symbol)) {
43887                     return symbol;
43888                 }
43889             }
43890         }
43891         function getPropertiesOfUnionOrIntersectionType(type) {
43892             if (!type.resolvedProperties) {
43893                 var members = ts.createSymbolTable();
43894                 for (var _i = 0, _a = type.types; _i < _a.length; _i++) {
43895                     var current = _a[_i];
43896                     for (var _b = 0, _c = getPropertiesOfType(current); _b < _c.length; _b++) {
43897                         var prop = _c[_b];
43898                         if (!members.has(prop.escapedName)) {
43899                             var combinedProp = getPropertyOfUnionOrIntersectionType(type, prop.escapedName);
43900                             if (combinedProp) {
43901                                 members.set(prop.escapedName, combinedProp);
43902                             }
43903                         }
43904                     }
43905                     // The properties of a union type are those that are present in all constituent types, so
43906                     // we only need to check the properties of the first type without index signature
43907                     if (type.flags & 1048576 /* Union */ && !getIndexInfoOfType(current, 0 /* String */) && !getIndexInfoOfType(current, 1 /* Number */)) {
43908                         break;
43909                     }
43910                 }
43911                 type.resolvedProperties = getNamedMembers(members);
43912             }
43913             return type.resolvedProperties;
43914         }
43915         function getPropertiesOfType(type) {
43916             type = getReducedApparentType(type);
43917             return type.flags & 3145728 /* UnionOrIntersection */ ?
43918                 getPropertiesOfUnionOrIntersectionType(type) :
43919                 getPropertiesOfObjectType(type);
43920         }
43921         function isTypeInvalidDueToUnionDiscriminant(contextualType, obj) {
43922             var list = obj.properties;
43923             return list.some(function (property) {
43924                 var nameType = property.name && getLiteralTypeFromPropertyName(property.name);
43925                 var name = nameType && isTypeUsableAsPropertyName(nameType) ? getPropertyNameFromType(nameType) : undefined;
43926                 var expected = name === undefined ? undefined : getTypeOfPropertyOfType(contextualType, name);
43927                 return !!expected && isLiteralType(expected) && !isTypeAssignableTo(getTypeOfNode(property), expected);
43928             });
43929         }
43930         function getAllPossiblePropertiesOfTypes(types) {
43931             var unionType = getUnionType(types);
43932             if (!(unionType.flags & 1048576 /* Union */)) {
43933                 return getAugmentedPropertiesOfType(unionType);
43934             }
43935             var props = ts.createSymbolTable();
43936             for (var _i = 0, types_4 = types; _i < types_4.length; _i++) {
43937                 var memberType = types_4[_i];
43938                 for (var _a = 0, _b = getAugmentedPropertiesOfType(memberType); _a < _b.length; _a++) {
43939                     var escapedName = _b[_a].escapedName;
43940                     if (!props.has(escapedName)) {
43941                         var prop = createUnionOrIntersectionProperty(unionType, escapedName);
43942                         // May be undefined if the property is private
43943                         if (prop)
43944                             props.set(escapedName, prop);
43945                     }
43946                 }
43947             }
43948             return ts.arrayFrom(props.values());
43949         }
43950         function getConstraintOfType(type) {
43951             return type.flags & 262144 /* TypeParameter */ ? getConstraintOfTypeParameter(type) :
43952                 type.flags & 8388608 /* IndexedAccess */ ? getConstraintOfIndexedAccess(type) :
43953                     type.flags & 16777216 /* Conditional */ ? getConstraintOfConditionalType(type) :
43954                         getBaseConstraintOfType(type);
43955         }
43956         function getConstraintOfTypeParameter(typeParameter) {
43957             return hasNonCircularBaseConstraint(typeParameter) ? getConstraintFromTypeParameter(typeParameter) : undefined;
43958         }
43959         function getConstraintOfIndexedAccess(type) {
43960             return hasNonCircularBaseConstraint(type) ? getConstraintFromIndexedAccess(type) : undefined;
43961         }
43962         function getSimplifiedTypeOrConstraint(type) {
43963             var simplified = getSimplifiedType(type, /*writing*/ false);
43964             return simplified !== type ? simplified : getConstraintOfType(type);
43965         }
43966         function getConstraintFromIndexedAccess(type) {
43967             var indexConstraint = getSimplifiedTypeOrConstraint(type.indexType);
43968             if (indexConstraint && indexConstraint !== type.indexType) {
43969                 var indexedAccess = getIndexedAccessTypeOrUndefined(type.objectType, indexConstraint);
43970                 if (indexedAccess) {
43971                     return indexedAccess;
43972                 }
43973             }
43974             var objectConstraint = getSimplifiedTypeOrConstraint(type.objectType);
43975             if (objectConstraint && objectConstraint !== type.objectType) {
43976                 return getIndexedAccessTypeOrUndefined(objectConstraint, type.indexType);
43977             }
43978             return undefined;
43979         }
43980         function getDefaultConstraintOfConditionalType(type) {
43981             if (!type.resolvedDefaultConstraint) {
43982                 // An `any` branch of a conditional type would normally be viral - specifically, without special handling here,
43983                 // a conditional type with a single branch of type `any` would be assignable to anything, since it's constraint would simplify to
43984                 // just `any`. This result is _usually_ unwanted - so instead here we elide an `any` branch from the constraint type,
43985                 // in effect treating `any` like `never` rather than `unknown` in this location.
43986                 var trueConstraint = getInferredTrueTypeFromConditionalType(type);
43987                 var falseConstraint = getFalseTypeFromConditionalType(type);
43988                 type.resolvedDefaultConstraint = isTypeAny(trueConstraint) ? falseConstraint : isTypeAny(falseConstraint) ? trueConstraint : getUnionType([trueConstraint, falseConstraint]);
43989             }
43990             return type.resolvedDefaultConstraint;
43991         }
43992         function getConstraintOfDistributiveConditionalType(type) {
43993             // Check if we have a conditional type of the form 'T extends U ? X : Y', where T is a constrained
43994             // type parameter. If so, create an instantiation of the conditional type where T is replaced
43995             // with its constraint. We do this because if the constraint is a union type it will be distributed
43996             // over the conditional type and possibly reduced. For example, 'T extends undefined ? never : T'
43997             // removes 'undefined' from T.
43998             // We skip returning a distributive constraint for a restrictive instantiation of a conditional type
43999             // as the constraint for all type params (check type included) have been replace with `unknown`, which
44000             // is going to produce even more false positive/negative results than the distribute constraint already does.
44001             // Please note: the distributive constraint is a kludge for emulating what a negated type could to do filter
44002             // a union - once negated types exist and are applied to the conditional false branch, this "constraint"
44003             // likely doesn't need to exist.
44004             if (type.root.isDistributive && type.restrictiveInstantiation !== type) {
44005                 var simplified = getSimplifiedType(type.checkType, /*writing*/ false);
44006                 var constraint = simplified === type.checkType ? getConstraintOfType(simplified) : simplified;
44007                 if (constraint && constraint !== type.checkType) {
44008                     var instantiated = getConditionalTypeInstantiation(type, prependTypeMapping(type.root.checkType, constraint, type.mapper));
44009                     if (!(instantiated.flags & 131072 /* Never */)) {
44010                         return instantiated;
44011                     }
44012                 }
44013             }
44014             return undefined;
44015         }
44016         function getConstraintFromConditionalType(type) {
44017             return getConstraintOfDistributiveConditionalType(type) || getDefaultConstraintOfConditionalType(type);
44018         }
44019         function getConstraintOfConditionalType(type) {
44020             return hasNonCircularBaseConstraint(type) ? getConstraintFromConditionalType(type) : undefined;
44021         }
44022         function getEffectiveConstraintOfIntersection(types, targetIsUnion) {
44023             var constraints;
44024             var hasDisjointDomainType = false;
44025             for (var _i = 0, types_5 = types; _i < types_5.length; _i++) {
44026                 var t = types_5[_i];
44027                 if (t.flags & 63176704 /* Instantiable */) {
44028                     // We keep following constraints as long as we have an instantiable type that is known
44029                     // not to be circular or infinite (hence we stop on index access types).
44030                     var constraint = getConstraintOfType(t);
44031                     while (constraint && constraint.flags & (262144 /* TypeParameter */ | 4194304 /* Index */ | 16777216 /* Conditional */)) {
44032                         constraint = getConstraintOfType(constraint);
44033                     }
44034                     if (constraint) {
44035                         constraints = ts.append(constraints, constraint);
44036                         if (targetIsUnion) {
44037                             constraints = ts.append(constraints, t);
44038                         }
44039                     }
44040                 }
44041                 else if (t.flags & 67238908 /* DisjointDomains */) {
44042                     hasDisjointDomainType = true;
44043                 }
44044             }
44045             // If the target is a union type or if we are intersecting with types belonging to one of the
44046             // disjoint domains, we may end up producing a constraint that hasn't been examined before.
44047             if (constraints && (targetIsUnion || hasDisjointDomainType)) {
44048                 if (hasDisjointDomainType) {
44049                     // We add any types belong to one of the disjoint domains because they might cause the final
44050                     // intersection operation to reduce the union constraints.
44051                     for (var _a = 0, types_6 = types; _a < types_6.length; _a++) {
44052                         var t = types_6[_a];
44053                         if (t.flags & 67238908 /* DisjointDomains */) {
44054                             constraints = ts.append(constraints, t);
44055                         }
44056                     }
44057                 }
44058                 return getIntersectionType(constraints);
44059             }
44060             return undefined;
44061         }
44062         function getBaseConstraintOfType(type) {
44063             if (type.flags & (58982400 /* InstantiableNonPrimitive */ | 3145728 /* UnionOrIntersection */)) {
44064                 var constraint = getResolvedBaseConstraint(type);
44065                 return constraint !== noConstraintType && constraint !== circularConstraintType ? constraint : undefined;
44066             }
44067             return type.flags & 4194304 /* Index */ ? keyofConstraintType : undefined;
44068         }
44069         /**
44070          * This is similar to `getBaseConstraintOfType` except it returns the input type if there's no base constraint, instead of `undefined`
44071          * It also doesn't map indexes to `string`, as where this is used this would be unneeded (and likely undesirable)
44072          */
44073         function getBaseConstraintOrType(type) {
44074             return getBaseConstraintOfType(type) || type;
44075         }
44076         function hasNonCircularBaseConstraint(type) {
44077             return getResolvedBaseConstraint(type) !== circularConstraintType;
44078         }
44079         /**
44080          * Return the resolved base constraint of a type variable. The noConstraintType singleton is returned if the
44081          * type variable has no constraint, and the circularConstraintType singleton is returned if the constraint
44082          * circularly references the type variable.
44083          */
44084         function getResolvedBaseConstraint(type) {
44085             var nonTerminating = false;
44086             return type.resolvedBaseConstraint ||
44087                 (type.resolvedBaseConstraint = getTypeWithThisArgument(getImmediateBaseConstraint(type), type));
44088             function getImmediateBaseConstraint(t) {
44089                 if (!t.immediateBaseConstraint) {
44090                     if (!pushTypeResolution(t, 4 /* ImmediateBaseConstraint */)) {
44091                         return circularConstraintType;
44092                     }
44093                     if (constraintDepth >= 50) {
44094                         // We have reached 50 recursive invocations of getImmediateBaseConstraint and there is a
44095                         // very high likelihood we're dealing with an infinite generic type that perpetually generates
44096                         // new type identities as we descend into it. We stop the recursion here and mark this type
44097                         // and the outer types as having circular constraints.
44098                         error(currentNode, ts.Diagnostics.Type_instantiation_is_excessively_deep_and_possibly_infinite);
44099                         nonTerminating = true;
44100                         return t.immediateBaseConstraint = noConstraintType;
44101                     }
44102                     constraintDepth++;
44103                     var result = computeBaseConstraint(getSimplifiedType(t, /*writing*/ false));
44104                     constraintDepth--;
44105                     if (!popTypeResolution()) {
44106                         if (t.flags & 262144 /* TypeParameter */) {
44107                             var errorNode = getConstraintDeclaration(t);
44108                             if (errorNode) {
44109                                 var diagnostic = error(errorNode, ts.Diagnostics.Type_parameter_0_has_a_circular_constraint, typeToString(t));
44110                                 if (currentNode && !ts.isNodeDescendantOf(errorNode, currentNode) && !ts.isNodeDescendantOf(currentNode, errorNode)) {
44111                                     ts.addRelatedInfo(diagnostic, ts.createDiagnosticForNode(currentNode, ts.Diagnostics.Circularity_originates_in_type_at_this_location));
44112                                 }
44113                             }
44114                         }
44115                         result = circularConstraintType;
44116                     }
44117                     if (nonTerminating) {
44118                         result = circularConstraintType;
44119                     }
44120                     t.immediateBaseConstraint = result || noConstraintType;
44121                 }
44122                 return t.immediateBaseConstraint;
44123             }
44124             function getBaseConstraint(t) {
44125                 var c = getImmediateBaseConstraint(t);
44126                 return c !== noConstraintType && c !== circularConstraintType ? c : undefined;
44127             }
44128             function computeBaseConstraint(t) {
44129                 if (t.flags & 262144 /* TypeParameter */) {
44130                     var constraint = getConstraintFromTypeParameter(t);
44131                     return t.isThisType || !constraint ?
44132                         constraint :
44133                         getBaseConstraint(constraint);
44134                 }
44135                 if (t.flags & 3145728 /* UnionOrIntersection */) {
44136                     var types = t.types;
44137                     var baseTypes = [];
44138                     for (var _i = 0, types_7 = types; _i < types_7.length; _i++) {
44139                         var type_2 = types_7[_i];
44140                         var baseType = getBaseConstraint(type_2);
44141                         if (baseType) {
44142                             baseTypes.push(baseType);
44143                         }
44144                     }
44145                     return t.flags & 1048576 /* Union */ && baseTypes.length === types.length ? getUnionType(baseTypes) :
44146                         t.flags & 2097152 /* Intersection */ && baseTypes.length ? getIntersectionType(baseTypes) :
44147                             undefined;
44148                 }
44149                 if (t.flags & 4194304 /* Index */) {
44150                     return keyofConstraintType;
44151                 }
44152                 if (t.flags & 8388608 /* IndexedAccess */) {
44153                     var baseObjectType = getBaseConstraint(t.objectType);
44154                     var baseIndexType = getBaseConstraint(t.indexType);
44155                     var baseIndexedAccess = baseObjectType && baseIndexType && getIndexedAccessTypeOrUndefined(baseObjectType, baseIndexType);
44156                     return baseIndexedAccess && getBaseConstraint(baseIndexedAccess);
44157                 }
44158                 if (t.flags & 16777216 /* Conditional */) {
44159                     var constraint = getConstraintFromConditionalType(t);
44160                     constraintDepth++; // Penalize repeating conditional types (this captures the recursion within getConstraintFromConditionalType and carries it forward)
44161                     var result = constraint && getBaseConstraint(constraint);
44162                     constraintDepth--;
44163                     return result;
44164                 }
44165                 if (t.flags & 33554432 /* Substitution */) {
44166                     return getBaseConstraint(t.substitute);
44167                 }
44168                 return t;
44169             }
44170         }
44171         function getApparentTypeOfIntersectionType(type) {
44172             return type.resolvedApparentType || (type.resolvedApparentType = getTypeWithThisArgument(type, type, /*apparentType*/ true));
44173         }
44174         function getResolvedTypeParameterDefault(typeParameter) {
44175             if (!typeParameter.default) {
44176                 if (typeParameter.target) {
44177                     var targetDefault = getResolvedTypeParameterDefault(typeParameter.target);
44178                     typeParameter.default = targetDefault ? instantiateType(targetDefault, typeParameter.mapper) : noConstraintType;
44179                 }
44180                 else {
44181                     // To block recursion, set the initial value to the resolvingDefaultType.
44182                     typeParameter.default = resolvingDefaultType;
44183                     var defaultDeclaration = typeParameter.symbol && ts.forEach(typeParameter.symbol.declarations, function (decl) { return ts.isTypeParameterDeclaration(decl) && decl.default; });
44184                     var defaultType = defaultDeclaration ? getTypeFromTypeNode(defaultDeclaration) : noConstraintType;
44185                     if (typeParameter.default === resolvingDefaultType) {
44186                         // If we have not been called recursively, set the correct default type.
44187                         typeParameter.default = defaultType;
44188                     }
44189                 }
44190             }
44191             else if (typeParameter.default === resolvingDefaultType) {
44192                 // If we are called recursively for this type parameter, mark the default as circular.
44193                 typeParameter.default = circularConstraintType;
44194             }
44195             return typeParameter.default;
44196         }
44197         /**
44198          * Gets the default type for a type parameter.
44199          *
44200          * If the type parameter is the result of an instantiation, this gets the instantiated
44201          * default type of its target. If the type parameter has no default type or the default is
44202          * circular, `undefined` is returned.
44203          */
44204         function getDefaultFromTypeParameter(typeParameter) {
44205             var defaultType = getResolvedTypeParameterDefault(typeParameter);
44206             return defaultType !== noConstraintType && defaultType !== circularConstraintType ? defaultType : undefined;
44207         }
44208         function hasNonCircularTypeParameterDefault(typeParameter) {
44209             return getResolvedTypeParameterDefault(typeParameter) !== circularConstraintType;
44210         }
44211         /**
44212          * Indicates whether the declaration of a typeParameter has a default type.
44213          */
44214         function hasTypeParameterDefault(typeParameter) {
44215             return !!(typeParameter.symbol && ts.forEach(typeParameter.symbol.declarations, function (decl) { return ts.isTypeParameterDeclaration(decl) && decl.default; }));
44216         }
44217         function getApparentTypeOfMappedType(type) {
44218             return type.resolvedApparentType || (type.resolvedApparentType = getResolvedApparentTypeOfMappedType(type));
44219         }
44220         function getResolvedApparentTypeOfMappedType(type) {
44221             var typeVariable = getHomomorphicTypeVariable(type);
44222             if (typeVariable) {
44223                 var constraint = getConstraintOfTypeParameter(typeVariable);
44224                 if (constraint && (isArrayType(constraint) || isTupleType(constraint))) {
44225                     return instantiateType(type, prependTypeMapping(typeVariable, constraint, type.mapper));
44226                 }
44227             }
44228             return type;
44229         }
44230         /**
44231          * For a type parameter, return the base constraint of the type parameter. For the string, number,
44232          * boolean, and symbol primitive types, return the corresponding object types. Otherwise return the
44233          * type itself.
44234          */
44235         function getApparentType(type) {
44236             var t = type.flags & 63176704 /* Instantiable */ ? getBaseConstraintOfType(type) || unknownType : type;
44237             return ts.getObjectFlags(t) & 32 /* Mapped */ ? getApparentTypeOfMappedType(t) :
44238                 t.flags & 2097152 /* Intersection */ ? getApparentTypeOfIntersectionType(t) :
44239                     t.flags & 132 /* StringLike */ ? globalStringType :
44240                         t.flags & 296 /* NumberLike */ ? globalNumberType :
44241                             t.flags & 2112 /* BigIntLike */ ? getGlobalBigIntType(/*reportErrors*/ languageVersion >= 7 /* ES2020 */) :
44242                                 t.flags & 528 /* BooleanLike */ ? globalBooleanType :
44243                                     t.flags & 12288 /* ESSymbolLike */ ? getGlobalESSymbolType(/*reportErrors*/ languageVersion >= 2 /* ES2015 */) :
44244                                         t.flags & 67108864 /* NonPrimitive */ ? emptyObjectType :
44245                                             t.flags & 4194304 /* Index */ ? keyofConstraintType :
44246                                                 t.flags & 2 /* Unknown */ && !strictNullChecks ? emptyObjectType :
44247                                                     t;
44248         }
44249         function getReducedApparentType(type) {
44250             // Since getApparentType may return a non-reduced union or intersection type, we need to perform
44251             // type reduction both before and after obtaining the apparent type. For example, given a type parameter
44252             // 'T extends A | B', the type 'T & X' becomes 'A & X | B & X' after obtaining the apparent type, and
44253             // that type may need futher reduction to remove empty intersections.
44254             return getReducedType(getApparentType(getReducedType(type)));
44255         }
44256         function createUnionOrIntersectionProperty(containingType, name) {
44257             var singleProp;
44258             var propSet;
44259             var indexTypes;
44260             var isUnion = containingType.flags & 1048576 /* Union */;
44261             // Flags we want to propagate to the result if they exist in all source symbols
44262             var optionalFlag = isUnion ? 0 /* None */ : 16777216 /* Optional */;
44263             var syntheticFlag = 4 /* SyntheticMethod */;
44264             var checkFlags = 0;
44265             for (var _i = 0, _a = containingType.types; _i < _a.length; _i++) {
44266                 var current = _a[_i];
44267                 var type = getApparentType(current);
44268                 if (!(type === errorType || type.flags & 131072 /* Never */)) {
44269                     var prop = getPropertyOfType(type, name);
44270                     var modifiers = prop ? ts.getDeclarationModifierFlagsFromSymbol(prop) : 0;
44271                     if (prop) {
44272                         if (isUnion) {
44273                             optionalFlag |= (prop.flags & 16777216 /* Optional */);
44274                         }
44275                         else {
44276                             optionalFlag &= prop.flags;
44277                         }
44278                         if (!singleProp) {
44279                             singleProp = prop;
44280                         }
44281                         else if (prop !== singleProp) {
44282                             if (!propSet) {
44283                                 propSet = ts.createMap();
44284                                 propSet.set("" + getSymbolId(singleProp), singleProp);
44285                             }
44286                             var id = "" + getSymbolId(prop);
44287                             if (!propSet.has(id)) {
44288                                 propSet.set(id, prop);
44289                             }
44290                         }
44291                         checkFlags |= (isReadonlySymbol(prop) ? 8 /* Readonly */ : 0) |
44292                             (!(modifiers & 24 /* NonPublicAccessibilityModifier */) ? 256 /* ContainsPublic */ : 0) |
44293                             (modifiers & 16 /* Protected */ ? 512 /* ContainsProtected */ : 0) |
44294                             (modifiers & 8 /* Private */ ? 1024 /* ContainsPrivate */ : 0) |
44295                             (modifiers & 32 /* Static */ ? 2048 /* ContainsStatic */ : 0);
44296                         if (!isPrototypeProperty(prop)) {
44297                             syntheticFlag = 2 /* SyntheticProperty */;
44298                         }
44299                     }
44300                     else if (isUnion) {
44301                         var indexInfo = !isLateBoundName(name) && (isNumericLiteralName(name) && getIndexInfoOfType(type, 1 /* Number */) || getIndexInfoOfType(type, 0 /* String */));
44302                         if (indexInfo) {
44303                             checkFlags |= 32 /* WritePartial */ | (indexInfo.isReadonly ? 8 /* Readonly */ : 0);
44304                             indexTypes = ts.append(indexTypes, isTupleType(type) ? getRestTypeOfTupleType(type) || undefinedType : indexInfo.type);
44305                         }
44306                         else if (isObjectLiteralType(type)) {
44307                             checkFlags |= 32 /* WritePartial */;
44308                             indexTypes = ts.append(indexTypes, undefinedType);
44309                         }
44310                         else {
44311                             checkFlags |= 16 /* ReadPartial */;
44312                         }
44313                     }
44314                 }
44315             }
44316             if (!singleProp || isUnion && (propSet || checkFlags & 48 /* Partial */) && checkFlags & (1024 /* ContainsPrivate */ | 512 /* ContainsProtected */)) {
44317                 // No property was found, or, in a union, a property has a private or protected declaration in one
44318                 // constituent, but is missing or has a different declaration in another constituent.
44319                 return undefined;
44320             }
44321             if (!propSet && !(checkFlags & 16 /* ReadPartial */) && !indexTypes) {
44322                 return singleProp;
44323             }
44324             var props = propSet ? ts.arrayFrom(propSet.values()) : [singleProp];
44325             var declarations;
44326             var firstType;
44327             var nameType;
44328             var propTypes = [];
44329             var firstValueDeclaration;
44330             var hasNonUniformValueDeclaration = false;
44331             for (var _b = 0, props_1 = props; _b < props_1.length; _b++) {
44332                 var prop = props_1[_b];
44333                 if (!firstValueDeclaration) {
44334                     firstValueDeclaration = prop.valueDeclaration;
44335                 }
44336                 else if (prop.valueDeclaration && prop.valueDeclaration !== firstValueDeclaration) {
44337                     hasNonUniformValueDeclaration = true;
44338                 }
44339                 declarations = ts.addRange(declarations, prop.declarations);
44340                 var type = getTypeOfSymbol(prop);
44341                 if (!firstType) {
44342                     firstType = type;
44343                     nameType = getSymbolLinks(prop).nameType;
44344                 }
44345                 else if (type !== firstType) {
44346                     checkFlags |= 64 /* HasNonUniformType */;
44347                 }
44348                 if (isLiteralType(type)) {
44349                     checkFlags |= 128 /* HasLiteralType */;
44350                 }
44351                 if (type.flags & 131072 /* Never */) {
44352                     checkFlags |= 131072 /* HasNeverType */;
44353                 }
44354                 propTypes.push(type);
44355             }
44356             ts.addRange(propTypes, indexTypes);
44357             var result = createSymbol(4 /* Property */ | optionalFlag, name, syntheticFlag | checkFlags);
44358             result.containingType = containingType;
44359             if (!hasNonUniformValueDeclaration && firstValueDeclaration) {
44360                 result.valueDeclaration = firstValueDeclaration;
44361                 // Inherit information about parent type.
44362                 if (firstValueDeclaration.symbol.parent) {
44363                     result.parent = firstValueDeclaration.symbol.parent;
44364                 }
44365             }
44366             result.declarations = declarations;
44367             result.nameType = nameType;
44368             if (propTypes.length > 2) {
44369                 // When `propTypes` has the potential to explode in size when normalized, defer normalization until absolutely needed
44370                 result.checkFlags |= 65536 /* DeferredType */;
44371                 result.deferralParent = containingType;
44372                 result.deferralConstituents = propTypes;
44373             }
44374             else {
44375                 result.type = isUnion ? getUnionType(propTypes) : getIntersectionType(propTypes);
44376             }
44377             return result;
44378         }
44379         // Return the symbol for a given property in a union or intersection type, or undefined if the property
44380         // does not exist in any constituent type. Note that the returned property may only be present in some
44381         // constituents, in which case the isPartial flag is set when the containing type is union type. We need
44382         // these partial properties when identifying discriminant properties, but otherwise they are filtered out
44383         // and do not appear to be present in the union type.
44384         function getUnionOrIntersectionProperty(type, name) {
44385             var properties = type.propertyCache || (type.propertyCache = ts.createSymbolTable());
44386             var property = properties.get(name);
44387             if (!property) {
44388                 property = createUnionOrIntersectionProperty(type, name);
44389                 if (property) {
44390                     properties.set(name, property);
44391                 }
44392             }
44393             return property;
44394         }
44395         function getPropertyOfUnionOrIntersectionType(type, name) {
44396             var property = getUnionOrIntersectionProperty(type, name);
44397             // We need to filter out partial properties in union types
44398             return property && !(ts.getCheckFlags(property) & 16 /* ReadPartial */) ? property : undefined;
44399         }
44400         /**
44401          * Return the reduced form of the given type. For a union type, it is a union of the normalized constituent types.
44402          * For an intersection of types containing one or more mututally exclusive discriminant properties, it is 'never'.
44403          * For all other types, it is simply the type itself. Discriminant properties are considered mutually exclusive when
44404          * no constituent property has type 'never', but the intersection of the constituent property types is 'never'.
44405          */
44406         function getReducedType(type) {
44407             if (type.flags & 1048576 /* Union */ && type.objectFlags & 268435456 /* ContainsIntersections */) {
44408                 return type.resolvedReducedType || (type.resolvedReducedType = getReducedUnionType(type));
44409             }
44410             else if (type.flags & 2097152 /* Intersection */) {
44411                 if (!(type.objectFlags & 268435456 /* IsNeverIntersectionComputed */)) {
44412                     type.objectFlags |= 268435456 /* IsNeverIntersectionComputed */ |
44413                         (ts.some(getPropertiesOfUnionOrIntersectionType(type), isNeverReducedProperty) ? 536870912 /* IsNeverIntersection */ : 0);
44414                 }
44415                 return type.objectFlags & 536870912 /* IsNeverIntersection */ ? neverType : type;
44416             }
44417             return type;
44418         }
44419         function getReducedUnionType(unionType) {
44420             var reducedTypes = ts.sameMap(unionType.types, getReducedType);
44421             if (reducedTypes === unionType.types) {
44422                 return unionType;
44423             }
44424             var reduced = getUnionType(reducedTypes);
44425             if (reduced.flags & 1048576 /* Union */) {
44426                 reduced.resolvedReducedType = reduced;
44427             }
44428             return reduced;
44429         }
44430         function isNeverReducedProperty(prop) {
44431             return isDiscriminantWithNeverType(prop) || isConflictingPrivateProperty(prop);
44432         }
44433         function isDiscriminantWithNeverType(prop) {
44434             // Return true for a synthetic non-optional property with non-uniform types, where at least one is
44435             // a literal type and none is never, that reduces to never.
44436             return !(prop.flags & 16777216 /* Optional */) &&
44437                 (ts.getCheckFlags(prop) & (192 /* Discriminant */ | 131072 /* HasNeverType */)) === 192 /* Discriminant */ &&
44438                 !!(getTypeOfSymbol(prop).flags & 131072 /* Never */);
44439         }
44440         function isConflictingPrivateProperty(prop) {
44441             // Return true for a synthetic property with multiple declarations, at least one of which is private.
44442             return !prop.valueDeclaration && !!(ts.getCheckFlags(prop) & 1024 /* ContainsPrivate */);
44443         }
44444         function elaborateNeverIntersection(errorInfo, type) {
44445             if (ts.getObjectFlags(type) & 536870912 /* IsNeverIntersection */) {
44446                 var neverProp = ts.find(getPropertiesOfUnionOrIntersectionType(type), isDiscriminantWithNeverType);
44447                 if (neverProp) {
44448                     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));
44449                 }
44450                 var privateProp = ts.find(getPropertiesOfUnionOrIntersectionType(type), isConflictingPrivateProperty);
44451                 if (privateProp) {
44452                     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));
44453                 }
44454             }
44455             return errorInfo;
44456         }
44457         /**
44458          * Return the symbol for the property with the given name in the given type. Creates synthetic union properties when
44459          * necessary, maps primitive types and type parameters are to their apparent types, and augments with properties from
44460          * Object and Function as appropriate.
44461          *
44462          * @param type a type to look up property from
44463          * @param name a name of property to look up in a given type
44464          */
44465         function getPropertyOfType(type, name) {
44466             type = getReducedApparentType(type);
44467             if (type.flags & 524288 /* Object */) {
44468                 var resolved = resolveStructuredTypeMembers(type);
44469                 var symbol = resolved.members.get(name);
44470                 if (symbol && symbolIsValue(symbol)) {
44471                     return symbol;
44472                 }
44473                 var functionType = resolved === anyFunctionType ? globalFunctionType :
44474                     resolved.callSignatures.length ? globalCallableFunctionType :
44475                         resolved.constructSignatures.length ? globalNewableFunctionType :
44476                             undefined;
44477                 if (functionType) {
44478                     var symbol_1 = getPropertyOfObjectType(functionType, name);
44479                     if (symbol_1) {
44480                         return symbol_1;
44481                     }
44482                 }
44483                 return getPropertyOfObjectType(globalObjectType, name);
44484             }
44485             if (type.flags & 3145728 /* UnionOrIntersection */) {
44486                 return getPropertyOfUnionOrIntersectionType(type, name);
44487             }
44488             return undefined;
44489         }
44490         function getSignaturesOfStructuredType(type, kind) {
44491             if (type.flags & 3670016 /* StructuredType */) {
44492                 var resolved = resolveStructuredTypeMembers(type);
44493                 return kind === 0 /* Call */ ? resolved.callSignatures : resolved.constructSignatures;
44494             }
44495             return ts.emptyArray;
44496         }
44497         /**
44498          * Return the signatures of the given kind in the given type. Creates synthetic union signatures when necessary and
44499          * maps primitive types and type parameters are to their apparent types.
44500          */
44501         function getSignaturesOfType(type, kind) {
44502             return getSignaturesOfStructuredType(getReducedApparentType(type), kind);
44503         }
44504         function getIndexInfoOfStructuredType(type, kind) {
44505             if (type.flags & 3670016 /* StructuredType */) {
44506                 var resolved = resolveStructuredTypeMembers(type);
44507                 return kind === 0 /* String */ ? resolved.stringIndexInfo : resolved.numberIndexInfo;
44508             }
44509         }
44510         function getIndexTypeOfStructuredType(type, kind) {
44511             var info = getIndexInfoOfStructuredType(type, kind);
44512             return info && info.type;
44513         }
44514         // Return the indexing info of the given kind in the given type. Creates synthetic union index types when necessary and
44515         // maps primitive types and type parameters are to their apparent types.
44516         function getIndexInfoOfType(type, kind) {
44517             return getIndexInfoOfStructuredType(getReducedApparentType(type), kind);
44518         }
44519         // Return the index type of the given kind in the given type. Creates synthetic union index types when necessary and
44520         // maps primitive types and type parameters are to their apparent types.
44521         function getIndexTypeOfType(type, kind) {
44522             return getIndexTypeOfStructuredType(getReducedApparentType(type), kind);
44523         }
44524         function getImplicitIndexTypeOfType(type, kind) {
44525             if (isObjectTypeWithInferableIndex(type)) {
44526                 var propTypes = [];
44527                 for (var _i = 0, _a = getPropertiesOfType(type); _i < _a.length; _i++) {
44528                     var prop = _a[_i];
44529                     if (kind === 0 /* String */ || isNumericLiteralName(prop.escapedName)) {
44530                         propTypes.push(getTypeOfSymbol(prop));
44531                     }
44532                 }
44533                 if (kind === 0 /* String */) {
44534                     ts.append(propTypes, getIndexTypeOfType(type, 1 /* Number */));
44535                 }
44536                 if (propTypes.length) {
44537                     return getUnionType(propTypes);
44538                 }
44539             }
44540             return undefined;
44541         }
44542         // Return list of type parameters with duplicates removed (duplicate identifier errors are generated in the actual
44543         // type checking functions).
44544         function getTypeParametersFromDeclaration(declaration) {
44545             var result;
44546             for (var _i = 0, _a = ts.getEffectiveTypeParameterDeclarations(declaration); _i < _a.length; _i++) {
44547                 var node = _a[_i];
44548                 result = ts.appendIfUnique(result, getDeclaredTypeOfTypeParameter(node.symbol));
44549             }
44550             return result;
44551         }
44552         function symbolsToArray(symbols) {
44553             var result = [];
44554             symbols.forEach(function (symbol, id) {
44555                 if (!isReservedMemberName(id)) {
44556                     result.push(symbol);
44557                 }
44558             });
44559             return result;
44560         }
44561         function isJSDocOptionalParameter(node) {
44562             return ts.isInJSFile(node) && (
44563             // node.type should only be a JSDocOptionalType when node is a parameter of a JSDocFunctionType
44564             node.type && node.type.kind === 299 /* JSDocOptionalType */
44565                 || ts.getJSDocParameterTags(node).some(function (_a) {
44566                     var isBracketed = _a.isBracketed, typeExpression = _a.typeExpression;
44567                     return isBracketed || !!typeExpression && typeExpression.type.kind === 299 /* JSDocOptionalType */;
44568                 }));
44569         }
44570         function tryFindAmbientModule(moduleName, withAugmentations) {
44571             if (ts.isExternalModuleNameRelative(moduleName)) {
44572                 return undefined;
44573             }
44574             var symbol = getSymbol(globals, '"' + moduleName + '"', 512 /* ValueModule */);
44575             // merged symbol is module declaration symbol combined with all augmentations
44576             return symbol && withAugmentations ? getMergedSymbol(symbol) : symbol;
44577         }
44578         function isOptionalParameter(node) {
44579             if (ts.hasQuestionToken(node) || isOptionalJSDocParameterTag(node) || isJSDocOptionalParameter(node)) {
44580                 return true;
44581             }
44582             if (node.initializer) {
44583                 var signature = getSignatureFromDeclaration(node.parent);
44584                 var parameterIndex = node.parent.parameters.indexOf(node);
44585                 ts.Debug.assert(parameterIndex >= 0);
44586                 return parameterIndex >= getMinArgumentCount(signature, /*strongArityForUntypedJS*/ true);
44587             }
44588             var iife = ts.getImmediatelyInvokedFunctionExpression(node.parent);
44589             if (iife) {
44590                 return !node.type &&
44591                     !node.dotDotDotToken &&
44592                     node.parent.parameters.indexOf(node) >= iife.arguments.length;
44593             }
44594             return false;
44595         }
44596         function isOptionalJSDocParameterTag(node) {
44597             if (!ts.isJSDocParameterTag(node)) {
44598                 return false;
44599             }
44600             var isBracketed = node.isBracketed, typeExpression = node.typeExpression;
44601             return isBracketed || !!typeExpression && typeExpression.type.kind === 299 /* JSDocOptionalType */;
44602         }
44603         function createTypePredicate(kind, parameterName, parameterIndex, type) {
44604             return { kind: kind, parameterName: parameterName, parameterIndex: parameterIndex, type: type };
44605         }
44606         /**
44607          * Gets the minimum number of type arguments needed to satisfy all non-optional type
44608          * parameters.
44609          */
44610         function getMinTypeArgumentCount(typeParameters) {
44611             var minTypeArgumentCount = 0;
44612             if (typeParameters) {
44613                 for (var i = 0; i < typeParameters.length; i++) {
44614                     if (!hasTypeParameterDefault(typeParameters[i])) {
44615                         minTypeArgumentCount = i + 1;
44616                     }
44617                 }
44618             }
44619             return minTypeArgumentCount;
44620         }
44621         function fillMissingTypeArguments(typeArguments, typeParameters, minTypeArgumentCount, isJavaScriptImplicitAny) {
44622             var numTypeParameters = ts.length(typeParameters);
44623             if (!numTypeParameters) {
44624                 return [];
44625             }
44626             var numTypeArguments = ts.length(typeArguments);
44627             if (isJavaScriptImplicitAny || (numTypeArguments >= minTypeArgumentCount && numTypeArguments <= numTypeParameters)) {
44628                 var result = typeArguments ? typeArguments.slice() : [];
44629                 // Map invalid forward references in default types to the error type
44630                 for (var i = numTypeArguments; i < numTypeParameters; i++) {
44631                     result[i] = errorType;
44632                 }
44633                 var baseDefaultType = getDefaultTypeArgumentType(isJavaScriptImplicitAny);
44634                 for (var i = numTypeArguments; i < numTypeParameters; i++) {
44635                     var defaultType = getDefaultFromTypeParameter(typeParameters[i]);
44636                     if (isJavaScriptImplicitAny && defaultType && (isTypeIdenticalTo(defaultType, unknownType) || isTypeIdenticalTo(defaultType, emptyObjectType))) {
44637                         defaultType = anyType;
44638                     }
44639                     result[i] = defaultType ? instantiateType(defaultType, createTypeMapper(typeParameters, result)) : baseDefaultType;
44640                 }
44641                 result.length = typeParameters.length;
44642                 return result;
44643             }
44644             return typeArguments && typeArguments.slice();
44645         }
44646         function getSignatureFromDeclaration(declaration) {
44647             var links = getNodeLinks(declaration);
44648             if (!links.resolvedSignature) {
44649                 var parameters = [];
44650                 var flags = 0 /* None */;
44651                 var minArgumentCount = 0;
44652                 var thisParameter = void 0;
44653                 var hasThisParameter = false;
44654                 var iife = ts.getImmediatelyInvokedFunctionExpression(declaration);
44655                 var isJSConstructSignature = ts.isJSDocConstructSignature(declaration);
44656                 var isUntypedSignatureInJSFile = !iife &&
44657                     ts.isInJSFile(declaration) &&
44658                     ts.isValueSignatureDeclaration(declaration) &&
44659                     !ts.hasJSDocParameterTags(declaration) &&
44660                     !ts.getJSDocType(declaration);
44661                 if (isUntypedSignatureInJSFile) {
44662                     flags |= 16 /* IsUntypedSignatureInJSFile */;
44663                 }
44664                 // If this is a JSDoc construct signature, then skip the first parameter in the
44665                 // parameter list.  The first parameter represents the return type of the construct
44666                 // signature.
44667                 for (var i = isJSConstructSignature ? 1 : 0; i < declaration.parameters.length; i++) {
44668                     var param = declaration.parameters[i];
44669                     var paramSymbol = param.symbol;
44670                     var type = ts.isJSDocParameterTag(param) ? (param.typeExpression && param.typeExpression.type) : param.type;
44671                     // Include parameter symbol instead of property symbol in the signature
44672                     if (paramSymbol && !!(paramSymbol.flags & 4 /* Property */) && !ts.isBindingPattern(param.name)) {
44673                         var resolvedSymbol = resolveName(param, paramSymbol.escapedName, 111551 /* Value */, undefined, undefined, /*isUse*/ false);
44674                         paramSymbol = resolvedSymbol;
44675                     }
44676                     if (i === 0 && paramSymbol.escapedName === "this" /* This */) {
44677                         hasThisParameter = true;
44678                         thisParameter = param.symbol;
44679                     }
44680                     else {
44681                         parameters.push(paramSymbol);
44682                     }
44683                     if (type && type.kind === 187 /* LiteralType */) {
44684                         flags |= 2 /* HasLiteralTypes */;
44685                     }
44686                     // Record a new minimum argument count if this is not an optional parameter
44687                     var isOptionalParameter_1 = isOptionalJSDocParameterTag(param) ||
44688                         param.initializer || param.questionToken || param.dotDotDotToken ||
44689                         iife && parameters.length > iife.arguments.length && !type ||
44690                         isJSDocOptionalParameter(param);
44691                     if (!isOptionalParameter_1) {
44692                         minArgumentCount = parameters.length;
44693                     }
44694                 }
44695                 // If only one accessor includes a this-type annotation, the other behaves as if it had the same type annotation
44696                 if ((declaration.kind === 163 /* GetAccessor */ || declaration.kind === 164 /* SetAccessor */) &&
44697                     !hasNonBindableDynamicName(declaration) &&
44698                     (!hasThisParameter || !thisParameter)) {
44699                     var otherKind = declaration.kind === 163 /* GetAccessor */ ? 164 /* SetAccessor */ : 163 /* GetAccessor */;
44700                     var other = ts.getDeclarationOfKind(getSymbolOfNode(declaration), otherKind);
44701                     if (other) {
44702                         thisParameter = getAnnotatedAccessorThisParameter(other);
44703                     }
44704                 }
44705                 var classType = declaration.kind === 162 /* Constructor */ ?
44706                     getDeclaredTypeOfClassOrInterface(getMergedSymbol(declaration.parent.symbol))
44707                     : undefined;
44708                 var typeParameters = classType ? classType.localTypeParameters : getTypeParametersFromDeclaration(declaration);
44709                 if (ts.hasRestParameter(declaration) || ts.isInJSFile(declaration) && maybeAddJsSyntheticRestParameter(declaration, parameters)) {
44710                     flags |= 1 /* HasRestParameter */;
44711                 }
44712                 links.resolvedSignature = createSignature(declaration, typeParameters, thisParameter, parameters, 
44713                 /*resolvedReturnType*/ undefined, /*resolvedTypePredicate*/ undefined, minArgumentCount, flags);
44714             }
44715             return links.resolvedSignature;
44716         }
44717         /**
44718          * A JS function gets a synthetic rest parameter if it references `arguments` AND:
44719          * 1. It has no parameters but at least one `@param` with a type that starts with `...`
44720          * OR
44721          * 2. It has at least one parameter, and the last parameter has a matching `@param` with a type that starts with `...`
44722          */
44723         function maybeAddJsSyntheticRestParameter(declaration, parameters) {
44724             if (ts.isJSDocSignature(declaration) || !containsArgumentsReference(declaration)) {
44725                 return false;
44726             }
44727             var lastParam = ts.lastOrUndefined(declaration.parameters);
44728             var lastParamTags = lastParam ? ts.getJSDocParameterTags(lastParam) : ts.getJSDocTags(declaration).filter(ts.isJSDocParameterTag);
44729             var lastParamVariadicType = ts.firstDefined(lastParamTags, function (p) {
44730                 return p.typeExpression && ts.isJSDocVariadicType(p.typeExpression.type) ? p.typeExpression.type : undefined;
44731             });
44732             var syntheticArgsSymbol = createSymbol(3 /* Variable */, "args", 32768 /* RestParameter */);
44733             syntheticArgsSymbol.type = lastParamVariadicType ? createArrayType(getTypeFromTypeNode(lastParamVariadicType.type)) : anyArrayType;
44734             if (lastParamVariadicType) {
44735                 // Replace the last parameter with a rest parameter.
44736                 parameters.pop();
44737             }
44738             parameters.push(syntheticArgsSymbol);
44739             return true;
44740         }
44741         function getSignatureOfTypeTag(node) {
44742             // should be attached to a function declaration or expression
44743             if (!(ts.isInJSFile(node) && ts.isFunctionLikeDeclaration(node)))
44744                 return undefined;
44745             var typeTag = ts.getJSDocTypeTag(node);
44746             var signature = typeTag && typeTag.typeExpression && getSingleCallSignature(getTypeFromTypeNode(typeTag.typeExpression));
44747             return signature && getErasedSignature(signature);
44748         }
44749         function getReturnTypeOfTypeTag(node) {
44750             var signature = getSignatureOfTypeTag(node);
44751             return signature && getReturnTypeOfSignature(signature);
44752         }
44753         function containsArgumentsReference(declaration) {
44754             var links = getNodeLinks(declaration);
44755             if (links.containsArgumentsReference === undefined) {
44756                 if (links.flags & 8192 /* CaptureArguments */) {
44757                     links.containsArgumentsReference = true;
44758                 }
44759                 else {
44760                     links.containsArgumentsReference = traverse(declaration.body);
44761                 }
44762             }
44763             return links.containsArgumentsReference;
44764             function traverse(node) {
44765                 if (!node)
44766                     return false;
44767                 switch (node.kind) {
44768                     case 75 /* Identifier */:
44769                         return node.escapedText === "arguments" && ts.isExpressionNode(node);
44770                     case 159 /* PropertyDeclaration */:
44771                     case 161 /* MethodDeclaration */:
44772                     case 163 /* GetAccessor */:
44773                     case 164 /* SetAccessor */:
44774                         return node.name.kind === 154 /* ComputedPropertyName */
44775                             && traverse(node.name);
44776                     default:
44777                         return !ts.nodeStartsNewLexicalEnvironment(node) && !ts.isPartOfTypeNode(node) && !!ts.forEachChild(node, traverse);
44778                 }
44779             }
44780         }
44781         function getSignaturesOfSymbol(symbol) {
44782             if (!symbol)
44783                 return ts.emptyArray;
44784             var result = [];
44785             for (var i = 0; i < symbol.declarations.length; i++) {
44786                 var decl = symbol.declarations[i];
44787                 if (!ts.isFunctionLike(decl))
44788                     continue;
44789                 // Don't include signature if node is the implementation of an overloaded function. A node is considered
44790                 // an implementation node if it has a body and the previous node is of the same kind and immediately
44791                 // precedes the implementation node (i.e. has the same parent and ends where the implementation starts).
44792                 if (i > 0 && decl.body) {
44793                     var previous = symbol.declarations[i - 1];
44794                     if (decl.parent === previous.parent && decl.kind === previous.kind && decl.pos === previous.end) {
44795                         continue;
44796                     }
44797                 }
44798                 result.push(getSignatureFromDeclaration(decl));
44799             }
44800             return result;
44801         }
44802         function resolveExternalModuleTypeByLiteral(name) {
44803             var moduleSym = resolveExternalModuleName(name, name);
44804             if (moduleSym) {
44805                 var resolvedModuleSymbol = resolveExternalModuleSymbol(moduleSym);
44806                 if (resolvedModuleSymbol) {
44807                     return getTypeOfSymbol(resolvedModuleSymbol);
44808                 }
44809             }
44810             return anyType;
44811         }
44812         function getThisTypeOfSignature(signature) {
44813             if (signature.thisParameter) {
44814                 return getTypeOfSymbol(signature.thisParameter);
44815             }
44816         }
44817         function getTypePredicateOfSignature(signature) {
44818             if (!signature.resolvedTypePredicate) {
44819                 if (signature.target) {
44820                     var targetTypePredicate = getTypePredicateOfSignature(signature.target);
44821                     signature.resolvedTypePredicate = targetTypePredicate ? instantiateTypePredicate(targetTypePredicate, signature.mapper) : noTypePredicate;
44822                 }
44823                 else if (signature.unionSignatures) {
44824                     signature.resolvedTypePredicate = getUnionTypePredicate(signature.unionSignatures) || noTypePredicate;
44825                 }
44826                 else {
44827                     var type = signature.declaration && ts.getEffectiveReturnTypeNode(signature.declaration);
44828                     var jsdocPredicate = void 0;
44829                     if (!type && ts.isInJSFile(signature.declaration)) {
44830                         var jsdocSignature = getSignatureOfTypeTag(signature.declaration);
44831                         if (jsdocSignature && signature !== jsdocSignature) {
44832                             jsdocPredicate = getTypePredicateOfSignature(jsdocSignature);
44833                         }
44834                     }
44835                     signature.resolvedTypePredicate = type && ts.isTypePredicateNode(type) ?
44836                         createTypePredicateFromTypePredicateNode(type, signature) :
44837                         jsdocPredicate || noTypePredicate;
44838                 }
44839                 ts.Debug.assert(!!signature.resolvedTypePredicate);
44840             }
44841             return signature.resolvedTypePredicate === noTypePredicate ? undefined : signature.resolvedTypePredicate;
44842         }
44843         function createTypePredicateFromTypePredicateNode(node, signature) {
44844             var parameterName = node.parameterName;
44845             var type = node.type && getTypeFromTypeNode(node.type);
44846             return parameterName.kind === 183 /* ThisType */ ?
44847                 createTypePredicate(node.assertsModifier ? 2 /* AssertsThis */ : 0 /* This */, /*parameterName*/ undefined, /*parameterIndex*/ undefined, type) :
44848                 createTypePredicate(node.assertsModifier ? 3 /* AssertsIdentifier */ : 1 /* Identifier */, parameterName.escapedText, ts.findIndex(signature.parameters, function (p) { return p.escapedName === parameterName.escapedText; }), type);
44849         }
44850         function getReturnTypeOfSignature(signature) {
44851             if (!signature.resolvedReturnType) {
44852                 if (!pushTypeResolution(signature, 3 /* ResolvedReturnType */)) {
44853                     return errorType;
44854                 }
44855                 var type = signature.target ? instantiateType(getReturnTypeOfSignature(signature.target), signature.mapper) :
44856                     signature.unionSignatures ? getUnionType(ts.map(signature.unionSignatures, getReturnTypeOfSignature), 2 /* Subtype */) :
44857                         getReturnTypeFromAnnotation(signature.declaration) ||
44858                             (ts.nodeIsMissing(signature.declaration.body) ? anyType : getReturnTypeFromBody(signature.declaration));
44859                 if (signature.flags & 4 /* IsInnerCallChain */) {
44860                     type = addOptionalTypeMarker(type);
44861                 }
44862                 else if (signature.flags & 8 /* IsOuterCallChain */) {
44863                     type = getOptionalType(type);
44864                 }
44865                 if (!popTypeResolution()) {
44866                     if (signature.declaration) {
44867                         var typeNode = ts.getEffectiveReturnTypeNode(signature.declaration);
44868                         if (typeNode) {
44869                             error(typeNode, ts.Diagnostics.Return_type_annotation_circularly_references_itself);
44870                         }
44871                         else if (noImplicitAny) {
44872                             var declaration = signature.declaration;
44873                             var name = ts.getNameOfDeclaration(declaration);
44874                             if (name) {
44875                                 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));
44876                             }
44877                             else {
44878                                 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);
44879                             }
44880                         }
44881                     }
44882                     type = anyType;
44883                 }
44884                 signature.resolvedReturnType = type;
44885             }
44886             return signature.resolvedReturnType;
44887         }
44888         function getReturnTypeFromAnnotation(declaration) {
44889             if (declaration.kind === 162 /* Constructor */) {
44890                 return getDeclaredTypeOfClassOrInterface(getMergedSymbol(declaration.parent.symbol));
44891             }
44892             if (ts.isJSDocConstructSignature(declaration)) {
44893                 return getTypeFromTypeNode(declaration.parameters[0].type); // TODO: GH#18217
44894             }
44895             var typeNode = ts.getEffectiveReturnTypeNode(declaration);
44896             if (typeNode) {
44897                 return getTypeFromTypeNode(typeNode);
44898             }
44899             if (declaration.kind === 163 /* GetAccessor */ && !hasNonBindableDynamicName(declaration)) {
44900                 var jsDocType = ts.isInJSFile(declaration) && getTypeForDeclarationFromJSDocComment(declaration);
44901                 if (jsDocType) {
44902                     return jsDocType;
44903                 }
44904                 var setter = ts.getDeclarationOfKind(getSymbolOfNode(declaration), 164 /* SetAccessor */);
44905                 var setterType = getAnnotatedAccessorType(setter);
44906                 if (setterType) {
44907                     return setterType;
44908                 }
44909             }
44910             return getReturnTypeOfTypeTag(declaration);
44911         }
44912         function isResolvingReturnTypeOfSignature(signature) {
44913             return !signature.resolvedReturnType && findResolutionCycleStartIndex(signature, 3 /* ResolvedReturnType */) >= 0;
44914         }
44915         function getRestTypeOfSignature(signature) {
44916             return tryGetRestTypeOfSignature(signature) || anyType;
44917         }
44918         function tryGetRestTypeOfSignature(signature) {
44919             if (signatureHasRestParameter(signature)) {
44920                 var sigRestType = getTypeOfSymbol(signature.parameters[signature.parameters.length - 1]);
44921                 var restType = isTupleType(sigRestType) ? getRestTypeOfTupleType(sigRestType) : sigRestType;
44922                 return restType && getIndexTypeOfType(restType, 1 /* Number */);
44923             }
44924             return undefined;
44925         }
44926         function getSignatureInstantiation(signature, typeArguments, isJavascript, inferredTypeParameters) {
44927             var instantiatedSignature = getSignatureInstantiationWithoutFillingInTypeArguments(signature, fillMissingTypeArguments(typeArguments, signature.typeParameters, getMinTypeArgumentCount(signature.typeParameters), isJavascript));
44928             if (inferredTypeParameters) {
44929                 var returnSignature = getSingleCallOrConstructSignature(getReturnTypeOfSignature(instantiatedSignature));
44930                 if (returnSignature) {
44931                     var newReturnSignature = cloneSignature(returnSignature);
44932                     newReturnSignature.typeParameters = inferredTypeParameters;
44933                     var newInstantiatedSignature = cloneSignature(instantiatedSignature);
44934                     newInstantiatedSignature.resolvedReturnType = getOrCreateTypeFromSignature(newReturnSignature);
44935                     return newInstantiatedSignature;
44936                 }
44937             }
44938             return instantiatedSignature;
44939         }
44940         function getSignatureInstantiationWithoutFillingInTypeArguments(signature, typeArguments) {
44941             var instantiations = signature.instantiations || (signature.instantiations = ts.createMap());
44942             var id = getTypeListId(typeArguments);
44943             var instantiation = instantiations.get(id);
44944             if (!instantiation) {
44945                 instantiations.set(id, instantiation = createSignatureInstantiation(signature, typeArguments));
44946             }
44947             return instantiation;
44948         }
44949         function createSignatureInstantiation(signature, typeArguments) {
44950             return instantiateSignature(signature, createSignatureTypeMapper(signature, typeArguments), /*eraseTypeParameters*/ true);
44951         }
44952         function createSignatureTypeMapper(signature, typeArguments) {
44953             return createTypeMapper(signature.typeParameters, typeArguments);
44954         }
44955         function getErasedSignature(signature) {
44956             return signature.typeParameters ?
44957                 signature.erasedSignatureCache || (signature.erasedSignatureCache = createErasedSignature(signature)) :
44958                 signature;
44959         }
44960         function createErasedSignature(signature) {
44961             // Create an instantiation of the signature where all type arguments are the any type.
44962             return instantiateSignature(signature, createTypeEraser(signature.typeParameters), /*eraseTypeParameters*/ true);
44963         }
44964         function getCanonicalSignature(signature) {
44965             return signature.typeParameters ?
44966                 signature.canonicalSignatureCache || (signature.canonicalSignatureCache = createCanonicalSignature(signature)) :
44967                 signature;
44968         }
44969         function createCanonicalSignature(signature) {
44970             // Create an instantiation of the signature where each unconstrained type parameter is replaced with
44971             // its original. When a generic class or interface is instantiated, each generic method in the class or
44972             // interface is instantiated with a fresh set of cloned type parameters (which we need to handle scenarios
44973             // where different generations of the same type parameter are in scope). This leads to a lot of new type
44974             // identities, and potentially a lot of work comparing those identities, so here we create an instantiation
44975             // that uses the original type identities for all unconstrained type parameters.
44976             return getSignatureInstantiation(signature, ts.map(signature.typeParameters, function (tp) { return tp.target && !getConstraintOfTypeParameter(tp.target) ? tp.target : tp; }), ts.isInJSFile(signature.declaration));
44977         }
44978         function getBaseSignature(signature) {
44979             var typeParameters = signature.typeParameters;
44980             if (typeParameters) {
44981                 var typeEraser_1 = createTypeEraser(typeParameters);
44982                 var baseConstraints = ts.map(typeParameters, function (tp) { return instantiateType(getBaseConstraintOfType(tp), typeEraser_1) || unknownType; });
44983                 return instantiateSignature(signature, createTypeMapper(typeParameters, baseConstraints), /*eraseTypeParameters*/ true);
44984             }
44985             return signature;
44986         }
44987         function getOrCreateTypeFromSignature(signature) {
44988             // There are two ways to declare a construct signature, one is by declaring a class constructor
44989             // using the constructor keyword, and the other is declaring a bare construct signature in an
44990             // object type literal or interface (using the new keyword). Each way of declaring a constructor
44991             // will result in a different declaration kind.
44992             if (!signature.isolatedSignatureType) {
44993                 var kind = signature.declaration ? signature.declaration.kind : 0 /* Unknown */;
44994                 var isConstructor = kind === 162 /* Constructor */ || kind === 166 /* ConstructSignature */ || kind === 171 /* ConstructorType */;
44995                 var type = createObjectType(16 /* Anonymous */);
44996                 type.members = emptySymbols;
44997                 type.properties = ts.emptyArray;
44998                 type.callSignatures = !isConstructor ? [signature] : ts.emptyArray;
44999                 type.constructSignatures = isConstructor ? [signature] : ts.emptyArray;
45000                 signature.isolatedSignatureType = type;
45001             }
45002             return signature.isolatedSignatureType;
45003         }
45004         function getIndexSymbol(symbol) {
45005             return symbol.members.get("__index" /* Index */);
45006         }
45007         function getIndexDeclarationOfSymbol(symbol, kind) {
45008             var syntaxKind = kind === 1 /* Number */ ? 140 /* NumberKeyword */ : 143 /* StringKeyword */;
45009             var indexSymbol = getIndexSymbol(symbol);
45010             if (indexSymbol) {
45011                 for (var _i = 0, _a = indexSymbol.declarations; _i < _a.length; _i++) {
45012                     var decl = _a[_i];
45013                     var node = ts.cast(decl, ts.isIndexSignatureDeclaration);
45014                     if (node.parameters.length === 1) {
45015                         var parameter = node.parameters[0];
45016                         if (parameter.type && parameter.type.kind === syntaxKind) {
45017                             return node;
45018                         }
45019                     }
45020                 }
45021             }
45022             return undefined;
45023         }
45024         function createIndexInfo(type, isReadonly, declaration) {
45025             return { type: type, isReadonly: isReadonly, declaration: declaration };
45026         }
45027         function getIndexInfoOfSymbol(symbol, kind) {
45028             var declaration = getIndexDeclarationOfSymbol(symbol, kind);
45029             if (declaration) {
45030                 return createIndexInfo(declaration.type ? getTypeFromTypeNode(declaration.type) : anyType, ts.hasModifier(declaration, 64 /* Readonly */), declaration);
45031             }
45032             return undefined;
45033         }
45034         function getConstraintDeclaration(type) {
45035             return ts.mapDefined(ts.filter(type.symbol && type.symbol.declarations, ts.isTypeParameterDeclaration), ts.getEffectiveConstraintOfTypeParameter)[0];
45036         }
45037         function getInferredTypeParameterConstraint(typeParameter) {
45038             var inferences;
45039             if (typeParameter.symbol) {
45040                 for (var _i = 0, _a = typeParameter.symbol.declarations; _i < _a.length; _i++) {
45041                     var declaration = _a[_i];
45042                     if (declaration.parent.kind === 181 /* InferType */) {
45043                         // When an 'infer T' declaration is immediately contained in a type reference node
45044                         // (such as 'Foo<infer T>'), T's constraint is inferred from the constraint of the
45045                         // corresponding type parameter in 'Foo'. When multiple 'infer T' declarations are
45046                         // present, we form an intersection of the inferred constraint types.
45047                         var grandParent = declaration.parent.parent;
45048                         if (grandParent.kind === 169 /* TypeReference */) {
45049                             var typeReference = grandParent;
45050                             var typeParameters = getTypeParametersForTypeReference(typeReference);
45051                             if (typeParameters) {
45052                                 var index = typeReference.typeArguments.indexOf(declaration.parent);
45053                                 if (index < typeParameters.length) {
45054                                     var declaredConstraint = getConstraintOfTypeParameter(typeParameters[index]);
45055                                     if (declaredConstraint) {
45056                                         // Type parameter constraints can reference other type parameters so
45057                                         // constraints need to be instantiated. If instantiation produces the
45058                                         // type parameter itself, we discard that inference. For example, in
45059                                         //   type Foo<T extends string, U extends T> = [T, U];
45060                                         //   type Bar<T> = T extends Foo<infer X, infer X> ? Foo<X, X> : T;
45061                                         // the instantiated constraint for U is X, so we discard that inference.
45062                                         var mapper = createTypeMapper(typeParameters, getEffectiveTypeArguments(typeReference, typeParameters));
45063                                         var constraint = instantiateType(declaredConstraint, mapper);
45064                                         if (constraint !== typeParameter) {
45065                                             inferences = ts.append(inferences, constraint);
45066                                         }
45067                                     }
45068                                 }
45069                             }
45070                         }
45071                         // When an 'infer T' declaration is immediately contained in a rest parameter
45072                         // declaration, we infer an 'unknown[]' constraint.
45073                         else if (grandParent.kind === 156 /* Parameter */ && grandParent.dotDotDotToken) {
45074                             inferences = ts.append(inferences, createArrayType(unknownType));
45075                         }
45076                     }
45077                 }
45078             }
45079             return inferences && getIntersectionType(inferences);
45080         }
45081         /** This is a worker function. Use getConstraintOfTypeParameter which guards against circular constraints. */
45082         function getConstraintFromTypeParameter(typeParameter) {
45083             if (!typeParameter.constraint) {
45084                 if (typeParameter.target) {
45085                     var targetConstraint = getConstraintOfTypeParameter(typeParameter.target);
45086                     typeParameter.constraint = targetConstraint ? instantiateType(targetConstraint, typeParameter.mapper) : noConstraintType;
45087                 }
45088                 else {
45089                     var constraintDeclaration = getConstraintDeclaration(typeParameter);
45090                     if (!constraintDeclaration) {
45091                         typeParameter.constraint = getInferredTypeParameterConstraint(typeParameter) || noConstraintType;
45092                     }
45093                     else {
45094                         var type = getTypeFromTypeNode(constraintDeclaration);
45095                         if (type.flags & 1 /* Any */ && type !== errorType) { // Allow errorType to propegate to keep downstream errors suppressed
45096                             // use keyofConstraintType as the base constraint for mapped type key constraints (unknown isn;t assignable to that, but `any` was),
45097                             // use unknown otherwise
45098                             type = constraintDeclaration.parent.parent.kind === 186 /* MappedType */ ? keyofConstraintType : unknownType;
45099                         }
45100                         typeParameter.constraint = type;
45101                     }
45102                 }
45103             }
45104             return typeParameter.constraint === noConstraintType ? undefined : typeParameter.constraint;
45105         }
45106         function getParentSymbolOfTypeParameter(typeParameter) {
45107             var tp = ts.getDeclarationOfKind(typeParameter.symbol, 155 /* TypeParameter */);
45108             var host = ts.isJSDocTemplateTag(tp.parent) ? ts.getHostSignatureFromJSDoc(tp.parent) : tp.parent;
45109             return host && getSymbolOfNode(host);
45110         }
45111         function getTypeListId(types) {
45112             var result = "";
45113             if (types) {
45114                 var length_4 = types.length;
45115                 var i = 0;
45116                 while (i < length_4) {
45117                     var startId = types[i].id;
45118                     var count = 1;
45119                     while (i + count < length_4 && types[i + count].id === startId + count) {
45120                         count++;
45121                     }
45122                     if (result.length) {
45123                         result += ",";
45124                     }
45125                     result += startId;
45126                     if (count > 1) {
45127                         result += ":" + count;
45128                     }
45129                     i += count;
45130                 }
45131             }
45132             return result;
45133         }
45134         // This function is used to propagate certain flags when creating new object type references and union types.
45135         // It is only necessary to do so if a constituent type might be the undefined type, the null type, the type
45136         // of an object literal or the anyFunctionType. This is because there are operations in the type checker
45137         // that care about the presence of such types at arbitrary depth in a containing type.
45138         function getPropagatingFlagsOfTypes(types, excludeKinds) {
45139             var result = 0;
45140             for (var _i = 0, types_8 = types; _i < types_8.length; _i++) {
45141                 var type = types_8[_i];
45142                 if (!(type.flags & excludeKinds)) {
45143                     result |= ts.getObjectFlags(type);
45144                 }
45145             }
45146             return result & 3670016 /* PropagatingFlags */;
45147         }
45148         function createTypeReference(target, typeArguments) {
45149             var id = getTypeListId(typeArguments);
45150             var type = target.instantiations.get(id);
45151             if (!type) {
45152                 type = createObjectType(4 /* Reference */, target.symbol);
45153                 target.instantiations.set(id, type);
45154                 type.objectFlags |= typeArguments ? getPropagatingFlagsOfTypes(typeArguments, /*excludeKinds*/ 0) : 0;
45155                 type.target = target;
45156                 type.resolvedTypeArguments = typeArguments;
45157             }
45158             return type;
45159         }
45160         function cloneTypeReference(source) {
45161             var type = createType(source.flags);
45162             type.symbol = source.symbol;
45163             type.objectFlags = source.objectFlags;
45164             type.target = source.target;
45165             type.resolvedTypeArguments = source.resolvedTypeArguments;
45166             return type;
45167         }
45168         function createDeferredTypeReference(target, node, mapper) {
45169             var aliasSymbol = getAliasSymbolForTypeNode(node);
45170             var aliasTypeArguments = getTypeArgumentsForAliasSymbol(aliasSymbol);
45171             var type = createObjectType(4 /* Reference */, target.symbol);
45172             type.target = target;
45173             type.node = node;
45174             type.mapper = mapper;
45175             type.aliasSymbol = aliasSymbol;
45176             type.aliasTypeArguments = mapper ? instantiateTypes(aliasTypeArguments, mapper) : aliasTypeArguments;
45177             return type;
45178         }
45179         function getTypeArguments(type) {
45180             var _a, _b;
45181             if (!type.resolvedTypeArguments) {
45182                 if (!pushTypeResolution(type, 6 /* ResolvedTypeArguments */)) {
45183                     return ((_a = type.target.localTypeParameters) === null || _a === void 0 ? void 0 : _a.map(function () { return errorType; })) || ts.emptyArray;
45184                 }
45185                 var node = type.node;
45186                 var typeArguments = !node ? ts.emptyArray :
45187                     node.kind === 169 /* TypeReference */ ? ts.concatenate(type.target.outerTypeParameters, getEffectiveTypeArguments(node, type.target.localTypeParameters)) :
45188                         node.kind === 174 /* ArrayType */ ? [getTypeFromTypeNode(node.elementType)] :
45189                             ts.map(node.elementTypes, getTypeFromTypeNode);
45190                 if (popTypeResolution()) {
45191                     type.resolvedTypeArguments = type.mapper ? instantiateTypes(typeArguments, type.mapper) : typeArguments;
45192                 }
45193                 else {
45194                     type.resolvedTypeArguments = ((_b = type.target.localTypeParameters) === null || _b === void 0 ? void 0 : _b.map(function () { return errorType; })) || ts.emptyArray;
45195                     error(type.node || currentNode, type.target.symbol
45196                         ? ts.Diagnostics.Type_arguments_for_0_circularly_reference_themselves
45197                         : ts.Diagnostics.Tuple_type_arguments_circularly_reference_themselves, type.target.symbol && symbolToString(type.target.symbol));
45198                 }
45199             }
45200             return type.resolvedTypeArguments;
45201         }
45202         function getTypeReferenceArity(type) {
45203             return ts.length(type.target.typeParameters);
45204         }
45205         /**
45206          * Get type from type-reference that reference to class or interface
45207          */
45208         function getTypeFromClassOrInterfaceReference(node, symbol) {
45209             var type = getDeclaredTypeOfSymbol(getMergedSymbol(symbol));
45210             var typeParameters = type.localTypeParameters;
45211             if (typeParameters) {
45212                 var numTypeArguments = ts.length(node.typeArguments);
45213                 var minTypeArgumentCount = getMinTypeArgumentCount(typeParameters);
45214                 var isJs = ts.isInJSFile(node);
45215                 var isJsImplicitAny = !noImplicitAny && isJs;
45216                 if (!isJsImplicitAny && (numTypeArguments < minTypeArgumentCount || numTypeArguments > typeParameters.length)) {
45217                     var missingAugmentsTag = isJs && ts.isExpressionWithTypeArguments(node) && !ts.isJSDocAugmentsTag(node.parent);
45218                     var diag = minTypeArgumentCount === typeParameters.length ?
45219                         missingAugmentsTag ?
45220                             ts.Diagnostics.Expected_0_type_arguments_provide_these_with_an_extends_tag :
45221                             ts.Diagnostics.Generic_type_0_requires_1_type_argument_s :
45222                         missingAugmentsTag ?
45223                             ts.Diagnostics.Expected_0_1_type_arguments_provide_these_with_an_extends_tag :
45224                             ts.Diagnostics.Generic_type_0_requires_between_1_and_2_type_arguments;
45225                     var typeStr = typeToString(type, /*enclosingDeclaration*/ undefined, 2 /* WriteArrayAsGenericType */);
45226                     error(node, diag, typeStr, minTypeArgumentCount, typeParameters.length);
45227                     if (!isJs) {
45228                         // TODO: Adopt same permissive behavior in TS as in JS to reduce follow-on editing experience failures (requires editing fillMissingTypeArguments)
45229                         return errorType;
45230                     }
45231                 }
45232                 if (node.kind === 169 /* TypeReference */ && isDeferredTypeReferenceNode(node, ts.length(node.typeArguments) !== typeParameters.length)) {
45233                     return createDeferredTypeReference(type, node, /*mapper*/ undefined);
45234                 }
45235                 // In a type reference, the outer type parameters of the referenced class or interface are automatically
45236                 // supplied as type arguments and the type reference only specifies arguments for the local type parameters
45237                 // of the class or interface.
45238                 var typeArguments = ts.concatenate(type.outerTypeParameters, fillMissingTypeArguments(typeArgumentsFromTypeReferenceNode(node), typeParameters, minTypeArgumentCount, isJs));
45239                 return createTypeReference(type, typeArguments);
45240             }
45241             return checkNoTypeArguments(node, symbol) ? type : errorType;
45242         }
45243         function getTypeAliasInstantiation(symbol, typeArguments) {
45244             var type = getDeclaredTypeOfSymbol(symbol);
45245             var links = getSymbolLinks(symbol);
45246             var typeParameters = links.typeParameters;
45247             var id = getTypeListId(typeArguments);
45248             var instantiation = links.instantiations.get(id);
45249             if (!instantiation) {
45250                 links.instantiations.set(id, instantiation = instantiateType(type, createTypeMapper(typeParameters, fillMissingTypeArguments(typeArguments, typeParameters, getMinTypeArgumentCount(typeParameters), ts.isInJSFile(symbol.valueDeclaration)))));
45251             }
45252             return instantiation;
45253         }
45254         /**
45255          * Get type from reference to type alias. When a type alias is generic, the declared type of the type alias may include
45256          * references to the type parameters of the alias. We replace those with the actual type arguments by instantiating the
45257          * declared type. Instantiations are cached using the type identities of the type arguments as the key.
45258          */
45259         function getTypeFromTypeAliasReference(node, symbol) {
45260             var type = getDeclaredTypeOfSymbol(symbol);
45261             var typeParameters = getSymbolLinks(symbol).typeParameters;
45262             if (typeParameters) {
45263                 var numTypeArguments = ts.length(node.typeArguments);
45264                 var minTypeArgumentCount = getMinTypeArgumentCount(typeParameters);
45265                 if (numTypeArguments < minTypeArgumentCount || numTypeArguments > typeParameters.length) {
45266                     error(node, minTypeArgumentCount === typeParameters.length ?
45267                         ts.Diagnostics.Generic_type_0_requires_1_type_argument_s :
45268                         ts.Diagnostics.Generic_type_0_requires_between_1_and_2_type_arguments, symbolToString(symbol), minTypeArgumentCount, typeParameters.length);
45269                     return errorType;
45270                 }
45271                 return getTypeAliasInstantiation(symbol, typeArgumentsFromTypeReferenceNode(node));
45272             }
45273             return checkNoTypeArguments(node, symbol) ? type : errorType;
45274         }
45275         function getTypeReferenceName(node) {
45276             switch (node.kind) {
45277                 case 169 /* TypeReference */:
45278                     return node.typeName;
45279                 case 216 /* ExpressionWithTypeArguments */:
45280                     // We only support expressions that are simple qualified names. For other
45281                     // expressions this produces undefined.
45282                     var expr = node.expression;
45283                     if (ts.isEntityNameExpression(expr)) {
45284                         return expr;
45285                     }
45286                 // fall through;
45287             }
45288             return undefined;
45289         }
45290         function resolveTypeReferenceName(typeReferenceName, meaning, ignoreErrors) {
45291             if (!typeReferenceName) {
45292                 return unknownSymbol;
45293             }
45294             return resolveEntityName(typeReferenceName, meaning, ignoreErrors) || unknownSymbol;
45295         }
45296         function getTypeReferenceType(node, symbol) {
45297             if (symbol === unknownSymbol) {
45298                 return errorType;
45299             }
45300             symbol = getExpandoSymbol(symbol) || symbol;
45301             if (symbol.flags & (32 /* Class */ | 64 /* Interface */)) {
45302                 return getTypeFromClassOrInterfaceReference(node, symbol);
45303             }
45304             if (symbol.flags & 524288 /* TypeAlias */) {
45305                 return getTypeFromTypeAliasReference(node, symbol);
45306             }
45307             // Get type from reference to named type that cannot be generic (enum or type parameter)
45308             var res = tryGetDeclaredTypeOfSymbol(symbol);
45309             if (res) {
45310                 return checkNoTypeArguments(node, symbol) ? getRegularTypeOfLiteralType(res) : errorType;
45311             }
45312             if (symbol.flags & 111551 /* Value */ && isJSDocTypeReference(node)) {
45313                 var jsdocType = getTypeFromJSDocValueReference(node, symbol);
45314                 if (jsdocType) {
45315                     return jsdocType;
45316                 }
45317                 else {
45318                     // Resolve the type reference as a Type for the purpose of reporting errors.
45319                     resolveTypeReferenceName(getTypeReferenceName(node), 788968 /* Type */);
45320                     return getTypeOfSymbol(symbol);
45321                 }
45322             }
45323             return errorType;
45324         }
45325         /**
45326          * A JSdoc TypeReference may be to a value, but resolve it as a type anyway.
45327          * Note: If the value is imported from commonjs, it should really be an alias,
45328          * but this function's special-case code fakes alias resolution as well.
45329          */
45330         function getTypeFromJSDocValueReference(node, symbol) {
45331             var links = getNodeLinks(node);
45332             if (!links.resolvedJSDocType) {
45333                 var valueType = getTypeOfSymbol(symbol);
45334                 var typeType = valueType;
45335                 if (symbol.valueDeclaration) {
45336                     var decl = ts.getRootDeclaration(symbol.valueDeclaration);
45337                     var isRequireAlias = false;
45338                     if (ts.isVariableDeclaration(decl) && decl.initializer) {
45339                         var expr = decl.initializer;
45340                         // skip past entity names, eg `require("x").a.b.c`
45341                         while (ts.isPropertyAccessExpression(expr)) {
45342                             expr = expr.expression;
45343                         }
45344                         isRequireAlias = ts.isCallExpression(expr) && ts.isRequireCall(expr, /*requireStringLiteralLikeArgument*/ true) && !!valueType.symbol;
45345                     }
45346                     var isImportTypeWithQualifier = node.kind === 188 /* ImportType */ && node.qualifier;
45347                     // valueType might not have a symbol, eg, {import('./b').STRING_LITERAL}
45348                     if (valueType.symbol && (isRequireAlias || isImportTypeWithQualifier)) {
45349                         typeType = getTypeReferenceType(node, valueType.symbol);
45350                     }
45351                 }
45352                 links.resolvedJSDocType = typeType;
45353             }
45354             return links.resolvedJSDocType;
45355         }
45356         function getSubstitutionType(baseType, substitute) {
45357             if (substitute.flags & 3 /* AnyOrUnknown */ || substitute === baseType) {
45358                 return baseType;
45359             }
45360             var id = getTypeId(baseType) + ">" + getTypeId(substitute);
45361             var cached = substitutionTypes.get(id);
45362             if (cached) {
45363                 return cached;
45364             }
45365             var result = createType(33554432 /* Substitution */);
45366             result.baseType = baseType;
45367             result.substitute = substitute;
45368             substitutionTypes.set(id, result);
45369             return result;
45370         }
45371         function isUnaryTupleTypeNode(node) {
45372             return node.kind === 175 /* TupleType */ && node.elementTypes.length === 1;
45373         }
45374         function getImpliedConstraint(type, checkNode, extendsNode) {
45375             return isUnaryTupleTypeNode(checkNode) && isUnaryTupleTypeNode(extendsNode) ? getImpliedConstraint(type, checkNode.elementTypes[0], extendsNode.elementTypes[0]) :
45376                 getActualTypeVariable(getTypeFromTypeNode(checkNode)) === type ? getTypeFromTypeNode(extendsNode) :
45377                     undefined;
45378         }
45379         function getConditionalFlowTypeOfType(type, node) {
45380             var constraints;
45381             while (node && !ts.isStatement(node) && node.kind !== 303 /* JSDocComment */) {
45382                 var parent = node.parent;
45383                 if (parent.kind === 180 /* ConditionalType */ && node === parent.trueType) {
45384                     var constraint = getImpliedConstraint(type, parent.checkType, parent.extendsType);
45385                     if (constraint) {
45386                         constraints = ts.append(constraints, constraint);
45387                     }
45388                 }
45389                 node = parent;
45390             }
45391             return constraints ? getSubstitutionType(type, getIntersectionType(ts.append(constraints, type))) : type;
45392         }
45393         function isJSDocTypeReference(node) {
45394             return !!(node.flags & 4194304 /* JSDoc */) && (node.kind === 169 /* TypeReference */ || node.kind === 188 /* ImportType */);
45395         }
45396         function checkNoTypeArguments(node, symbol) {
45397             if (node.typeArguments) {
45398                 error(node, ts.Diagnostics.Type_0_is_not_generic, symbol ? symbolToString(symbol) : node.typeName ? ts.declarationNameToString(node.typeName) : anon);
45399                 return false;
45400             }
45401             return true;
45402         }
45403         function getIntendedTypeFromJSDocTypeReference(node) {
45404             if (ts.isIdentifier(node.typeName)) {
45405                 var typeArgs = node.typeArguments;
45406                 switch (node.typeName.escapedText) {
45407                     case "String":
45408                         checkNoTypeArguments(node);
45409                         return stringType;
45410                     case "Number":
45411                         checkNoTypeArguments(node);
45412                         return numberType;
45413                     case "Boolean":
45414                         checkNoTypeArguments(node);
45415                         return booleanType;
45416                     case "Void":
45417                         checkNoTypeArguments(node);
45418                         return voidType;
45419                     case "Undefined":
45420                         checkNoTypeArguments(node);
45421                         return undefinedType;
45422                     case "Null":
45423                         checkNoTypeArguments(node);
45424                         return nullType;
45425                     case "Function":
45426                     case "function":
45427                         checkNoTypeArguments(node);
45428                         return globalFunctionType;
45429                     case "array":
45430                         return (!typeArgs || !typeArgs.length) && !noImplicitAny ? anyArrayType : undefined;
45431                     case "promise":
45432                         return (!typeArgs || !typeArgs.length) && !noImplicitAny ? createPromiseType(anyType) : undefined;
45433                     case "Object":
45434                         if (typeArgs && typeArgs.length === 2) {
45435                             if (ts.isJSDocIndexSignature(node)) {
45436                                 var indexed = getTypeFromTypeNode(typeArgs[0]);
45437                                 var target = getTypeFromTypeNode(typeArgs[1]);
45438                                 var index = createIndexInfo(target, /*isReadonly*/ false);
45439                                 return createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, indexed === stringType ? index : undefined, indexed === numberType ? index : undefined);
45440                             }
45441                             return anyType;
45442                         }
45443                         checkNoTypeArguments(node);
45444                         return !noImplicitAny ? anyType : undefined;
45445                 }
45446             }
45447         }
45448         function getTypeFromJSDocNullableTypeNode(node) {
45449             var type = getTypeFromTypeNode(node.type);
45450             return strictNullChecks ? getNullableType(type, 65536 /* Null */) : type;
45451         }
45452         function getTypeFromTypeReference(node) {
45453             var links = getNodeLinks(node);
45454             if (!links.resolvedType) {
45455                 // handle LS queries on the `const` in `x as const` by resolving to the type of `x`
45456                 if (ts.isConstTypeReference(node) && ts.isAssertionExpression(node.parent)) {
45457                     links.resolvedSymbol = unknownSymbol;
45458                     return links.resolvedType = checkExpressionCached(node.parent.expression);
45459                 }
45460                 var symbol = void 0;
45461                 var type = void 0;
45462                 var meaning = 788968 /* Type */;
45463                 if (isJSDocTypeReference(node)) {
45464                     type = getIntendedTypeFromJSDocTypeReference(node);
45465                     if (!type) {
45466                         symbol = resolveTypeReferenceName(getTypeReferenceName(node), meaning, /*ignoreErrors*/ true);
45467                         if (symbol === unknownSymbol) {
45468                             symbol = resolveTypeReferenceName(getTypeReferenceName(node), meaning | 111551 /* Value */);
45469                         }
45470                         else {
45471                             resolveTypeReferenceName(getTypeReferenceName(node), meaning); // Resolve again to mark errors, if any
45472                         }
45473                         type = getTypeReferenceType(node, symbol);
45474                     }
45475                 }
45476                 if (!type) {
45477                     symbol = resolveTypeReferenceName(getTypeReferenceName(node), meaning);
45478                     type = getTypeReferenceType(node, symbol);
45479                 }
45480                 // Cache both the resolved symbol and the resolved type. The resolved symbol is needed when we check the
45481                 // type reference in checkTypeReferenceNode.
45482                 links.resolvedSymbol = symbol;
45483                 links.resolvedType = type;
45484             }
45485             return links.resolvedType;
45486         }
45487         function typeArgumentsFromTypeReferenceNode(node) {
45488             return ts.map(node.typeArguments, getTypeFromTypeNode);
45489         }
45490         function getTypeFromTypeQueryNode(node) {
45491             var links = getNodeLinks(node);
45492             if (!links.resolvedType) {
45493                 // TypeScript 1.0 spec (April 2014): 3.6.3
45494                 // The expression is processed as an identifier expression (section 4.3)
45495                 // or property access expression(section 4.10),
45496                 // the widened type(section 3.9) of which becomes the result.
45497                 links.resolvedType = getRegularTypeOfLiteralType(getWidenedType(checkExpression(node.exprName)));
45498             }
45499             return links.resolvedType;
45500         }
45501         function getTypeOfGlobalSymbol(symbol, arity) {
45502             function getTypeDeclaration(symbol) {
45503                 var declarations = symbol.declarations;
45504                 for (var _i = 0, declarations_3 = declarations; _i < declarations_3.length; _i++) {
45505                     var declaration = declarations_3[_i];
45506                     switch (declaration.kind) {
45507                         case 245 /* ClassDeclaration */:
45508                         case 246 /* InterfaceDeclaration */:
45509                         case 248 /* EnumDeclaration */:
45510                             return declaration;
45511                     }
45512                 }
45513             }
45514             if (!symbol) {
45515                 return arity ? emptyGenericType : emptyObjectType;
45516             }
45517             var type = getDeclaredTypeOfSymbol(symbol);
45518             if (!(type.flags & 524288 /* Object */)) {
45519                 error(getTypeDeclaration(symbol), ts.Diagnostics.Global_type_0_must_be_a_class_or_interface_type, ts.symbolName(symbol));
45520                 return arity ? emptyGenericType : emptyObjectType;
45521             }
45522             if (ts.length(type.typeParameters) !== arity) {
45523                 error(getTypeDeclaration(symbol), ts.Diagnostics.Global_type_0_must_have_1_type_parameter_s, ts.symbolName(symbol), arity);
45524                 return arity ? emptyGenericType : emptyObjectType;
45525             }
45526             return type;
45527         }
45528         function getGlobalValueSymbol(name, reportErrors) {
45529             return getGlobalSymbol(name, 111551 /* Value */, reportErrors ? ts.Diagnostics.Cannot_find_global_value_0 : undefined);
45530         }
45531         function getGlobalTypeSymbol(name, reportErrors) {
45532             return getGlobalSymbol(name, 788968 /* Type */, reportErrors ? ts.Diagnostics.Cannot_find_global_type_0 : undefined);
45533         }
45534         function getGlobalSymbol(name, meaning, diagnostic) {
45535             // Don't track references for global symbols anyway, so value if `isReference` is arbitrary
45536             return resolveName(undefined, name, meaning, diagnostic, name, /*isUse*/ false);
45537         }
45538         function getGlobalType(name, arity, reportErrors) {
45539             var symbol = getGlobalTypeSymbol(name, reportErrors);
45540             return symbol || reportErrors ? getTypeOfGlobalSymbol(symbol, arity) : undefined;
45541         }
45542         function getGlobalTypedPropertyDescriptorType() {
45543             return deferredGlobalTypedPropertyDescriptorType || (deferredGlobalTypedPropertyDescriptorType = getGlobalType("TypedPropertyDescriptor", /*arity*/ 1, /*reportErrors*/ true)) || emptyGenericType;
45544         }
45545         function getGlobalTemplateStringsArrayType() {
45546             return deferredGlobalTemplateStringsArrayType || (deferredGlobalTemplateStringsArrayType = getGlobalType("TemplateStringsArray", /*arity*/ 0, /*reportErrors*/ true)) || emptyObjectType;
45547         }
45548         function getGlobalImportMetaType() {
45549             return deferredGlobalImportMetaType || (deferredGlobalImportMetaType = getGlobalType("ImportMeta", /*arity*/ 0, /*reportErrors*/ true)) || emptyObjectType;
45550         }
45551         function getGlobalESSymbolConstructorSymbol(reportErrors) {
45552             return deferredGlobalESSymbolConstructorSymbol || (deferredGlobalESSymbolConstructorSymbol = getGlobalValueSymbol("Symbol", reportErrors));
45553         }
45554         function getGlobalESSymbolType(reportErrors) {
45555             return deferredGlobalESSymbolType || (deferredGlobalESSymbolType = getGlobalType("Symbol", /*arity*/ 0, reportErrors)) || emptyObjectType;
45556         }
45557         function getGlobalPromiseType(reportErrors) {
45558             return deferredGlobalPromiseType || (deferredGlobalPromiseType = getGlobalType("Promise", /*arity*/ 1, reportErrors)) || emptyGenericType;
45559         }
45560         function getGlobalPromiseLikeType(reportErrors) {
45561             return deferredGlobalPromiseLikeType || (deferredGlobalPromiseLikeType = getGlobalType("PromiseLike", /*arity*/ 1, reportErrors)) || emptyGenericType;
45562         }
45563         function getGlobalPromiseConstructorSymbol(reportErrors) {
45564             return deferredGlobalPromiseConstructorSymbol || (deferredGlobalPromiseConstructorSymbol = getGlobalValueSymbol("Promise", reportErrors));
45565         }
45566         function getGlobalPromiseConstructorLikeType(reportErrors) {
45567             return deferredGlobalPromiseConstructorLikeType || (deferredGlobalPromiseConstructorLikeType = getGlobalType("PromiseConstructorLike", /*arity*/ 0, reportErrors)) || emptyObjectType;
45568         }
45569         function getGlobalAsyncIterableType(reportErrors) {
45570             return deferredGlobalAsyncIterableType || (deferredGlobalAsyncIterableType = getGlobalType("AsyncIterable", /*arity*/ 1, reportErrors)) || emptyGenericType;
45571         }
45572         function getGlobalAsyncIteratorType(reportErrors) {
45573             return deferredGlobalAsyncIteratorType || (deferredGlobalAsyncIteratorType = getGlobalType("AsyncIterator", /*arity*/ 3, reportErrors)) || emptyGenericType;
45574         }
45575         function getGlobalAsyncIterableIteratorType(reportErrors) {
45576             return deferredGlobalAsyncIterableIteratorType || (deferredGlobalAsyncIterableIteratorType = getGlobalType("AsyncIterableIterator", /*arity*/ 1, reportErrors)) || emptyGenericType;
45577         }
45578         function getGlobalAsyncGeneratorType(reportErrors) {
45579             return deferredGlobalAsyncGeneratorType || (deferredGlobalAsyncGeneratorType = getGlobalType("AsyncGenerator", /*arity*/ 3, reportErrors)) || emptyGenericType;
45580         }
45581         function getGlobalIterableType(reportErrors) {
45582             return deferredGlobalIterableType || (deferredGlobalIterableType = getGlobalType("Iterable", /*arity*/ 1, reportErrors)) || emptyGenericType;
45583         }
45584         function getGlobalIteratorType(reportErrors) {
45585             return deferredGlobalIteratorType || (deferredGlobalIteratorType = getGlobalType("Iterator", /*arity*/ 3, reportErrors)) || emptyGenericType;
45586         }
45587         function getGlobalIterableIteratorType(reportErrors) {
45588             return deferredGlobalIterableIteratorType || (deferredGlobalIterableIteratorType = getGlobalType("IterableIterator", /*arity*/ 1, reportErrors)) || emptyGenericType;
45589         }
45590         function getGlobalGeneratorType(reportErrors) {
45591             return deferredGlobalGeneratorType || (deferredGlobalGeneratorType = getGlobalType("Generator", /*arity*/ 3, reportErrors)) || emptyGenericType;
45592         }
45593         function getGlobalIteratorYieldResultType(reportErrors) {
45594             return deferredGlobalIteratorYieldResultType || (deferredGlobalIteratorYieldResultType = getGlobalType("IteratorYieldResult", /*arity*/ 1, reportErrors)) || emptyGenericType;
45595         }
45596         function getGlobalIteratorReturnResultType(reportErrors) {
45597             return deferredGlobalIteratorReturnResultType || (deferredGlobalIteratorReturnResultType = getGlobalType("IteratorReturnResult", /*arity*/ 1, reportErrors)) || emptyGenericType;
45598         }
45599         function getGlobalTypeOrUndefined(name, arity) {
45600             if (arity === void 0) { arity = 0; }
45601             var symbol = getGlobalSymbol(name, 788968 /* Type */, /*diagnostic*/ undefined);
45602             return symbol && getTypeOfGlobalSymbol(symbol, arity);
45603         }
45604         function getGlobalExtractSymbol() {
45605             return deferredGlobalExtractSymbol || (deferredGlobalExtractSymbol = getGlobalSymbol("Extract", 524288 /* TypeAlias */, ts.Diagnostics.Cannot_find_global_type_0)); // TODO: GH#18217
45606         }
45607         function getGlobalOmitSymbol() {
45608             return deferredGlobalOmitSymbol || (deferredGlobalOmitSymbol = getGlobalSymbol("Omit", 524288 /* TypeAlias */, ts.Diagnostics.Cannot_find_global_type_0)); // TODO: GH#18217
45609         }
45610         function getGlobalBigIntType(reportErrors) {
45611             return deferredGlobalBigIntType || (deferredGlobalBigIntType = getGlobalType("BigInt", /*arity*/ 0, reportErrors)) || emptyObjectType;
45612         }
45613         /**
45614          * Instantiates a global type that is generic with some element type, and returns that instantiation.
45615          */
45616         function createTypeFromGenericGlobalType(genericGlobalType, typeArguments) {
45617             return genericGlobalType !== emptyGenericType ? createTypeReference(genericGlobalType, typeArguments) : emptyObjectType;
45618         }
45619         function createTypedPropertyDescriptorType(propertyType) {
45620             return createTypeFromGenericGlobalType(getGlobalTypedPropertyDescriptorType(), [propertyType]);
45621         }
45622         function createIterableType(iteratedType) {
45623             return createTypeFromGenericGlobalType(getGlobalIterableType(/*reportErrors*/ true), [iteratedType]);
45624         }
45625         function createArrayType(elementType, readonly) {
45626             return createTypeFromGenericGlobalType(readonly ? globalReadonlyArrayType : globalArrayType, [elementType]);
45627         }
45628         function getArrayOrTupleTargetType(node) {
45629             var readonly = isReadonlyTypeOperator(node.parent);
45630             if (node.kind === 174 /* ArrayType */ || node.elementTypes.length === 1 && node.elementTypes[0].kind === 177 /* RestType */) {
45631                 return readonly ? globalReadonlyArrayType : globalArrayType;
45632             }
45633             var lastElement = ts.lastOrUndefined(node.elementTypes);
45634             var restElement = lastElement && lastElement.kind === 177 /* RestType */ ? lastElement : undefined;
45635             var minLength = ts.findLastIndex(node.elementTypes, function (n) { return n.kind !== 176 /* OptionalType */ && n !== restElement; }) + 1;
45636             return getTupleTypeOfArity(node.elementTypes.length, minLength, !!restElement, readonly, /*associatedNames*/ undefined);
45637         }
45638         // Return true if the given type reference node is directly aliased or if it needs to be deferred
45639         // because it is possibly contained in a circular chain of eagerly resolved types.
45640         function isDeferredTypeReferenceNode(node, hasDefaultTypeArguments) {
45641             return !!getAliasSymbolForTypeNode(node) || isResolvedByTypeAlias(node) && (node.kind === 174 /* ArrayType */ ? mayResolveTypeAlias(node.elementType) :
45642                 node.kind === 175 /* TupleType */ ? ts.some(node.elementTypes, mayResolveTypeAlias) :
45643                     hasDefaultTypeArguments || ts.some(node.typeArguments, mayResolveTypeAlias));
45644         }
45645         // Return true when the given node is transitively contained in type constructs that eagerly
45646         // resolve their constituent types. We include SyntaxKind.TypeReference because type arguments
45647         // of type aliases are eagerly resolved.
45648         function isResolvedByTypeAlias(node) {
45649             var parent = node.parent;
45650             switch (parent.kind) {
45651                 case 182 /* ParenthesizedType */:
45652                 case 169 /* TypeReference */:
45653                 case 178 /* UnionType */:
45654                 case 179 /* IntersectionType */:
45655                 case 185 /* IndexedAccessType */:
45656                 case 180 /* ConditionalType */:
45657                 case 184 /* TypeOperator */:
45658                 case 174 /* ArrayType */:
45659                 case 175 /* TupleType */:
45660                     return isResolvedByTypeAlias(parent);
45661                 case 247 /* TypeAliasDeclaration */:
45662                     return true;
45663             }
45664             return false;
45665         }
45666         // Return true if resolving the given node (i.e. getTypeFromTypeNode) possibly causes resolution
45667         // of a type alias.
45668         function mayResolveTypeAlias(node) {
45669             switch (node.kind) {
45670                 case 169 /* TypeReference */:
45671                     return isJSDocTypeReference(node) || !!(resolveTypeReferenceName(node.typeName, 788968 /* Type */).flags & 524288 /* TypeAlias */);
45672                 case 172 /* TypeQuery */:
45673                     return true;
45674                 case 184 /* TypeOperator */:
45675                     return node.operator !== 147 /* UniqueKeyword */ && mayResolveTypeAlias(node.type);
45676                 case 182 /* ParenthesizedType */:
45677                 case 176 /* OptionalType */:
45678                 case 299 /* JSDocOptionalType */:
45679                 case 297 /* JSDocNullableType */:
45680                 case 298 /* JSDocNonNullableType */:
45681                 case 294 /* JSDocTypeExpression */:
45682                     return mayResolveTypeAlias(node.type);
45683                 case 177 /* RestType */:
45684                     return node.type.kind !== 174 /* ArrayType */ || mayResolveTypeAlias(node.type.elementType);
45685                 case 178 /* UnionType */:
45686                 case 179 /* IntersectionType */:
45687                     return ts.some(node.types, mayResolveTypeAlias);
45688                 case 185 /* IndexedAccessType */:
45689                     return mayResolveTypeAlias(node.objectType) || mayResolveTypeAlias(node.indexType);
45690                 case 180 /* ConditionalType */:
45691                     return mayResolveTypeAlias(node.checkType) || mayResolveTypeAlias(node.extendsType) ||
45692                         mayResolveTypeAlias(node.trueType) || mayResolveTypeAlias(node.falseType);
45693             }
45694             return false;
45695         }
45696         function getTypeFromArrayOrTupleTypeNode(node) {
45697             var links = getNodeLinks(node);
45698             if (!links.resolvedType) {
45699                 var target = getArrayOrTupleTargetType(node);
45700                 if (target === emptyGenericType) {
45701                     links.resolvedType = emptyObjectType;
45702                 }
45703                 else if (isDeferredTypeReferenceNode(node)) {
45704                     links.resolvedType = node.kind === 175 /* TupleType */ && node.elementTypes.length === 0 ? target :
45705                         createDeferredTypeReference(target, node, /*mapper*/ undefined);
45706                 }
45707                 else {
45708                     var elementTypes = node.kind === 174 /* ArrayType */ ? [getTypeFromTypeNode(node.elementType)] : ts.map(node.elementTypes, getTypeFromTypeNode);
45709                     links.resolvedType = createTypeReference(target, elementTypes);
45710                 }
45711             }
45712             return links.resolvedType;
45713         }
45714         function isReadonlyTypeOperator(node) {
45715             return ts.isTypeOperatorNode(node) && node.operator === 138 /* ReadonlyKeyword */;
45716         }
45717         // We represent tuple types as type references to synthesized generic interface types created by
45718         // this function. The types are of the form:
45719         //
45720         //   interface Tuple<T0, T1, T2, ...> extends Array<T0 | T1 | T2 | ...> { 0: T0, 1: T1, 2: T2, ... }
45721         //
45722         // Note that the generic type created by this function has no symbol associated with it. The same
45723         // is true for each of the synthesized type parameters.
45724         function createTupleTypeOfArity(arity, minLength, hasRestElement, readonly, associatedNames) {
45725             var typeParameters;
45726             var properties = [];
45727             var maxLength = hasRestElement ? arity - 1 : arity;
45728             if (arity) {
45729                 typeParameters = new Array(arity);
45730                 for (var i = 0; i < arity; i++) {
45731                     var typeParameter = typeParameters[i] = createTypeParameter();
45732                     if (i < maxLength) {
45733                         var property = createSymbol(4 /* Property */ | (i >= minLength ? 16777216 /* Optional */ : 0), "" + i, readonly ? 8 /* Readonly */ : 0);
45734                         property.type = typeParameter;
45735                         properties.push(property);
45736                     }
45737                 }
45738             }
45739             var literalTypes = [];
45740             for (var i = minLength; i <= maxLength; i++)
45741                 literalTypes.push(getLiteralType(i));
45742             var lengthSymbol = createSymbol(4 /* Property */, "length");
45743             lengthSymbol.type = hasRestElement ? numberType : getUnionType(literalTypes);
45744             properties.push(lengthSymbol);
45745             var type = createObjectType(8 /* Tuple */ | 4 /* Reference */);
45746             type.typeParameters = typeParameters;
45747             type.outerTypeParameters = undefined;
45748             type.localTypeParameters = typeParameters;
45749             type.instantiations = ts.createMap();
45750             type.instantiations.set(getTypeListId(type.typeParameters), type);
45751             type.target = type;
45752             type.resolvedTypeArguments = type.typeParameters;
45753             type.thisType = createTypeParameter();
45754             type.thisType.isThisType = true;
45755             type.thisType.constraint = type;
45756             type.declaredProperties = properties;
45757             type.declaredCallSignatures = ts.emptyArray;
45758             type.declaredConstructSignatures = ts.emptyArray;
45759             type.declaredStringIndexInfo = undefined;
45760             type.declaredNumberIndexInfo = undefined;
45761             type.minLength = minLength;
45762             type.hasRestElement = hasRestElement;
45763             type.readonly = readonly;
45764             type.associatedNames = associatedNames;
45765             return type;
45766         }
45767         function getTupleTypeOfArity(arity, minLength, hasRestElement, readonly, associatedNames) {
45768             var key = arity + (hasRestElement ? "+" : ",") + minLength + (readonly ? "R" : "") + (associatedNames && associatedNames.length ? "," + associatedNames.join(",") : "");
45769             var type = tupleTypes.get(key);
45770             if (!type) {
45771                 tupleTypes.set(key, type = createTupleTypeOfArity(arity, minLength, hasRestElement, readonly, associatedNames));
45772             }
45773             return type;
45774         }
45775         function createTupleType(elementTypes, minLength, hasRestElement, readonly, associatedNames) {
45776             if (minLength === void 0) { minLength = elementTypes.length; }
45777             if (hasRestElement === void 0) { hasRestElement = false; }
45778             if (readonly === void 0) { readonly = false; }
45779             var arity = elementTypes.length;
45780             if (arity === 1 && hasRestElement) {
45781                 return createArrayType(elementTypes[0], readonly);
45782             }
45783             var tupleType = getTupleTypeOfArity(arity, minLength, arity > 0 && hasRestElement, readonly, associatedNames);
45784             return elementTypes.length ? createTypeReference(tupleType, elementTypes) : tupleType;
45785         }
45786         function sliceTupleType(type, index) {
45787             var tuple = type.target;
45788             if (tuple.hasRestElement) {
45789                 // don't slice off rest element
45790                 index = Math.min(index, getTypeReferenceArity(type) - 1);
45791             }
45792             return createTupleType(getTypeArguments(type).slice(index), Math.max(0, tuple.minLength - index), tuple.hasRestElement, tuple.readonly, tuple.associatedNames && tuple.associatedNames.slice(index));
45793         }
45794         function getTypeFromOptionalTypeNode(node) {
45795             var type = getTypeFromTypeNode(node.type);
45796             return strictNullChecks ? getOptionalType(type) : type;
45797         }
45798         function getTypeId(type) {
45799             return type.id;
45800         }
45801         function containsType(types, type) {
45802             return ts.binarySearch(types, type, getTypeId, ts.compareValues) >= 0;
45803         }
45804         function insertType(types, type) {
45805             var index = ts.binarySearch(types, type, getTypeId, ts.compareValues);
45806             if (index < 0) {
45807                 types.splice(~index, 0, type);
45808                 return true;
45809             }
45810             return false;
45811         }
45812         function addTypeToUnion(typeSet, includes, type) {
45813             var flags = type.flags;
45814             if (flags & 1048576 /* Union */) {
45815                 return addTypesToUnion(typeSet, includes, type.types);
45816             }
45817             // We ignore 'never' types in unions
45818             if (!(flags & 131072 /* Never */)) {
45819                 includes |= flags & 71041023 /* IncludesMask */;
45820                 if (flags & 66846720 /* StructuredOrInstantiable */)
45821                     includes |= 262144 /* IncludesStructuredOrInstantiable */;
45822                 if (type === wildcardType)
45823                     includes |= 8388608 /* IncludesWildcard */;
45824                 if (!strictNullChecks && flags & 98304 /* Nullable */) {
45825                     if (!(ts.getObjectFlags(type) & 524288 /* ContainsWideningType */))
45826                         includes |= 4194304 /* IncludesNonWideningType */;
45827                 }
45828                 else {
45829                     var len = typeSet.length;
45830                     var index = len && type.id > typeSet[len - 1].id ? ~len : ts.binarySearch(typeSet, type, getTypeId, ts.compareValues);
45831                     if (index < 0) {
45832                         typeSet.splice(~index, 0, type);
45833                     }
45834                 }
45835             }
45836             return includes;
45837         }
45838         // Add the given types to the given type set. Order is preserved, duplicates are removed,
45839         // and nested types of the given kind are flattened into the set.
45840         function addTypesToUnion(typeSet, includes, types) {
45841             for (var _i = 0, types_9 = types; _i < types_9.length; _i++) {
45842                 var type = types_9[_i];
45843                 includes = addTypeToUnion(typeSet, includes, type);
45844             }
45845             return includes;
45846         }
45847         function isSetOfLiteralsFromSameEnum(types) {
45848             var first = types[0];
45849             if (first.flags & 1024 /* EnumLiteral */) {
45850                 var firstEnum = getParentOfSymbol(first.symbol);
45851                 for (var i = 1; i < types.length; i++) {
45852                     var other = types[i];
45853                     if (!(other.flags & 1024 /* EnumLiteral */) || (firstEnum !== getParentOfSymbol(other.symbol))) {
45854                         return false;
45855                     }
45856                 }
45857                 return true;
45858             }
45859             return false;
45860         }
45861         function removeSubtypes(types, primitivesOnly) {
45862             var len = types.length;
45863             if (len === 0 || isSetOfLiteralsFromSameEnum(types)) {
45864                 return true;
45865             }
45866             var i = len;
45867             var count = 0;
45868             while (i > 0) {
45869                 i--;
45870                 var source = types[i];
45871                 for (var _i = 0, types_10 = types; _i < types_10.length; _i++) {
45872                     var target = types_10[_i];
45873                     if (source !== target) {
45874                         if (count === 100000) {
45875                             // After 100000 subtype checks we estimate the remaining amount of work by assuming the
45876                             // same ratio of checks per element. If the estimated number of remaining type checks is
45877                             // greater than an upper limit we deem the union type too complex to represent. The
45878                             // upper limit is 25M for unions of primitives only, and 1M otherwise. This for example
45879                             // caps union types at 5000 unique literal types and 1000 unique object types.
45880                             var estimatedCount = (count / (len - i)) * len;
45881                             if (estimatedCount > (primitivesOnly ? 25000000 : 1000000)) {
45882                                 error(currentNode, ts.Diagnostics.Expression_produces_a_union_type_that_is_too_complex_to_represent);
45883                                 return false;
45884                             }
45885                         }
45886                         count++;
45887                         if (isTypeRelatedTo(source, target, strictSubtypeRelation) && (!(ts.getObjectFlags(getTargetType(source)) & 1 /* Class */) ||
45888                             !(ts.getObjectFlags(getTargetType(target)) & 1 /* Class */) ||
45889                             isTypeDerivedFrom(source, target))) {
45890                             ts.orderedRemoveItemAt(types, i);
45891                             break;
45892                         }
45893                     }
45894                 }
45895             }
45896             return true;
45897         }
45898         function removeRedundantLiteralTypes(types, includes) {
45899             var i = types.length;
45900             while (i > 0) {
45901                 i--;
45902                 var t = types[i];
45903                 var remove = t.flags & 128 /* StringLiteral */ && includes & 4 /* String */ ||
45904                     t.flags & 256 /* NumberLiteral */ && includes & 8 /* Number */ ||
45905                     t.flags & 2048 /* BigIntLiteral */ && includes & 64 /* BigInt */ ||
45906                     t.flags & 8192 /* UniqueESSymbol */ && includes & 4096 /* ESSymbol */ ||
45907                     isFreshLiteralType(t) && containsType(types, t.regularType);
45908                 if (remove) {
45909                     ts.orderedRemoveItemAt(types, i);
45910                 }
45911             }
45912         }
45913         // We sort and deduplicate the constituent types based on object identity. If the subtypeReduction
45914         // flag is specified we also reduce the constituent type set to only include types that aren't subtypes
45915         // of other types. Subtype reduction is expensive for large union types and is possible only when union
45916         // types are known not to circularly reference themselves (as is the case with union types created by
45917         // expression constructs such as array literals and the || and ?: operators). Named types can
45918         // circularly reference themselves and therefore cannot be subtype reduced during their declaration.
45919         // For example, "type Item = string | (() => Item" is a named type that circularly references itself.
45920         function getUnionType(types, unionReduction, aliasSymbol, aliasTypeArguments) {
45921             if (unionReduction === void 0) { unionReduction = 1 /* Literal */; }
45922             if (types.length === 0) {
45923                 return neverType;
45924             }
45925             if (types.length === 1) {
45926                 return types[0];
45927             }
45928             var typeSet = [];
45929             var includes = addTypesToUnion(typeSet, 0, types);
45930             if (unionReduction !== 0 /* None */) {
45931                 if (includes & 3 /* AnyOrUnknown */) {
45932                     return includes & 1 /* Any */ ? includes & 8388608 /* IncludesWildcard */ ? wildcardType : anyType : unknownType;
45933                 }
45934                 switch (unionReduction) {
45935                     case 1 /* Literal */:
45936                         if (includes & (2944 /* Literal */ | 8192 /* UniqueESSymbol */)) {
45937                             removeRedundantLiteralTypes(typeSet, includes);
45938                         }
45939                         break;
45940                     case 2 /* Subtype */:
45941                         if (!removeSubtypes(typeSet, !(includes & 262144 /* IncludesStructuredOrInstantiable */))) {
45942                             return errorType;
45943                         }
45944                         break;
45945                 }
45946                 if (typeSet.length === 0) {
45947                     return includes & 65536 /* Null */ ? includes & 4194304 /* IncludesNonWideningType */ ? nullType : nullWideningType :
45948                         includes & 32768 /* Undefined */ ? includes & 4194304 /* IncludesNonWideningType */ ? undefinedType : undefinedWideningType :
45949                             neverType;
45950                 }
45951             }
45952             var objectFlags = (includes & 66994211 /* NotPrimitiveUnion */ ? 0 : 262144 /* PrimitiveUnion */) |
45953                 (includes & 2097152 /* Intersection */ ? 268435456 /* ContainsIntersections */ : 0);
45954             return getUnionTypeFromSortedList(typeSet, objectFlags, aliasSymbol, aliasTypeArguments);
45955         }
45956         function getUnionTypePredicate(signatures) {
45957             var first;
45958             var types = [];
45959             for (var _i = 0, signatures_6 = signatures; _i < signatures_6.length; _i++) {
45960                 var sig = signatures_6[_i];
45961                 var pred = getTypePredicateOfSignature(sig);
45962                 if (!pred || pred.kind === 2 /* AssertsThis */ || pred.kind === 3 /* AssertsIdentifier */) {
45963                     continue;
45964                 }
45965                 if (first) {
45966                     if (!typePredicateKindsMatch(first, pred)) {
45967                         // No common type predicate.
45968                         return undefined;
45969                     }
45970                 }
45971                 else {
45972                     first = pred;
45973                 }
45974                 types.push(pred.type);
45975             }
45976             if (!first) {
45977                 // No union signatures had a type predicate.
45978                 return undefined;
45979             }
45980             var unionType = getUnionType(types);
45981             return createTypePredicate(first.kind, first.parameterName, first.parameterIndex, unionType);
45982         }
45983         function typePredicateKindsMatch(a, b) {
45984             return a.kind === b.kind && a.parameterIndex === b.parameterIndex;
45985         }
45986         // This function assumes the constituent type list is sorted and deduplicated.
45987         function getUnionTypeFromSortedList(types, objectFlags, aliasSymbol, aliasTypeArguments) {
45988             if (types.length === 0) {
45989                 return neverType;
45990             }
45991             if (types.length === 1) {
45992                 return types[0];
45993             }
45994             var id = getTypeListId(types);
45995             var type = unionTypes.get(id);
45996             if (!type) {
45997                 type = createType(1048576 /* Union */);
45998                 unionTypes.set(id, type);
45999                 type.objectFlags = objectFlags | getPropagatingFlagsOfTypes(types, /*excludeKinds*/ 98304 /* Nullable */);
46000                 type.types = types;
46001                 /*
46002                 Note: This is the alias symbol (or lack thereof) that we see when we first encounter this union type.
46003                 For aliases of identical unions, eg `type T = A | B; type U = A | B`, the symbol of the first alias encountered is the aliasSymbol.
46004                 (In the language service, the order may depend on the order in which a user takes actions, such as hovering over symbols.)
46005                 It's important that we create equivalent union types only once, so that's an unfortunate side effect.
46006                 */
46007                 type.aliasSymbol = aliasSymbol;
46008                 type.aliasTypeArguments = aliasTypeArguments;
46009             }
46010             return type;
46011         }
46012         function getTypeFromUnionTypeNode(node) {
46013             var links = getNodeLinks(node);
46014             if (!links.resolvedType) {
46015                 var aliasSymbol = getAliasSymbolForTypeNode(node);
46016                 links.resolvedType = getUnionType(ts.map(node.types, getTypeFromTypeNode), 1 /* Literal */, aliasSymbol, getTypeArgumentsForAliasSymbol(aliasSymbol));
46017             }
46018             return links.resolvedType;
46019         }
46020         function addTypeToIntersection(typeSet, includes, type) {
46021             var flags = type.flags;
46022             if (flags & 2097152 /* Intersection */) {
46023                 return addTypesToIntersection(typeSet, includes, type.types);
46024             }
46025             if (isEmptyAnonymousObjectType(type)) {
46026                 if (!(includes & 16777216 /* IncludesEmptyObject */)) {
46027                     includes |= 16777216 /* IncludesEmptyObject */;
46028                     typeSet.set(type.id.toString(), type);
46029                 }
46030             }
46031             else {
46032                 if (flags & 3 /* AnyOrUnknown */) {
46033                     if (type === wildcardType)
46034                         includes |= 8388608 /* IncludesWildcard */;
46035                 }
46036                 else if ((strictNullChecks || !(flags & 98304 /* Nullable */)) && !typeSet.has(type.id.toString())) {
46037                     if (type.flags & 109440 /* Unit */ && includes & 109440 /* Unit */) {
46038                         // We have seen two distinct unit types which means we should reduce to an
46039                         // empty intersection. Adding TypeFlags.NonPrimitive causes that to happen.
46040                         includes |= 67108864 /* NonPrimitive */;
46041                     }
46042                     typeSet.set(type.id.toString(), type);
46043                 }
46044                 includes |= flags & 71041023 /* IncludesMask */;
46045             }
46046             return includes;
46047         }
46048         // Add the given types to the given type set. Order is preserved, freshness is removed from literal
46049         // types, duplicates are removed, and nested types of the given kind are flattened into the set.
46050         function addTypesToIntersection(typeSet, includes, types) {
46051             for (var _i = 0, types_11 = types; _i < types_11.length; _i++) {
46052                 var type = types_11[_i];
46053                 includes = addTypeToIntersection(typeSet, includes, getRegularTypeOfLiteralType(type));
46054             }
46055             return includes;
46056         }
46057         function removeRedundantPrimitiveTypes(types, includes) {
46058             var i = types.length;
46059             while (i > 0) {
46060                 i--;
46061                 var t = types[i];
46062                 var remove = t.flags & 4 /* String */ && includes & 128 /* StringLiteral */ ||
46063                     t.flags & 8 /* Number */ && includes & 256 /* NumberLiteral */ ||
46064                     t.flags & 64 /* BigInt */ && includes & 2048 /* BigIntLiteral */ ||
46065                     t.flags & 4096 /* ESSymbol */ && includes & 8192 /* UniqueESSymbol */;
46066                 if (remove) {
46067                     ts.orderedRemoveItemAt(types, i);
46068                 }
46069             }
46070         }
46071         // Check that the given type has a match in every union. A given type is matched by
46072         // an identical type, and a literal type is additionally matched by its corresponding
46073         // primitive type.
46074         function eachUnionContains(unionTypes, type) {
46075             for (var _i = 0, unionTypes_1 = unionTypes; _i < unionTypes_1.length; _i++) {
46076                 var u = unionTypes_1[_i];
46077                 if (!containsType(u.types, type)) {
46078                     var primitive = type.flags & 128 /* StringLiteral */ ? stringType :
46079                         type.flags & 256 /* NumberLiteral */ ? numberType :
46080                             type.flags & 2048 /* BigIntLiteral */ ? bigintType :
46081                                 type.flags & 8192 /* UniqueESSymbol */ ? esSymbolType :
46082                                     undefined;
46083                     if (!primitive || !containsType(u.types, primitive)) {
46084                         return false;
46085                     }
46086                 }
46087             }
46088             return true;
46089         }
46090         function extractIrreducible(types, flag) {
46091             if (ts.every(types, function (t) { return !!(t.flags & 1048576 /* Union */) && ts.some(t.types, function (tt) { return !!(tt.flags & flag); }); })) {
46092                 for (var i = 0; i < types.length; i++) {
46093                     types[i] = filterType(types[i], function (t) { return !(t.flags & flag); });
46094                 }
46095                 return true;
46096             }
46097             return false;
46098         }
46099         // If the given list of types contains more than one union of primitive types, replace the
46100         // first with a union containing an intersection of those primitive types, then remove the
46101         // other unions and return true. Otherwise, do nothing and return false.
46102         function intersectUnionsOfPrimitiveTypes(types) {
46103             var unionTypes;
46104             var index = ts.findIndex(types, function (t) { return !!(ts.getObjectFlags(t) & 262144 /* PrimitiveUnion */); });
46105             if (index < 0) {
46106                 return false;
46107             }
46108             var i = index + 1;
46109             // Remove all but the first union of primitive types and collect them in
46110             // the unionTypes array.
46111             while (i < types.length) {
46112                 var t = types[i];
46113                 if (ts.getObjectFlags(t) & 262144 /* PrimitiveUnion */) {
46114                     (unionTypes || (unionTypes = [types[index]])).push(t);
46115                     ts.orderedRemoveItemAt(types, i);
46116                 }
46117                 else {
46118                     i++;
46119                 }
46120             }
46121             // Return false if there was only one union of primitive types
46122             if (!unionTypes) {
46123                 return false;
46124             }
46125             // We have more than one union of primitive types, now intersect them. For each
46126             // type in each union we check if the type is matched in every union and if so
46127             // we include it in the result.
46128             var checked = [];
46129             var result = [];
46130             for (var _i = 0, unionTypes_2 = unionTypes; _i < unionTypes_2.length; _i++) {
46131                 var u = unionTypes_2[_i];
46132                 for (var _a = 0, _b = u.types; _a < _b.length; _a++) {
46133                     var t = _b[_a];
46134                     if (insertType(checked, t)) {
46135                         if (eachUnionContains(unionTypes, t)) {
46136                             insertType(result, t);
46137                         }
46138                     }
46139                 }
46140             }
46141             // Finally replace the first union with the result
46142             types[index] = getUnionTypeFromSortedList(result, 262144 /* PrimitiveUnion */);
46143             return true;
46144         }
46145         function createIntersectionType(types, aliasSymbol, aliasTypeArguments) {
46146             var result = createType(2097152 /* Intersection */);
46147             result.objectFlags = getPropagatingFlagsOfTypes(types, /*excludeKinds*/ 98304 /* Nullable */);
46148             result.types = types;
46149             result.aliasSymbol = aliasSymbol; // See comment in `getUnionTypeFromSortedList`.
46150             result.aliasTypeArguments = aliasTypeArguments;
46151             return result;
46152         }
46153         // We normalize combinations of intersection and union types based on the distributive property of the '&'
46154         // operator. Specifically, because X & (A | B) is equivalent to X & A | X & B, we can transform intersection
46155         // types with union type constituents into equivalent union types with intersection type constituents and
46156         // effectively ensure that union types are always at the top level in type representations.
46157         //
46158         // We do not perform structural deduplication on intersection types. Intersection types are created only by the &
46159         // type operator and we can't reduce those because we want to support recursive intersection types. For example,
46160         // a type alias of the form "type List<T> = T & { next: List<T> }" cannot be reduced during its declaration.
46161         // Also, unlike union types, the order of the constituent types is preserved in order that overload resolution
46162         // for intersections of types with signatures can be deterministic.
46163         function getIntersectionType(types, aliasSymbol, aliasTypeArguments) {
46164             var typeMembershipMap = ts.createMap();
46165             var includes = addTypesToIntersection(typeMembershipMap, 0, types);
46166             var typeSet = ts.arrayFrom(typeMembershipMap.values());
46167             // An intersection type is considered empty if it contains
46168             // the type never, or
46169             // more than one unit type or,
46170             // an object type and a nullable type (null or undefined), or
46171             // a string-like type and a type known to be non-string-like, or
46172             // a number-like type and a type known to be non-number-like, or
46173             // a symbol-like type and a type known to be non-symbol-like, or
46174             // a void-like type and a type known to be non-void-like, or
46175             // a non-primitive type and a type known to be primitive.
46176             if (includes & 131072 /* Never */ ||
46177                 strictNullChecks && includes & 98304 /* Nullable */ && includes & (524288 /* Object */ | 67108864 /* NonPrimitive */ | 16777216 /* IncludesEmptyObject */) ||
46178                 includes & 67108864 /* NonPrimitive */ && includes & (67238908 /* DisjointDomains */ & ~67108864 /* NonPrimitive */) ||
46179                 includes & 132 /* StringLike */ && includes & (67238908 /* DisjointDomains */ & ~132 /* StringLike */) ||
46180                 includes & 296 /* NumberLike */ && includes & (67238908 /* DisjointDomains */ & ~296 /* NumberLike */) ||
46181                 includes & 2112 /* BigIntLike */ && includes & (67238908 /* DisjointDomains */ & ~2112 /* BigIntLike */) ||
46182                 includes & 12288 /* ESSymbolLike */ && includes & (67238908 /* DisjointDomains */ & ~12288 /* ESSymbolLike */) ||
46183                 includes & 49152 /* VoidLike */ && includes & (67238908 /* DisjointDomains */ & ~49152 /* VoidLike */)) {
46184                 return neverType;
46185             }
46186             if (includes & 1 /* Any */) {
46187                 return includes & 8388608 /* IncludesWildcard */ ? wildcardType : anyType;
46188             }
46189             if (!strictNullChecks && includes & 98304 /* Nullable */) {
46190                 return includes & 32768 /* Undefined */ ? undefinedType : nullType;
46191             }
46192             if (includes & 4 /* String */ && includes & 128 /* StringLiteral */ ||
46193                 includes & 8 /* Number */ && includes & 256 /* NumberLiteral */ ||
46194                 includes & 64 /* BigInt */ && includes & 2048 /* BigIntLiteral */ ||
46195                 includes & 4096 /* ESSymbol */ && includes & 8192 /* UniqueESSymbol */) {
46196                 removeRedundantPrimitiveTypes(typeSet, includes);
46197             }
46198             if (includes & 16777216 /* IncludesEmptyObject */ && includes & 524288 /* Object */) {
46199                 ts.orderedRemoveItemAt(typeSet, ts.findIndex(typeSet, isEmptyAnonymousObjectType));
46200             }
46201             if (typeSet.length === 0) {
46202                 return unknownType;
46203             }
46204             if (typeSet.length === 1) {
46205                 return typeSet[0];
46206             }
46207             var id = getTypeListId(typeSet);
46208             var result = intersectionTypes.get(id);
46209             if (!result) {
46210                 if (includes & 1048576 /* Union */) {
46211                     if (intersectUnionsOfPrimitiveTypes(typeSet)) {
46212                         // When the intersection creates a reduced set (which might mean that *all* union types have
46213                         // disappeared), we restart the operation to get a new set of combined flags. Once we have
46214                         // reduced we'll never reduce again, so this occurs at most once.
46215                         result = getIntersectionType(typeSet, aliasSymbol, aliasTypeArguments);
46216                     }
46217                     else if (extractIrreducible(typeSet, 32768 /* Undefined */)) {
46218                         result = getUnionType([getIntersectionType(typeSet), undefinedType], 1 /* Literal */, aliasSymbol, aliasTypeArguments);
46219                     }
46220                     else if (extractIrreducible(typeSet, 65536 /* Null */)) {
46221                         result = getUnionType([getIntersectionType(typeSet), nullType], 1 /* Literal */, aliasSymbol, aliasTypeArguments);
46222                     }
46223                     else {
46224                         // We are attempting to construct a type of the form X & (A | B) & Y. Transform this into a type of
46225                         // the form X & A & Y | X & B & Y and recursively reduce until no union type constituents remain.
46226                         // If the estimated size of the resulting union type exceeds 100000 constituents, report an error.
46227                         var size = ts.reduceLeft(typeSet, function (n, t) { return n * (t.flags & 1048576 /* Union */ ? t.types.length : 1); }, 1);
46228                         if (size >= 100000) {
46229                             error(currentNode, ts.Diagnostics.Expression_produces_a_union_type_that_is_too_complex_to_represent);
46230                             return errorType;
46231                         }
46232                         var unionIndex_1 = ts.findIndex(typeSet, function (t) { return (t.flags & 1048576 /* Union */) !== 0; });
46233                         var unionType = typeSet[unionIndex_1];
46234                         result = getUnionType(ts.map(unionType.types, function (t) { return getIntersectionType(ts.replaceElement(typeSet, unionIndex_1, t)); }), 1 /* Literal */, aliasSymbol, aliasTypeArguments);
46235                     }
46236                 }
46237                 else {
46238                     result = createIntersectionType(typeSet, aliasSymbol, aliasTypeArguments);
46239                 }
46240                 intersectionTypes.set(id, result);
46241             }
46242             return result;
46243         }
46244         function getTypeFromIntersectionTypeNode(node) {
46245             var links = getNodeLinks(node);
46246             if (!links.resolvedType) {
46247                 var aliasSymbol = getAliasSymbolForTypeNode(node);
46248                 links.resolvedType = getIntersectionType(ts.map(node.types, getTypeFromTypeNode), aliasSymbol, getTypeArgumentsForAliasSymbol(aliasSymbol));
46249             }
46250             return links.resolvedType;
46251         }
46252         function createIndexType(type, stringsOnly) {
46253             var result = createType(4194304 /* Index */);
46254             result.type = type;
46255             result.stringsOnly = stringsOnly;
46256             return result;
46257         }
46258         function getIndexTypeForGenericType(type, stringsOnly) {
46259             return stringsOnly ?
46260                 type.resolvedStringIndexType || (type.resolvedStringIndexType = createIndexType(type, /*stringsOnly*/ true)) :
46261                 type.resolvedIndexType || (type.resolvedIndexType = createIndexType(type, /*stringsOnly*/ false));
46262         }
46263         function getLiteralTypeFromPropertyName(name) {
46264             if (ts.isPrivateIdentifier(name)) {
46265                 return neverType;
46266             }
46267             return ts.isIdentifier(name) ? getLiteralType(ts.unescapeLeadingUnderscores(name.escapedText)) :
46268                 getRegularTypeOfLiteralType(ts.isComputedPropertyName(name) ? checkComputedPropertyName(name) : checkExpression(name));
46269         }
46270         function getBigIntLiteralType(node) {
46271             return getLiteralType({
46272                 negative: false,
46273                 base10Value: ts.parsePseudoBigInt(node.text)
46274             });
46275         }
46276         function getLiteralTypeFromProperty(prop, include) {
46277             if (!(ts.getDeclarationModifierFlagsFromSymbol(prop) & 24 /* NonPublicAccessibilityModifier */)) {
46278                 var type = getSymbolLinks(getLateBoundSymbol(prop)).nameType;
46279                 if (!type && !ts.isKnownSymbol(prop)) {
46280                     if (prop.escapedName === "default" /* Default */) {
46281                         type = getLiteralType("default");
46282                     }
46283                     else {
46284                         var name = prop.valueDeclaration && ts.getNameOfDeclaration(prop.valueDeclaration);
46285                         type = name && getLiteralTypeFromPropertyName(name) || getLiteralType(ts.symbolName(prop));
46286                     }
46287                 }
46288                 if (type && type.flags & include) {
46289                     return type;
46290                 }
46291             }
46292             return neverType;
46293         }
46294         function getLiteralTypeFromProperties(type, include) {
46295             return getUnionType(ts.map(getPropertiesOfType(type), function (p) { return getLiteralTypeFromProperty(p, include); }));
46296         }
46297         function getNonEnumNumberIndexInfo(type) {
46298             var numberIndexInfo = getIndexInfoOfType(type, 1 /* Number */);
46299             return numberIndexInfo !== enumNumberIndexInfo ? numberIndexInfo : undefined;
46300         }
46301         function getIndexType(type, stringsOnly, noIndexSignatures) {
46302             if (stringsOnly === void 0) { stringsOnly = keyofStringsOnly; }
46303             type = getReducedType(type);
46304             return type.flags & 1048576 /* Union */ ? getIntersectionType(ts.map(type.types, function (t) { return getIndexType(t, stringsOnly, noIndexSignatures); })) :
46305                 type.flags & 2097152 /* Intersection */ ? getUnionType(ts.map(type.types, function (t) { return getIndexType(t, stringsOnly, noIndexSignatures); })) :
46306                     maybeTypeOfKind(type, 58982400 /* InstantiableNonPrimitive */) ? getIndexTypeForGenericType(type, stringsOnly) :
46307                         ts.getObjectFlags(type) & 32 /* Mapped */ ? filterType(getConstraintTypeFromMappedType(type), function (t) { return !(noIndexSignatures && t.flags & (1 /* Any */ | 4 /* String */)); }) :
46308                             type === wildcardType ? wildcardType :
46309                                 type.flags & 2 /* Unknown */ ? neverType :
46310                                     type.flags & (1 /* Any */ | 131072 /* Never */) ? keyofConstraintType :
46311                                         stringsOnly ? !noIndexSignatures && getIndexInfoOfType(type, 0 /* String */) ? stringType : getLiteralTypeFromProperties(type, 128 /* StringLiteral */) :
46312                                             !noIndexSignatures && getIndexInfoOfType(type, 0 /* String */) ? getUnionType([stringType, numberType, getLiteralTypeFromProperties(type, 8192 /* UniqueESSymbol */)]) :
46313                                                 getNonEnumNumberIndexInfo(type) ? getUnionType([numberType, getLiteralTypeFromProperties(type, 128 /* StringLiteral */ | 8192 /* UniqueESSymbol */)]) :
46314                                                     getLiteralTypeFromProperties(type, 8576 /* StringOrNumberLiteralOrUnique */);
46315         }
46316         function getExtractStringType(type) {
46317             if (keyofStringsOnly) {
46318                 return type;
46319             }
46320             var extractTypeAlias = getGlobalExtractSymbol();
46321             return extractTypeAlias ? getTypeAliasInstantiation(extractTypeAlias, [type, stringType]) : stringType;
46322         }
46323         function getIndexTypeOrString(type) {
46324             var indexType = getExtractStringType(getIndexType(type));
46325             return indexType.flags & 131072 /* Never */ ? stringType : indexType;
46326         }
46327         function getTypeFromTypeOperatorNode(node) {
46328             var links = getNodeLinks(node);
46329             if (!links.resolvedType) {
46330                 switch (node.operator) {
46331                     case 134 /* KeyOfKeyword */:
46332                         links.resolvedType = getIndexType(getTypeFromTypeNode(node.type));
46333                         break;
46334                     case 147 /* UniqueKeyword */:
46335                         links.resolvedType = node.type.kind === 144 /* SymbolKeyword */
46336                             ? getESSymbolLikeTypeForNode(ts.walkUpParenthesizedTypes(node.parent))
46337                             : errorType;
46338                         break;
46339                     case 138 /* ReadonlyKeyword */:
46340                         links.resolvedType = getTypeFromTypeNode(node.type);
46341                         break;
46342                     default:
46343                         throw ts.Debug.assertNever(node.operator);
46344                 }
46345             }
46346             return links.resolvedType;
46347         }
46348         function createIndexedAccessType(objectType, indexType, aliasSymbol, aliasTypeArguments) {
46349             var type = createType(8388608 /* IndexedAccess */);
46350             type.objectType = objectType;
46351             type.indexType = indexType;
46352             type.aliasSymbol = aliasSymbol;
46353             type.aliasTypeArguments = aliasTypeArguments;
46354             return type;
46355         }
46356         /**
46357          * Returns if a type is or consists of a JSLiteral object type
46358          * In addition to objects which are directly literals,
46359          * * unions where every element is a jsliteral
46360          * * intersections where at least one element is a jsliteral
46361          * * and instantiable types constrained to a jsliteral
46362          * Should all count as literals and not print errors on access or assignment of possibly existing properties.
46363          * This mirrors the behavior of the index signature propagation, to which this behaves similarly (but doesn't affect assignability or inference).
46364          */
46365         function isJSLiteralType(type) {
46366             if (noImplicitAny) {
46367                 return false; // Flag is meaningless under `noImplicitAny` mode
46368             }
46369             if (ts.getObjectFlags(type) & 16384 /* JSLiteral */) {
46370                 return true;
46371             }
46372             if (type.flags & 1048576 /* Union */) {
46373                 return ts.every(type.types, isJSLiteralType);
46374             }
46375             if (type.flags & 2097152 /* Intersection */) {
46376                 return ts.some(type.types, isJSLiteralType);
46377             }
46378             if (type.flags & 63176704 /* Instantiable */) {
46379                 return isJSLiteralType(getResolvedBaseConstraint(type));
46380             }
46381             return false;
46382         }
46383         function getPropertyNameFromIndex(indexType, accessNode) {
46384             var accessExpression = accessNode && accessNode.kind === 195 /* ElementAccessExpression */ ? accessNode : undefined;
46385             return isTypeUsableAsPropertyName(indexType) ?
46386                 getPropertyNameFromType(indexType) :
46387                 accessExpression && checkThatExpressionIsProperSymbolReference(accessExpression.argumentExpression, indexType, /*reportError*/ false) ?
46388                     ts.getPropertyNameForKnownSymbolName(ts.idText(accessExpression.argumentExpression.name)) :
46389                     accessNode && ts.isPropertyName(accessNode) ?
46390                         // late bound names are handled in the first branch, so here we only need to handle normal names
46391                         ts.getPropertyNameForPropertyNameNode(accessNode) :
46392                         undefined;
46393         }
46394         function getPropertyTypeForIndexType(originalObjectType, objectType, indexType, fullIndexType, suppressNoImplicitAnyError, accessNode, accessFlags) {
46395             var accessExpression = accessNode && accessNode.kind === 195 /* ElementAccessExpression */ ? accessNode : undefined;
46396             var propName = accessNode && ts.isPrivateIdentifier(accessNode) ? undefined : getPropertyNameFromIndex(indexType, accessNode);
46397             if (propName !== undefined) {
46398                 var prop = getPropertyOfType(objectType, propName);
46399                 if (prop) {
46400                     if (accessExpression) {
46401                         markPropertyAsReferenced(prop, accessExpression, /*isThisAccess*/ accessExpression.expression.kind === 104 /* ThisKeyword */);
46402                         if (isAssignmentToReadonlyEntity(accessExpression, prop, ts.getAssignmentTargetKind(accessExpression))) {
46403                             error(accessExpression.argumentExpression, ts.Diagnostics.Cannot_assign_to_0_because_it_is_a_read_only_property, symbolToString(prop));
46404                             return undefined;
46405                         }
46406                         if (accessFlags & 4 /* CacheSymbol */) {
46407                             getNodeLinks(accessNode).resolvedSymbol = prop;
46408                         }
46409                     }
46410                     var propType = getTypeOfSymbol(prop);
46411                     return accessExpression && ts.getAssignmentTargetKind(accessExpression) !== 1 /* Definite */ ?
46412                         getFlowTypeOfReference(accessExpression, propType) :
46413                         propType;
46414                 }
46415                 if (everyType(objectType, isTupleType) && isNumericLiteralName(propName) && +propName >= 0) {
46416                     if (accessNode && everyType(objectType, function (t) { return !t.target.hasRestElement; }) && !(accessFlags & 8 /* NoTupleBoundsCheck */)) {
46417                         var indexNode = getIndexNodeForAccessExpression(accessNode);
46418                         if (isTupleType(objectType)) {
46419                             error(indexNode, ts.Diagnostics.Tuple_type_0_of_length_1_has_no_element_at_index_2, typeToString(objectType), getTypeReferenceArity(objectType), ts.unescapeLeadingUnderscores(propName));
46420                         }
46421                         else {
46422                             error(indexNode, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.unescapeLeadingUnderscores(propName), typeToString(objectType));
46423                         }
46424                     }
46425                     errorIfWritingToReadonlyIndex(getIndexInfoOfType(objectType, 1 /* Number */));
46426                     return mapType(objectType, function (t) { return getRestTypeOfTupleType(t) || undefinedType; });
46427                 }
46428             }
46429             if (!(indexType.flags & 98304 /* Nullable */) && isTypeAssignableToKind(indexType, 132 /* StringLike */ | 296 /* NumberLike */ | 12288 /* ESSymbolLike */)) {
46430                 if (objectType.flags & (1 /* Any */ | 131072 /* Never */)) {
46431                     return objectType;
46432                 }
46433                 var stringIndexInfo = getIndexInfoOfType(objectType, 0 /* String */);
46434                 var indexInfo = isTypeAssignableToKind(indexType, 296 /* NumberLike */) && getIndexInfoOfType(objectType, 1 /* Number */) || stringIndexInfo;
46435                 if (indexInfo) {
46436                     if (accessFlags & 1 /* NoIndexSignatures */ && indexInfo === stringIndexInfo) {
46437                         if (accessExpression) {
46438                             error(accessExpression, ts.Diagnostics.Type_0_cannot_be_used_to_index_type_1, typeToString(indexType), typeToString(originalObjectType));
46439                         }
46440                         return undefined;
46441                     }
46442                     if (accessNode && !isTypeAssignableToKind(indexType, 4 /* String */ | 8 /* Number */)) {
46443                         var indexNode = getIndexNodeForAccessExpression(accessNode);
46444                         error(indexNode, ts.Diagnostics.Type_0_cannot_be_used_as_an_index_type, typeToString(indexType));
46445                         return indexInfo.type;
46446                     }
46447                     errorIfWritingToReadonlyIndex(indexInfo);
46448                     return indexInfo.type;
46449                 }
46450                 if (indexType.flags & 131072 /* Never */) {
46451                     return neverType;
46452                 }
46453                 if (isJSLiteralType(objectType)) {
46454                     return anyType;
46455                 }
46456                 if (accessExpression && !isConstEnumObjectType(objectType)) {
46457                     if (objectType.symbol === globalThisSymbol && propName !== undefined && globalThisSymbol.exports.has(propName) && (globalThisSymbol.exports.get(propName).flags & 418 /* BlockScoped */)) {
46458                         error(accessExpression, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.unescapeLeadingUnderscores(propName), typeToString(objectType));
46459                     }
46460                     else if (noImplicitAny && !compilerOptions.suppressImplicitAnyIndexErrors && !suppressNoImplicitAnyError) {
46461                         if (propName !== undefined && typeHasStaticProperty(propName, objectType)) {
46462                             error(accessExpression, ts.Diagnostics.Property_0_is_a_static_member_of_type_1, propName, typeToString(objectType));
46463                         }
46464                         else if (getIndexTypeOfType(objectType, 1 /* Number */)) {
46465                             error(accessExpression.argumentExpression, ts.Diagnostics.Element_implicitly_has_an_any_type_because_index_expression_is_not_of_type_number);
46466                         }
46467                         else {
46468                             var suggestion = void 0;
46469                             if (propName !== undefined && (suggestion = getSuggestionForNonexistentProperty(propName, objectType))) {
46470                                 if (suggestion !== undefined) {
46471                                     error(accessExpression.argumentExpression, ts.Diagnostics.Property_0_does_not_exist_on_type_1_Did_you_mean_2, propName, typeToString(objectType), suggestion);
46472                                 }
46473                             }
46474                             else {
46475                                 var suggestion_1 = getSuggestionForNonexistentIndexSignature(objectType, accessExpression, indexType);
46476                                 if (suggestion_1 !== undefined) {
46477                                     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);
46478                                 }
46479                                 else {
46480                                     var errorInfo = void 0;
46481                                     if (indexType.flags & 1024 /* EnumLiteral */) {
46482                                         errorInfo = ts.chainDiagnosticMessages(/* details */ undefined, ts.Diagnostics.Property_0_does_not_exist_on_type_1, "[" + typeToString(indexType) + "]", typeToString(objectType));
46483                                     }
46484                                     else if (indexType.flags & 8192 /* UniqueESSymbol */) {
46485                                         var symbolName_2 = getFullyQualifiedName(indexType.symbol, accessExpression);
46486                                         errorInfo = ts.chainDiagnosticMessages(/* details */ undefined, ts.Diagnostics.Property_0_does_not_exist_on_type_1, "[" + symbolName_2 + "]", typeToString(objectType));
46487                                     }
46488                                     else if (indexType.flags & 128 /* StringLiteral */) {
46489                                         errorInfo = ts.chainDiagnosticMessages(/* details */ undefined, ts.Diagnostics.Property_0_does_not_exist_on_type_1, indexType.value, typeToString(objectType));
46490                                     }
46491                                     else if (indexType.flags & 256 /* NumberLiteral */) {
46492                                         errorInfo = ts.chainDiagnosticMessages(/* details */ undefined, ts.Diagnostics.Property_0_does_not_exist_on_type_1, indexType.value, typeToString(objectType));
46493                                     }
46494                                     else if (indexType.flags & (8 /* Number */ | 4 /* String */)) {
46495                                         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));
46496                                     }
46497                                     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));
46498                                     diagnostics.add(ts.createDiagnosticForNodeFromMessageChain(accessExpression, errorInfo));
46499                                 }
46500                             }
46501                         }
46502                     }
46503                     return undefined;
46504                 }
46505             }
46506             if (isJSLiteralType(objectType)) {
46507                 return anyType;
46508             }
46509             if (accessNode) {
46510                 var indexNode = getIndexNodeForAccessExpression(accessNode);
46511                 if (indexType.flags & (128 /* StringLiteral */ | 256 /* NumberLiteral */)) {
46512                     error(indexNode, ts.Diagnostics.Property_0_does_not_exist_on_type_1, "" + indexType.value, typeToString(objectType));
46513                 }
46514                 else if (indexType.flags & (4 /* String */ | 8 /* Number */)) {
46515                     error(indexNode, ts.Diagnostics.Type_0_has_no_matching_index_signature_for_type_1, typeToString(objectType), typeToString(indexType));
46516                 }
46517                 else {
46518                     error(indexNode, ts.Diagnostics.Type_0_cannot_be_used_as_an_index_type, typeToString(indexType));
46519                 }
46520             }
46521             if (isTypeAny(indexType)) {
46522                 return indexType;
46523             }
46524             return undefined;
46525             function errorIfWritingToReadonlyIndex(indexInfo) {
46526                 if (indexInfo && indexInfo.isReadonly && accessExpression && (ts.isAssignmentTarget(accessExpression) || ts.isDeleteTarget(accessExpression))) {
46527                     error(accessExpression, ts.Diagnostics.Index_signature_in_type_0_only_permits_reading, typeToString(objectType));
46528                 }
46529             }
46530         }
46531         function getIndexNodeForAccessExpression(accessNode) {
46532             return accessNode.kind === 195 /* ElementAccessExpression */ ? accessNode.argumentExpression :
46533                 accessNode.kind === 185 /* IndexedAccessType */ ? accessNode.indexType :
46534                     accessNode.kind === 154 /* ComputedPropertyName */ ? accessNode.expression :
46535                         accessNode;
46536         }
46537         function isGenericObjectType(type) {
46538             if (type.flags & 3145728 /* UnionOrIntersection */) {
46539                 if (!(type.objectFlags & 4194304 /* IsGenericObjectTypeComputed */)) {
46540                     type.objectFlags |= 4194304 /* IsGenericObjectTypeComputed */ |
46541                         (ts.some(type.types, isGenericObjectType) ? 8388608 /* IsGenericObjectType */ : 0);
46542                 }
46543                 return !!(type.objectFlags & 8388608 /* IsGenericObjectType */);
46544             }
46545             return !!(type.flags & 58982400 /* InstantiableNonPrimitive */) || isGenericMappedType(type);
46546         }
46547         function isGenericIndexType(type) {
46548             if (type.flags & 3145728 /* UnionOrIntersection */) {
46549                 if (!(type.objectFlags & 16777216 /* IsGenericIndexTypeComputed */)) {
46550                     type.objectFlags |= 16777216 /* IsGenericIndexTypeComputed */ |
46551                         (ts.some(type.types, isGenericIndexType) ? 33554432 /* IsGenericIndexType */ : 0);
46552                 }
46553                 return !!(type.objectFlags & 33554432 /* IsGenericIndexType */);
46554             }
46555             return !!(type.flags & (58982400 /* InstantiableNonPrimitive */ | 4194304 /* Index */));
46556         }
46557         function isThisTypeParameter(type) {
46558             return !!(type.flags & 262144 /* TypeParameter */ && type.isThisType);
46559         }
46560         function getSimplifiedType(type, writing) {
46561             return type.flags & 8388608 /* IndexedAccess */ ? getSimplifiedIndexedAccessType(type, writing) :
46562                 type.flags & 16777216 /* Conditional */ ? getSimplifiedConditionalType(type, writing) :
46563                     type;
46564         }
46565         function distributeIndexOverObjectType(objectType, indexType, writing) {
46566             // (T | U)[K] -> T[K] | U[K] (reading)
46567             // (T | U)[K] -> T[K] & U[K] (writing)
46568             // (T & U)[K] -> T[K] & U[K]
46569             if (objectType.flags & 3145728 /* UnionOrIntersection */) {
46570                 var types = ts.map(objectType.types, function (t) { return getSimplifiedType(getIndexedAccessType(t, indexType), writing); });
46571                 return objectType.flags & 2097152 /* Intersection */ || writing ? getIntersectionType(types) : getUnionType(types);
46572             }
46573         }
46574         function distributeObjectOverIndexType(objectType, indexType, writing) {
46575             // T[A | B] -> T[A] | T[B] (reading)
46576             // T[A | B] -> T[A] & T[B] (writing)
46577             if (indexType.flags & 1048576 /* Union */) {
46578                 var types = ts.map(indexType.types, function (t) { return getSimplifiedType(getIndexedAccessType(objectType, t), writing); });
46579                 return writing ? getIntersectionType(types) : getUnionType(types);
46580             }
46581         }
46582         function unwrapSubstitution(type) {
46583             if (type.flags & 33554432 /* Substitution */) {
46584                 return type.substitute;
46585             }
46586             return type;
46587         }
46588         // Transform an indexed access to a simpler form, if possible. Return the simpler form, or return
46589         // the type itself if no transformation is possible. The writing flag indicates that the type is
46590         // the target of an assignment.
46591         function getSimplifiedIndexedAccessType(type, writing) {
46592             var cache = writing ? "simplifiedForWriting" : "simplifiedForReading";
46593             if (type[cache]) {
46594                 return type[cache] === circularConstraintType ? type : type[cache];
46595             }
46596             type[cache] = circularConstraintType;
46597             // We recursively simplify the object type as it may in turn be an indexed access type. For example, with
46598             // '{ [P in T]: { [Q in U]: number } }[T][U]' we want to first simplify the inner indexed access type.
46599             var objectType = unwrapSubstitution(getSimplifiedType(type.objectType, writing));
46600             var indexType = getSimplifiedType(type.indexType, writing);
46601             // T[A | B] -> T[A] | T[B] (reading)
46602             // T[A | B] -> T[A] & T[B] (writing)
46603             var distributedOverIndex = distributeObjectOverIndexType(objectType, indexType, writing);
46604             if (distributedOverIndex) {
46605                 return type[cache] = distributedOverIndex;
46606             }
46607             // Only do the inner distributions if the index can no longer be instantiated to cause index distribution again
46608             if (!(indexType.flags & 63176704 /* Instantiable */)) {
46609                 // (T | U)[K] -> T[K] | U[K] (reading)
46610                 // (T | U)[K] -> T[K] & U[K] (writing)
46611                 // (T & U)[K] -> T[K] & U[K]
46612                 var distributedOverObject = distributeIndexOverObjectType(objectType, indexType, writing);
46613                 if (distributedOverObject) {
46614                     return type[cache] = distributedOverObject;
46615                 }
46616             }
46617             // So ultimately (reading):
46618             // ((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]
46619             // If the object type is a mapped type { [P in K]: E }, where K is generic, instantiate E using a mapper
46620             // that substitutes the index type for P. For example, for an index access { [P in K]: Box<T[P]> }[X], we
46621             // construct the type Box<T[X]>.
46622             if (isGenericMappedType(objectType)) {
46623                 return type[cache] = mapType(substituteIndexedMappedType(objectType, type.indexType), function (t) { return getSimplifiedType(t, writing); });
46624             }
46625             return type[cache] = type;
46626         }
46627         function getSimplifiedConditionalType(type, writing) {
46628             var checkType = type.checkType;
46629             var extendsType = type.extendsType;
46630             var trueType = getTrueTypeFromConditionalType(type);
46631             var falseType = getFalseTypeFromConditionalType(type);
46632             // Simplifications for types of the form `T extends U ? T : never` and `T extends U ? never : T`.
46633             if (falseType.flags & 131072 /* Never */ && getActualTypeVariable(trueType) === getActualTypeVariable(checkType)) {
46634                 if (checkType.flags & 1 /* Any */ || isTypeAssignableTo(getRestrictiveInstantiation(checkType), getRestrictiveInstantiation(extendsType))) { // Always true
46635                     return getSimplifiedType(trueType, writing);
46636                 }
46637                 else if (isIntersectionEmpty(checkType, extendsType)) { // Always false
46638                     return neverType;
46639                 }
46640             }
46641             else if (trueType.flags & 131072 /* Never */ && getActualTypeVariable(falseType) === getActualTypeVariable(checkType)) {
46642                 if (!(checkType.flags & 1 /* Any */) && isTypeAssignableTo(getRestrictiveInstantiation(checkType), getRestrictiveInstantiation(extendsType))) { // Always true
46643                     return neverType;
46644                 }
46645                 else if (checkType.flags & 1 /* Any */ || isIntersectionEmpty(checkType, extendsType)) { // Always false
46646                     return getSimplifiedType(falseType, writing);
46647                 }
46648             }
46649             return type;
46650         }
46651         /**
46652          * Invokes union simplification logic to determine if an intersection is considered empty as a union constituent
46653          */
46654         function isIntersectionEmpty(type1, type2) {
46655             return !!(getUnionType([intersectTypes(type1, type2), neverType]).flags & 131072 /* Never */);
46656         }
46657         function substituteIndexedMappedType(objectType, index) {
46658             var mapper = createTypeMapper([getTypeParameterFromMappedType(objectType)], [index]);
46659             var templateMapper = combineTypeMappers(objectType.mapper, mapper);
46660             return instantiateType(getTemplateTypeFromMappedType(objectType), templateMapper);
46661         }
46662         function getIndexedAccessType(objectType, indexType, accessNode, aliasSymbol, aliasTypeArguments) {
46663             return getIndexedAccessTypeOrUndefined(objectType, indexType, accessNode, 0 /* None */, aliasSymbol, aliasTypeArguments) || (accessNode ? errorType : unknownType);
46664         }
46665         function getIndexedAccessTypeOrUndefined(objectType, indexType, accessNode, accessFlags, aliasSymbol, aliasTypeArguments) {
46666             if (accessFlags === void 0) { accessFlags = 0 /* None */; }
46667             if (objectType === wildcardType || indexType === wildcardType) {
46668                 return wildcardType;
46669             }
46670             // If the object type has a string index signature and no other members we know that the result will
46671             // always be the type of that index signature and we can simplify accordingly.
46672             if (isStringIndexSignatureOnlyType(objectType) && !(indexType.flags & 98304 /* Nullable */) && isTypeAssignableToKind(indexType, 4 /* String */ | 8 /* Number */)) {
46673                 indexType = stringType;
46674             }
46675             // If the index type is generic, or if the object type is generic and doesn't originate in an expression,
46676             // we are performing a higher-order index access where we cannot meaningfully access the properties of the
46677             // object type. Note that for a generic T and a non-generic K, we eagerly resolve T[K] if it originates in
46678             // an expression. This is to preserve backwards compatibility. For example, an element access 'this["foo"]'
46679             // has always been resolved eagerly using the constraint type of 'this' at the given location.
46680             if (isGenericIndexType(indexType) || !(accessNode && accessNode.kind !== 185 /* IndexedAccessType */) && isGenericObjectType(objectType)) {
46681                 if (objectType.flags & 3 /* AnyOrUnknown */) {
46682                     return objectType;
46683                 }
46684                 // Defer the operation by creating an indexed access type.
46685                 var id = objectType.id + "," + indexType.id;
46686                 var type = indexedAccessTypes.get(id);
46687                 if (!type) {
46688                     indexedAccessTypes.set(id, type = createIndexedAccessType(objectType, indexType, aliasSymbol, aliasTypeArguments));
46689                 }
46690                 return type;
46691             }
46692             // In the following we resolve T[K] to the type of the property in T selected by K.
46693             // We treat boolean as different from other unions to improve errors;
46694             // skipping straight to getPropertyTypeForIndexType gives errors with 'boolean' instead of 'true'.
46695             var apparentObjectType = getReducedApparentType(objectType);
46696             if (indexType.flags & 1048576 /* Union */ && !(indexType.flags & 16 /* Boolean */)) {
46697                 var propTypes = [];
46698                 var wasMissingProp = false;
46699                 for (var _i = 0, _a = indexType.types; _i < _a.length; _i++) {
46700                     var t = _a[_i];
46701                     var propType = getPropertyTypeForIndexType(objectType, apparentObjectType, t, indexType, wasMissingProp, accessNode, accessFlags);
46702                     if (propType) {
46703                         propTypes.push(propType);
46704                     }
46705                     else if (!accessNode) {
46706                         // If there's no error node, we can immeditely stop, since error reporting is off
46707                         return undefined;
46708                     }
46709                     else {
46710                         // Otherwise we set a flag and return at the end of the loop so we still mark all errors
46711                         wasMissingProp = true;
46712                     }
46713                 }
46714                 if (wasMissingProp) {
46715                     return undefined;
46716                 }
46717                 return accessFlags & 2 /* Writing */ ? getIntersectionType(propTypes, aliasSymbol, aliasTypeArguments) : getUnionType(propTypes, 1 /* Literal */, aliasSymbol, aliasTypeArguments);
46718             }
46719             return getPropertyTypeForIndexType(objectType, apparentObjectType, indexType, indexType, /* supressNoImplicitAnyError */ false, accessNode, accessFlags | 4 /* CacheSymbol */);
46720         }
46721         function getTypeFromIndexedAccessTypeNode(node) {
46722             var links = getNodeLinks(node);
46723             if (!links.resolvedType) {
46724                 var objectType = getTypeFromTypeNode(node.objectType);
46725                 var indexType = getTypeFromTypeNode(node.indexType);
46726                 var potentialAlias = getAliasSymbolForTypeNode(node);
46727                 var resolved = getIndexedAccessType(objectType, indexType, node, potentialAlias, getTypeArgumentsForAliasSymbol(potentialAlias));
46728                 links.resolvedType = resolved.flags & 8388608 /* IndexedAccess */ &&
46729                     resolved.objectType === objectType &&
46730                     resolved.indexType === indexType ?
46731                     getConditionalFlowTypeOfType(resolved, node) : resolved;
46732             }
46733             return links.resolvedType;
46734         }
46735         function getTypeFromMappedTypeNode(node) {
46736             var links = getNodeLinks(node);
46737             if (!links.resolvedType) {
46738                 var type = createObjectType(32 /* Mapped */, node.symbol);
46739                 type.declaration = node;
46740                 type.aliasSymbol = getAliasSymbolForTypeNode(node);
46741                 type.aliasTypeArguments = getTypeArgumentsForAliasSymbol(type.aliasSymbol);
46742                 links.resolvedType = type;
46743                 // Eagerly resolve the constraint type which forces an error if the constraint type circularly
46744                 // references itself through one or more type aliases.
46745                 getConstraintTypeFromMappedType(type);
46746             }
46747             return links.resolvedType;
46748         }
46749         function getActualTypeVariable(type) {
46750             if (type.flags & 33554432 /* Substitution */) {
46751                 return type.baseType;
46752             }
46753             if (type.flags & 8388608 /* IndexedAccess */ && (type.objectType.flags & 33554432 /* Substitution */ ||
46754                 type.indexType.flags & 33554432 /* Substitution */)) {
46755                 return getIndexedAccessType(getActualTypeVariable(type.objectType), getActualTypeVariable(type.indexType));
46756             }
46757             return type;
46758         }
46759         function getConditionalType(root, mapper) {
46760             var result;
46761             var extraTypes;
46762             var _loop_12 = function () {
46763                 var checkType = instantiateType(root.checkType, mapper);
46764                 var checkTypeInstantiable = isGenericObjectType(checkType) || isGenericIndexType(checkType);
46765                 var extendsType = instantiateType(root.extendsType, mapper);
46766                 if (checkType === wildcardType || extendsType === wildcardType) {
46767                     return { value: wildcardType };
46768                 }
46769                 var combinedMapper = void 0;
46770                 if (root.inferTypeParameters) {
46771                     var context = createInferenceContext(root.inferTypeParameters, /*signature*/ undefined, 0 /* None */);
46772                     // We skip inference of the possible `infer` types unles the `extendsType` _is_ an infer type
46773                     // if it was, it's trivial to say that extendsType = checkType, however such a pattern is used to
46774                     // "reset" the type being build up during constraint calculation and avoid making an apparently "infinite" constraint
46775                     // so in those cases we refain from performing inference and retain the uninfered type parameter
46776                     if (!checkTypeInstantiable || !ts.some(root.inferTypeParameters, function (t) { return t === extendsType; })) {
46777                         // We don't want inferences from constraints as they may cause us to eagerly resolve the
46778                         // conditional type instead of deferring resolution. Also, we always want strict function
46779                         // types rules (i.e. proper contravariance) for inferences.
46780                         inferTypes(context.inferences, checkType, extendsType, 128 /* NoConstraints */ | 256 /* AlwaysStrict */);
46781                     }
46782                     combinedMapper = mergeTypeMappers(mapper, context.mapper);
46783                 }
46784                 // Instantiate the extends type including inferences for 'infer T' type parameters
46785                 var inferredExtendsType = combinedMapper ? instantiateType(root.extendsType, combinedMapper) : extendsType;
46786                 // We attempt to resolve the conditional type only when the check and extends types are non-generic
46787                 if (!checkTypeInstantiable && !isGenericObjectType(inferredExtendsType) && !isGenericIndexType(inferredExtendsType)) {
46788                     // Return falseType for a definitely false extends check. We check an instantiations of the two
46789                     // types with type parameters mapped to the wildcard type, the most permissive instantiations
46790                     // possible (the wildcard type is assignable to and from all types). If those are not related,
46791                     // then no instantiations will be and we can just return the false branch type.
46792                     if (!(inferredExtendsType.flags & 3 /* AnyOrUnknown */) && (checkType.flags & 1 /* Any */ || !isTypeAssignableTo(getPermissiveInstantiation(checkType), getPermissiveInstantiation(inferredExtendsType)))) {
46793                         // Return union of trueType and falseType for 'any' since it matches anything
46794                         if (checkType.flags & 1 /* Any */) {
46795                             (extraTypes || (extraTypes = [])).push(instantiateTypeWithoutDepthIncrease(root.trueType, combinedMapper || mapper));
46796                         }
46797                         // If falseType is an immediately nested conditional type that isn't distributive or has an
46798                         // identical checkType, switch to that type and loop.
46799                         var falseType_1 = root.falseType;
46800                         if (falseType_1.flags & 16777216 /* Conditional */) {
46801                             var newRoot = falseType_1.root;
46802                             if (newRoot.node.parent === root.node && (!newRoot.isDistributive || newRoot.checkType === root.checkType)) {
46803                                 root = newRoot;
46804                                 return "continue";
46805                             }
46806                         }
46807                         result = instantiateTypeWithoutDepthIncrease(falseType_1, mapper);
46808                         return "break";
46809                     }
46810                     // Return trueType for a definitely true extends check. We check instantiations of the two
46811                     // types with type parameters mapped to their restrictive form, i.e. a form of the type parameter
46812                     // that has no constraint. This ensures that, for example, the type
46813                     //   type Foo<T extends { x: any }> = T extends { x: string } ? string : number
46814                     // doesn't immediately resolve to 'string' instead of being deferred.
46815                     if (inferredExtendsType.flags & 3 /* AnyOrUnknown */ || isTypeAssignableTo(getRestrictiveInstantiation(checkType), getRestrictiveInstantiation(inferredExtendsType))) {
46816                         result = instantiateTypeWithoutDepthIncrease(root.trueType, combinedMapper || mapper);
46817                         return "break";
46818                     }
46819                 }
46820                 // Return a deferred type for a check that is neither definitely true nor definitely false
46821                 var erasedCheckType = getActualTypeVariable(checkType);
46822                 result = createType(16777216 /* Conditional */);
46823                 result.root = root;
46824                 result.checkType = erasedCheckType;
46825                 result.extendsType = extendsType;
46826                 result.mapper = mapper;
46827                 result.combinedMapper = combinedMapper;
46828                 result.aliasSymbol = root.aliasSymbol;
46829                 result.aliasTypeArguments = instantiateTypes(root.aliasTypeArguments, mapper); // TODO: GH#18217
46830                 return "break";
46831             };
46832             // We loop here for an immediately nested conditional type in the false position, effectively treating
46833             // types of the form 'A extends B ? X : C extends D ? Y : E extends F ? Z : ...' as a single construct for
46834             // purposes of resolution. This means such types aren't subject to the instatiation depth limiter.
46835             while (true) {
46836                 var state_4 = _loop_12();
46837                 if (typeof state_4 === "object")
46838                     return state_4.value;
46839                 if (state_4 === "break")
46840                     break;
46841             }
46842             return extraTypes ? getUnionType(ts.append(extraTypes, result)) : result;
46843         }
46844         function getTrueTypeFromConditionalType(type) {
46845             return type.resolvedTrueType || (type.resolvedTrueType = instantiateType(type.root.trueType, type.mapper));
46846         }
46847         function getFalseTypeFromConditionalType(type) {
46848             return type.resolvedFalseType || (type.resolvedFalseType = instantiateType(type.root.falseType, type.mapper));
46849         }
46850         function getInferredTrueTypeFromConditionalType(type) {
46851             return type.resolvedInferredTrueType || (type.resolvedInferredTrueType = type.combinedMapper ? instantiateType(type.root.trueType, type.combinedMapper) : getTrueTypeFromConditionalType(type));
46852         }
46853         function getInferTypeParameters(node) {
46854             var result;
46855             if (node.locals) {
46856                 node.locals.forEach(function (symbol) {
46857                     if (symbol.flags & 262144 /* TypeParameter */) {
46858                         result = ts.append(result, getDeclaredTypeOfSymbol(symbol));
46859                     }
46860                 });
46861             }
46862             return result;
46863         }
46864         function getTypeFromConditionalTypeNode(node) {
46865             var links = getNodeLinks(node);
46866             if (!links.resolvedType) {
46867                 var checkType = getTypeFromTypeNode(node.checkType);
46868                 var aliasSymbol = getAliasSymbolForTypeNode(node);
46869                 var aliasTypeArguments = getTypeArgumentsForAliasSymbol(aliasSymbol);
46870                 var allOuterTypeParameters = getOuterTypeParameters(node, /*includeThisTypes*/ true);
46871                 var outerTypeParameters = aliasTypeArguments ? allOuterTypeParameters : ts.filter(allOuterTypeParameters, function (tp) { return isTypeParameterPossiblyReferenced(tp, node); });
46872                 var root = {
46873                     node: node,
46874                     checkType: checkType,
46875                     extendsType: getTypeFromTypeNode(node.extendsType),
46876                     trueType: getTypeFromTypeNode(node.trueType),
46877                     falseType: getTypeFromTypeNode(node.falseType),
46878                     isDistributive: !!(checkType.flags & 262144 /* TypeParameter */),
46879                     inferTypeParameters: getInferTypeParameters(node),
46880                     outerTypeParameters: outerTypeParameters,
46881                     instantiations: undefined,
46882                     aliasSymbol: aliasSymbol,
46883                     aliasTypeArguments: aliasTypeArguments
46884                 };
46885                 links.resolvedType = getConditionalType(root, /*mapper*/ undefined);
46886                 if (outerTypeParameters) {
46887                     root.instantiations = ts.createMap();
46888                     root.instantiations.set(getTypeListId(outerTypeParameters), links.resolvedType);
46889                 }
46890             }
46891             return links.resolvedType;
46892         }
46893         function getTypeFromInferTypeNode(node) {
46894             var links = getNodeLinks(node);
46895             if (!links.resolvedType) {
46896                 links.resolvedType = getDeclaredTypeOfTypeParameter(getSymbolOfNode(node.typeParameter));
46897             }
46898             return links.resolvedType;
46899         }
46900         function getIdentifierChain(node) {
46901             if (ts.isIdentifier(node)) {
46902                 return [node];
46903             }
46904             else {
46905                 return ts.append(getIdentifierChain(node.left), node.right);
46906             }
46907         }
46908         function getTypeFromImportTypeNode(node) {
46909             var links = getNodeLinks(node);
46910             if (!links.resolvedType) {
46911                 if (node.isTypeOf && node.typeArguments) { // Only the non-typeof form can make use of type arguments
46912                     error(node, ts.Diagnostics.Type_arguments_cannot_be_used_here);
46913                     links.resolvedSymbol = unknownSymbol;
46914                     return links.resolvedType = errorType;
46915                 }
46916                 if (!ts.isLiteralImportTypeNode(node)) {
46917                     error(node.argument, ts.Diagnostics.String_literal_expected);
46918                     links.resolvedSymbol = unknownSymbol;
46919                     return links.resolvedType = errorType;
46920                 }
46921                 var targetMeaning = node.isTypeOf ? 111551 /* Value */ : node.flags & 4194304 /* JSDoc */ ? 111551 /* Value */ | 788968 /* Type */ : 788968 /* Type */;
46922                 // TODO: Future work: support unions/generics/whatever via a deferred import-type
46923                 var innerModuleSymbol = resolveExternalModuleName(node, node.argument.literal);
46924                 if (!innerModuleSymbol) {
46925                     links.resolvedSymbol = unknownSymbol;
46926                     return links.resolvedType = errorType;
46927                 }
46928                 var moduleSymbol = resolveExternalModuleSymbol(innerModuleSymbol, /*dontResolveAlias*/ false);
46929                 if (!ts.nodeIsMissing(node.qualifier)) {
46930                     var nameStack = getIdentifierChain(node.qualifier);
46931                     var currentNamespace = moduleSymbol;
46932                     var current = void 0;
46933                     while (current = nameStack.shift()) {
46934                         var meaning = nameStack.length ? 1920 /* Namespace */ : targetMeaning;
46935                         var next = getSymbol(getExportsOfSymbol(getMergedSymbol(resolveSymbol(currentNamespace))), current.escapedText, meaning);
46936                         if (!next) {
46937                             error(current, ts.Diagnostics.Namespace_0_has_no_exported_member_1, getFullyQualifiedName(currentNamespace), ts.declarationNameToString(current));
46938                             return links.resolvedType = errorType;
46939                         }
46940                         getNodeLinks(current).resolvedSymbol = next;
46941                         getNodeLinks(current.parent).resolvedSymbol = next;
46942                         currentNamespace = next;
46943                     }
46944                     links.resolvedType = resolveImportSymbolType(node, links, currentNamespace, targetMeaning);
46945                 }
46946                 else {
46947                     if (moduleSymbol.flags & targetMeaning) {
46948                         links.resolvedType = resolveImportSymbolType(node, links, moduleSymbol, targetMeaning);
46949                     }
46950                     else {
46951                         var errorMessage = targetMeaning === 111551 /* Value */
46952                             ? ts.Diagnostics.Module_0_does_not_refer_to_a_value_but_is_used_as_a_value_here
46953                             : ts.Diagnostics.Module_0_does_not_refer_to_a_type_but_is_used_as_a_type_here_Did_you_mean_typeof_import_0;
46954                         error(node, errorMessage, node.argument.literal.text);
46955                         links.resolvedSymbol = unknownSymbol;
46956                         links.resolvedType = errorType;
46957                     }
46958                 }
46959             }
46960             return links.resolvedType;
46961         }
46962         function resolveImportSymbolType(node, links, symbol, meaning) {
46963             var resolvedSymbol = resolveSymbol(symbol);
46964             links.resolvedSymbol = resolvedSymbol;
46965             if (meaning === 111551 /* Value */) {
46966                 return getTypeOfSymbol(symbol); // intentionally doesn't use resolved symbol so type is cached as expected on the alias
46967             }
46968             else {
46969                 return getTypeReferenceType(node, resolvedSymbol); // getTypeReferenceType doesn't handle aliases - it must get the resolved symbol
46970             }
46971         }
46972         function getTypeFromTypeLiteralOrFunctionOrConstructorTypeNode(node) {
46973             var links = getNodeLinks(node);
46974             if (!links.resolvedType) {
46975                 // Deferred resolution of members is handled by resolveObjectTypeMembers
46976                 var aliasSymbol = getAliasSymbolForTypeNode(node);
46977                 if (getMembersOfSymbol(node.symbol).size === 0 && !aliasSymbol) {
46978                     links.resolvedType = emptyTypeLiteralType;
46979                 }
46980                 else {
46981                     var type = createObjectType(16 /* Anonymous */, node.symbol);
46982                     type.aliasSymbol = aliasSymbol;
46983                     type.aliasTypeArguments = getTypeArgumentsForAliasSymbol(aliasSymbol);
46984                     if (ts.isJSDocTypeLiteral(node) && node.isArrayType) {
46985                         type = createArrayType(type);
46986                     }
46987                     links.resolvedType = type;
46988                 }
46989             }
46990             return links.resolvedType;
46991         }
46992         function getAliasSymbolForTypeNode(node) {
46993             var host = node.parent;
46994             while (ts.isParenthesizedTypeNode(host) || ts.isTypeOperatorNode(host) && host.operator === 138 /* ReadonlyKeyword */) {
46995                 host = host.parent;
46996             }
46997             return ts.isTypeAlias(host) ? getSymbolOfNode(host) : undefined;
46998         }
46999         function getTypeArgumentsForAliasSymbol(symbol) {
47000             return symbol ? getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol) : undefined;
47001         }
47002         function isNonGenericObjectType(type) {
47003             return !!(type.flags & 524288 /* Object */) && !isGenericMappedType(type);
47004         }
47005         function isEmptyObjectTypeOrSpreadsIntoEmptyObject(type) {
47006             return isEmptyObjectType(type) || !!(type.flags & (65536 /* Null */ | 32768 /* Undefined */ | 528 /* BooleanLike */ | 296 /* NumberLike */ | 2112 /* BigIntLike */ | 132 /* StringLike */ | 1056 /* EnumLike */ | 67108864 /* NonPrimitive */ | 4194304 /* Index */));
47007         }
47008         function isSinglePropertyAnonymousObjectType(type) {
47009             return !!(type.flags & 524288 /* Object */) &&
47010                 !!(ts.getObjectFlags(type) & 16 /* Anonymous */) &&
47011                 (ts.length(getPropertiesOfType(type)) === 1 || ts.every(getPropertiesOfType(type), function (p) { return !!(p.flags & 16777216 /* Optional */); }));
47012         }
47013         function tryMergeUnionOfObjectTypeAndEmptyObject(type, readonly) {
47014             if (type.types.length === 2) {
47015                 var firstType = type.types[0];
47016                 var secondType = type.types[1];
47017                 if (ts.every(type.types, isEmptyObjectTypeOrSpreadsIntoEmptyObject)) {
47018                     return isEmptyObjectType(firstType) ? firstType : isEmptyObjectType(secondType) ? secondType : emptyObjectType;
47019                 }
47020                 if (isEmptyObjectTypeOrSpreadsIntoEmptyObject(firstType) && isSinglePropertyAnonymousObjectType(secondType)) {
47021                     return getAnonymousPartialType(secondType);
47022                 }
47023                 if (isEmptyObjectTypeOrSpreadsIntoEmptyObject(secondType) && isSinglePropertyAnonymousObjectType(firstType)) {
47024                     return getAnonymousPartialType(firstType);
47025                 }
47026             }
47027             function getAnonymousPartialType(type) {
47028                 // gets the type as if it had been spread, but where everything in the spread is made optional
47029                 var members = ts.createSymbolTable();
47030                 for (var _i = 0, _a = getPropertiesOfType(type); _i < _a.length; _i++) {
47031                     var prop = _a[_i];
47032                     if (ts.getDeclarationModifierFlagsFromSymbol(prop) & (8 /* Private */ | 16 /* Protected */)) {
47033                         // do nothing, skip privates
47034                     }
47035                     else if (isSpreadableProperty(prop)) {
47036                         var isSetonlyAccessor = prop.flags & 65536 /* SetAccessor */ && !(prop.flags & 32768 /* GetAccessor */);
47037                         var flags = 4 /* Property */ | 16777216 /* Optional */;
47038                         var result = createSymbol(flags, prop.escapedName, readonly ? 8 /* Readonly */ : 0);
47039                         result.type = isSetonlyAccessor ? undefinedType : getTypeOfSymbol(prop);
47040                         result.declarations = prop.declarations;
47041                         result.nameType = getSymbolLinks(prop).nameType;
47042                         result.syntheticOrigin = prop;
47043                         members.set(prop.escapedName, result);
47044                     }
47045                 }
47046                 var spread = createAnonymousType(type.symbol, members, ts.emptyArray, ts.emptyArray, getIndexInfoOfType(type, 0 /* String */), getIndexInfoOfType(type, 1 /* Number */));
47047                 spread.objectFlags |= 128 /* ObjectLiteral */ | 1048576 /* ContainsObjectOrArrayLiteral */;
47048                 return spread;
47049             }
47050         }
47051         /**
47052          * Since the source of spread types are object literals, which are not binary,
47053          * this function should be called in a left folding style, with left = previous result of getSpreadType
47054          * and right = the new element to be spread.
47055          */
47056         function getSpreadType(left, right, symbol, objectFlags, readonly) {
47057             if (left.flags & 1 /* Any */ || right.flags & 1 /* Any */) {
47058                 return anyType;
47059             }
47060             if (left.flags & 2 /* Unknown */ || right.flags & 2 /* Unknown */) {
47061                 return unknownType;
47062             }
47063             if (left.flags & 131072 /* Never */) {
47064                 return right;
47065             }
47066             if (right.flags & 131072 /* Never */) {
47067                 return left;
47068             }
47069             if (left.flags & 1048576 /* Union */) {
47070                 var merged = tryMergeUnionOfObjectTypeAndEmptyObject(left, readonly);
47071                 if (merged) {
47072                     return getSpreadType(merged, right, symbol, objectFlags, readonly);
47073                 }
47074                 return mapType(left, function (t) { return getSpreadType(t, right, symbol, objectFlags, readonly); });
47075             }
47076             if (right.flags & 1048576 /* Union */) {
47077                 var merged = tryMergeUnionOfObjectTypeAndEmptyObject(right, readonly);
47078                 if (merged) {
47079                     return getSpreadType(left, merged, symbol, objectFlags, readonly);
47080                 }
47081                 return mapType(right, function (t) { return getSpreadType(left, t, symbol, objectFlags, readonly); });
47082             }
47083             if (right.flags & (528 /* BooleanLike */ | 296 /* NumberLike */ | 2112 /* BigIntLike */ | 132 /* StringLike */ | 1056 /* EnumLike */ | 67108864 /* NonPrimitive */ | 4194304 /* Index */)) {
47084                 return left;
47085             }
47086             if (isGenericObjectType(left) || isGenericObjectType(right)) {
47087                 if (isEmptyObjectType(left)) {
47088                     return right;
47089                 }
47090                 // When the left type is an intersection, we may need to merge the last constituent of the
47091                 // intersection with the right type. For example when the left type is 'T & { a: string }'
47092                 // and the right type is '{ b: string }' we produce 'T & { a: string, b: string }'.
47093                 if (left.flags & 2097152 /* Intersection */) {
47094                     var types = left.types;
47095                     var lastLeft = types[types.length - 1];
47096                     if (isNonGenericObjectType(lastLeft) && isNonGenericObjectType(right)) {
47097                         return getIntersectionType(ts.concatenate(types.slice(0, types.length - 1), [getSpreadType(lastLeft, right, symbol, objectFlags, readonly)]));
47098                     }
47099                 }
47100                 return getIntersectionType([left, right]);
47101             }
47102             var members = ts.createSymbolTable();
47103             var skippedPrivateMembers = ts.createUnderscoreEscapedMap();
47104             var stringIndexInfo;
47105             var numberIndexInfo;
47106             if (left === emptyObjectType) {
47107                 // for the first spread element, left === emptyObjectType, so take the right's string indexer
47108                 stringIndexInfo = getIndexInfoOfType(right, 0 /* String */);
47109                 numberIndexInfo = getIndexInfoOfType(right, 1 /* Number */);
47110             }
47111             else {
47112                 stringIndexInfo = unionSpreadIndexInfos(getIndexInfoOfType(left, 0 /* String */), getIndexInfoOfType(right, 0 /* String */));
47113                 numberIndexInfo = unionSpreadIndexInfos(getIndexInfoOfType(left, 1 /* Number */), getIndexInfoOfType(right, 1 /* Number */));
47114             }
47115             for (var _i = 0, _a = getPropertiesOfType(right); _i < _a.length; _i++) {
47116                 var rightProp = _a[_i];
47117                 if (ts.getDeclarationModifierFlagsFromSymbol(rightProp) & (8 /* Private */ | 16 /* Protected */)) {
47118                     skippedPrivateMembers.set(rightProp.escapedName, true);
47119                 }
47120                 else if (isSpreadableProperty(rightProp)) {
47121                     members.set(rightProp.escapedName, getSpreadSymbol(rightProp, readonly));
47122                 }
47123             }
47124             for (var _b = 0, _c = getPropertiesOfType(left); _b < _c.length; _b++) {
47125                 var leftProp = _c[_b];
47126                 if (skippedPrivateMembers.has(leftProp.escapedName) || !isSpreadableProperty(leftProp)) {
47127                     continue;
47128                 }
47129                 if (members.has(leftProp.escapedName)) {
47130                     var rightProp = members.get(leftProp.escapedName);
47131                     var rightType = getTypeOfSymbol(rightProp);
47132                     if (rightProp.flags & 16777216 /* Optional */) {
47133                         var declarations = ts.concatenate(leftProp.declarations, rightProp.declarations);
47134                         var flags = 4 /* Property */ | (leftProp.flags & 16777216 /* Optional */);
47135                         var result = createSymbol(flags, leftProp.escapedName);
47136                         result.type = getUnionType([getTypeOfSymbol(leftProp), getTypeWithFacts(rightType, 524288 /* NEUndefined */)]);
47137                         result.leftSpread = leftProp;
47138                         result.rightSpread = rightProp;
47139                         result.declarations = declarations;
47140                         result.nameType = getSymbolLinks(leftProp).nameType;
47141                         members.set(leftProp.escapedName, result);
47142                     }
47143                 }
47144                 else {
47145                     members.set(leftProp.escapedName, getSpreadSymbol(leftProp, readonly));
47146                 }
47147             }
47148             var spread = createAnonymousType(symbol, members, ts.emptyArray, ts.emptyArray, getIndexInfoWithReadonly(stringIndexInfo, readonly), getIndexInfoWithReadonly(numberIndexInfo, readonly));
47149             spread.objectFlags |= 128 /* ObjectLiteral */ | 1048576 /* ContainsObjectOrArrayLiteral */ | 1024 /* ContainsSpread */ | objectFlags;
47150             return spread;
47151         }
47152         /** We approximate own properties as non-methods plus methods that are inside the object literal */
47153         function isSpreadableProperty(prop) {
47154             return !ts.some(prop.declarations, ts.isPrivateIdentifierPropertyDeclaration) &&
47155                 (!(prop.flags & (8192 /* Method */ | 32768 /* GetAccessor */ | 65536 /* SetAccessor */)) ||
47156                     !prop.declarations.some(function (decl) { return ts.isClassLike(decl.parent); }));
47157         }
47158         function getSpreadSymbol(prop, readonly) {
47159             var isSetonlyAccessor = prop.flags & 65536 /* SetAccessor */ && !(prop.flags & 32768 /* GetAccessor */);
47160             if (!isSetonlyAccessor && readonly === isReadonlySymbol(prop)) {
47161                 return prop;
47162             }
47163             var flags = 4 /* Property */ | (prop.flags & 16777216 /* Optional */);
47164             var result = createSymbol(flags, prop.escapedName, readonly ? 8 /* Readonly */ : 0);
47165             result.type = isSetonlyAccessor ? undefinedType : getTypeOfSymbol(prop);
47166             result.declarations = prop.declarations;
47167             result.nameType = getSymbolLinks(prop).nameType;
47168             result.syntheticOrigin = prop;
47169             return result;
47170         }
47171         function getIndexInfoWithReadonly(info, readonly) {
47172             return info && info.isReadonly !== readonly ? createIndexInfo(info.type, readonly, info.declaration) : info;
47173         }
47174         function createLiteralType(flags, value, symbol) {
47175             var type = createType(flags);
47176             type.symbol = symbol;
47177             type.value = value;
47178             return type;
47179         }
47180         function getFreshTypeOfLiteralType(type) {
47181             if (type.flags & 2944 /* Literal */) {
47182                 if (!type.freshType) {
47183                     var freshType = createLiteralType(type.flags, type.value, type.symbol);
47184                     freshType.regularType = type;
47185                     freshType.freshType = freshType;
47186                     type.freshType = freshType;
47187                 }
47188                 return type.freshType;
47189             }
47190             return type;
47191         }
47192         function getRegularTypeOfLiteralType(type) {
47193             return type.flags & 2944 /* Literal */ ? type.regularType :
47194                 type.flags & 1048576 /* Union */ ? (type.regularType || (type.regularType = getUnionType(ts.sameMap(type.types, getRegularTypeOfLiteralType)))) :
47195                     type;
47196         }
47197         function isFreshLiteralType(type) {
47198             return !!(type.flags & 2944 /* Literal */) && type.freshType === type;
47199         }
47200         function getLiteralType(value, enumId, symbol) {
47201             // We store all literal types in a single map with keys of the form '#NNN' and '@SSS',
47202             // where NNN is the text representation of a numeric literal and SSS are the characters
47203             // of a string literal. For literal enum members we use 'EEE#NNN' and 'EEE@SSS', where
47204             // EEE is a unique id for the containing enum type.
47205             var qualifier = typeof value === "number" ? "#" : typeof value === "string" ? "@" : "n";
47206             var key = (enumId ? enumId : "") + qualifier + (typeof value === "object" ? ts.pseudoBigIntToString(value) : value);
47207             var type = literalTypes.get(key);
47208             if (!type) {
47209                 var flags = (typeof value === "number" ? 256 /* NumberLiteral */ :
47210                     typeof value === "string" ? 128 /* StringLiteral */ : 2048 /* BigIntLiteral */) |
47211                     (enumId ? 1024 /* EnumLiteral */ : 0);
47212                 literalTypes.set(key, type = createLiteralType(flags, value, symbol));
47213                 type.regularType = type;
47214             }
47215             return type;
47216         }
47217         function getTypeFromLiteralTypeNode(node) {
47218             var links = getNodeLinks(node);
47219             if (!links.resolvedType) {
47220                 links.resolvedType = getRegularTypeOfLiteralType(checkExpression(node.literal));
47221             }
47222             return links.resolvedType;
47223         }
47224         function createUniqueESSymbolType(symbol) {
47225             var type = createType(8192 /* UniqueESSymbol */);
47226             type.symbol = symbol;
47227             type.escapedName = "__@" + type.symbol.escapedName + "@" + getSymbolId(type.symbol);
47228             return type;
47229         }
47230         function getESSymbolLikeTypeForNode(node) {
47231             if (ts.isValidESSymbolDeclaration(node)) {
47232                 var symbol = getSymbolOfNode(node);
47233                 var links = getSymbolLinks(symbol);
47234                 return links.uniqueESSymbolType || (links.uniqueESSymbolType = createUniqueESSymbolType(symbol));
47235             }
47236             return esSymbolType;
47237         }
47238         function getThisType(node) {
47239             var container = ts.getThisContainer(node, /*includeArrowFunctions*/ false);
47240             var parent = container && container.parent;
47241             if (parent && (ts.isClassLike(parent) || parent.kind === 246 /* InterfaceDeclaration */)) {
47242                 if (!ts.hasModifier(container, 32 /* Static */) &&
47243                     (!ts.isConstructorDeclaration(container) || ts.isNodeDescendantOf(node, container.body))) {
47244                     return getDeclaredTypeOfClassOrInterface(getSymbolOfNode(parent)).thisType;
47245                 }
47246             }
47247             // inside x.prototype = { ... }
47248             if (parent && ts.isObjectLiteralExpression(parent) && ts.isBinaryExpression(parent.parent) && ts.getAssignmentDeclarationKind(parent.parent) === 6 /* Prototype */) {
47249                 return getDeclaredTypeOfClassOrInterface(getSymbolOfNode(parent.parent.left).parent).thisType;
47250             }
47251             // /** @return {this} */
47252             // x.prototype.m = function() { ... }
47253             var host = node.flags & 4194304 /* JSDoc */ ? ts.getHostSignatureFromJSDoc(node) : undefined;
47254             if (host && ts.isFunctionExpression(host) && ts.isBinaryExpression(host.parent) && ts.getAssignmentDeclarationKind(host.parent) === 3 /* PrototypeProperty */) {
47255                 return getDeclaredTypeOfClassOrInterface(getSymbolOfNode(host.parent.left).parent).thisType;
47256             }
47257             // inside constructor function C() { ... }
47258             if (isJSConstructor(container) && ts.isNodeDescendantOf(node, container.body)) {
47259                 return getDeclaredTypeOfClassOrInterface(getSymbolOfNode(container)).thisType;
47260             }
47261             error(node, ts.Diagnostics.A_this_type_is_available_only_in_a_non_static_member_of_a_class_or_interface);
47262             return errorType;
47263         }
47264         function getTypeFromThisTypeNode(node) {
47265             var links = getNodeLinks(node);
47266             if (!links.resolvedType) {
47267                 links.resolvedType = getThisType(node);
47268             }
47269             return links.resolvedType;
47270         }
47271         function getTypeFromTypeNode(node) {
47272             return getConditionalFlowTypeOfType(getTypeFromTypeNodeWorker(node), node);
47273         }
47274         function getTypeFromTypeNodeWorker(node) {
47275             switch (node.kind) {
47276                 case 125 /* AnyKeyword */:
47277                 case 295 /* JSDocAllType */:
47278                 case 296 /* JSDocUnknownType */:
47279                     return anyType;
47280                 case 148 /* UnknownKeyword */:
47281                     return unknownType;
47282                 case 143 /* StringKeyword */:
47283                     return stringType;
47284                 case 140 /* NumberKeyword */:
47285                     return numberType;
47286                 case 151 /* BigIntKeyword */:
47287                     return bigintType;
47288                 case 128 /* BooleanKeyword */:
47289                     return booleanType;
47290                 case 144 /* SymbolKeyword */:
47291                     return esSymbolType;
47292                 case 110 /* VoidKeyword */:
47293                     return voidType;
47294                 case 146 /* UndefinedKeyword */:
47295                     return undefinedType;
47296                 case 100 /* NullKeyword */:
47297                     return nullType;
47298                 case 137 /* NeverKeyword */:
47299                     return neverType;
47300                 case 141 /* ObjectKeyword */:
47301                     return node.flags & 131072 /* JavaScriptFile */ && !noImplicitAny ? anyType : nonPrimitiveType;
47302                 case 183 /* ThisType */:
47303                 case 104 /* ThisKeyword */:
47304                     return getTypeFromThisTypeNode(node);
47305                 case 187 /* LiteralType */:
47306                     return getTypeFromLiteralTypeNode(node);
47307                 case 169 /* TypeReference */:
47308                     return getTypeFromTypeReference(node);
47309                 case 168 /* TypePredicate */:
47310                     return node.assertsModifier ? voidType : booleanType;
47311                 case 216 /* ExpressionWithTypeArguments */:
47312                     return getTypeFromTypeReference(node);
47313                 case 172 /* TypeQuery */:
47314                     return getTypeFromTypeQueryNode(node);
47315                 case 174 /* ArrayType */:
47316                 case 175 /* TupleType */:
47317                     return getTypeFromArrayOrTupleTypeNode(node);
47318                 case 176 /* OptionalType */:
47319                     return getTypeFromOptionalTypeNode(node);
47320                 case 178 /* UnionType */:
47321                     return getTypeFromUnionTypeNode(node);
47322                 case 179 /* IntersectionType */:
47323                     return getTypeFromIntersectionTypeNode(node);
47324                 case 297 /* JSDocNullableType */:
47325                     return getTypeFromJSDocNullableTypeNode(node);
47326                 case 299 /* JSDocOptionalType */:
47327                     return addOptionality(getTypeFromTypeNode(node.type));
47328                 case 182 /* ParenthesizedType */:
47329                 case 298 /* JSDocNonNullableType */:
47330                 case 294 /* JSDocTypeExpression */:
47331                     return getTypeFromTypeNode(node.type);
47332                 case 177 /* RestType */:
47333                     return getElementTypeOfArrayType(getTypeFromTypeNode(node.type)) || errorType;
47334                 case 301 /* JSDocVariadicType */:
47335                     return getTypeFromJSDocVariadicType(node);
47336                 case 170 /* FunctionType */:
47337                 case 171 /* ConstructorType */:
47338                 case 173 /* TypeLiteral */:
47339                 case 304 /* JSDocTypeLiteral */:
47340                 case 300 /* JSDocFunctionType */:
47341                 case 305 /* JSDocSignature */:
47342                     return getTypeFromTypeLiteralOrFunctionOrConstructorTypeNode(node);
47343                 case 184 /* TypeOperator */:
47344                     return getTypeFromTypeOperatorNode(node);
47345                 case 185 /* IndexedAccessType */:
47346                     return getTypeFromIndexedAccessTypeNode(node);
47347                 case 186 /* MappedType */:
47348                     return getTypeFromMappedTypeNode(node);
47349                 case 180 /* ConditionalType */:
47350                     return getTypeFromConditionalTypeNode(node);
47351                 case 181 /* InferType */:
47352                     return getTypeFromInferTypeNode(node);
47353                 case 188 /* ImportType */:
47354                     return getTypeFromImportTypeNode(node);
47355                 // This function assumes that an identifier or qualified name is a type expression
47356                 // Callers should first ensure this by calling isTypeNode
47357                 case 75 /* Identifier */:
47358                 case 153 /* QualifiedName */:
47359                     var symbol = getSymbolAtLocation(node);
47360                     return symbol ? getDeclaredTypeOfSymbol(symbol) : errorType;
47361                 default:
47362                     return errorType;
47363             }
47364         }
47365         function instantiateList(items, mapper, instantiator) {
47366             if (items && items.length) {
47367                 for (var i = 0; i < items.length; i++) {
47368                     var item = items[i];
47369                     var mapped = instantiator(item, mapper);
47370                     if (item !== mapped) {
47371                         var result = i === 0 ? [] : items.slice(0, i);
47372                         result.push(mapped);
47373                         for (i++; i < items.length; i++) {
47374                             result.push(instantiator(items[i], mapper));
47375                         }
47376                         return result;
47377                     }
47378                 }
47379             }
47380             return items;
47381         }
47382         function instantiateTypes(types, mapper) {
47383             return instantiateList(types, mapper, instantiateType);
47384         }
47385         function instantiateSignatures(signatures, mapper) {
47386             return instantiateList(signatures, mapper, instantiateSignature);
47387         }
47388         function createTypeMapper(sources, targets) {
47389             return sources.length === 1 ? makeUnaryTypeMapper(sources[0], targets ? targets[0] : anyType) : makeArrayTypeMapper(sources, targets);
47390         }
47391         function getMappedType(type, mapper) {
47392             switch (mapper.kind) {
47393                 case 0 /* Simple */:
47394                     return type === mapper.source ? mapper.target : type;
47395                 case 1 /* Array */:
47396                     var sources = mapper.sources;
47397                     var targets = mapper.targets;
47398                     for (var i = 0; i < sources.length; i++) {
47399                         if (type === sources[i]) {
47400                             return targets ? targets[i] : anyType;
47401                         }
47402                     }
47403                     return type;
47404                 case 2 /* Function */:
47405                     return mapper.func(type);
47406                 case 3 /* Composite */:
47407                 case 4 /* Merged */:
47408                     var t1 = getMappedType(type, mapper.mapper1);
47409                     return t1 !== type && mapper.kind === 3 /* Composite */ ? instantiateType(t1, mapper.mapper2) : getMappedType(t1, mapper.mapper2);
47410             }
47411         }
47412         function makeUnaryTypeMapper(source, target) {
47413             return { kind: 0 /* Simple */, source: source, target: target };
47414         }
47415         function makeArrayTypeMapper(sources, targets) {
47416             return { kind: 1 /* Array */, sources: sources, targets: targets };
47417         }
47418         function makeFunctionTypeMapper(func) {
47419             return { kind: 2 /* Function */, func: func };
47420         }
47421         function makeCompositeTypeMapper(kind, mapper1, mapper2) {
47422             return { kind: kind, mapper1: mapper1, mapper2: mapper2 };
47423         }
47424         function createTypeEraser(sources) {
47425             return createTypeMapper(sources, /*targets*/ undefined);
47426         }
47427         /**
47428          * Maps forward-references to later types parameters to the empty object type.
47429          * This is used during inference when instantiating type parameter defaults.
47430          */
47431         function createBackreferenceMapper(context, index) {
47432             return makeFunctionTypeMapper(function (t) { return ts.findIndex(context.inferences, function (info) { return info.typeParameter === t; }) >= index ? unknownType : t; });
47433         }
47434         function combineTypeMappers(mapper1, mapper2) {
47435             return mapper1 ? makeCompositeTypeMapper(3 /* Composite */, mapper1, mapper2) : mapper2;
47436         }
47437         function mergeTypeMappers(mapper1, mapper2) {
47438             return mapper1 ? makeCompositeTypeMapper(4 /* Merged */, mapper1, mapper2) : mapper2;
47439         }
47440         function prependTypeMapping(source, target, mapper) {
47441             return !mapper ? makeUnaryTypeMapper(source, target) : makeCompositeTypeMapper(4 /* Merged */, makeUnaryTypeMapper(source, target), mapper);
47442         }
47443         function appendTypeMapping(mapper, source, target) {
47444             return !mapper ? makeUnaryTypeMapper(source, target) : makeCompositeTypeMapper(4 /* Merged */, mapper, makeUnaryTypeMapper(source, target));
47445         }
47446         function getRestrictiveTypeParameter(tp) {
47447             return tp.constraint === unknownType ? tp : tp.restrictiveInstantiation || (tp.restrictiveInstantiation = createTypeParameter(tp.symbol),
47448                 tp.restrictiveInstantiation.constraint = unknownType,
47449                 tp.restrictiveInstantiation);
47450         }
47451         function cloneTypeParameter(typeParameter) {
47452             var result = createTypeParameter(typeParameter.symbol);
47453             result.target = typeParameter;
47454             return result;
47455         }
47456         function instantiateTypePredicate(predicate, mapper) {
47457             return createTypePredicate(predicate.kind, predicate.parameterName, predicate.parameterIndex, instantiateType(predicate.type, mapper));
47458         }
47459         function instantiateSignature(signature, mapper, eraseTypeParameters) {
47460             var freshTypeParameters;
47461             if (signature.typeParameters && !eraseTypeParameters) {
47462                 // First create a fresh set of type parameters, then include a mapping from the old to the
47463                 // new type parameters in the mapper function. Finally store this mapper in the new type
47464                 // parameters such that we can use it when instantiating constraints.
47465                 freshTypeParameters = ts.map(signature.typeParameters, cloneTypeParameter);
47466                 mapper = combineTypeMappers(createTypeMapper(signature.typeParameters, freshTypeParameters), mapper);
47467                 for (var _i = 0, freshTypeParameters_1 = freshTypeParameters; _i < freshTypeParameters_1.length; _i++) {
47468                     var tp = freshTypeParameters_1[_i];
47469                     tp.mapper = mapper;
47470                 }
47471             }
47472             // Don't compute resolvedReturnType and resolvedTypePredicate now,
47473             // because using `mapper` now could trigger inferences to become fixed. (See `createInferenceContext`.)
47474             // See GH#17600.
47475             var result = createSignature(signature.declaration, freshTypeParameters, signature.thisParameter && instantiateSymbol(signature.thisParameter, mapper), instantiateList(signature.parameters, mapper, instantiateSymbol), 
47476             /*resolvedReturnType*/ undefined, 
47477             /*resolvedTypePredicate*/ undefined, signature.minArgumentCount, signature.flags & 3 /* PropagatingFlags */);
47478             result.target = signature;
47479             result.mapper = mapper;
47480             return result;
47481         }
47482         function instantiateSymbol(symbol, mapper) {
47483             var links = getSymbolLinks(symbol);
47484             if (links.type && !couldContainTypeVariables(links.type)) {
47485                 // If the type of the symbol is already resolved, and if that type could not possibly
47486                 // be affected by instantiation, simply return the symbol itself.
47487                 return symbol;
47488             }
47489             if (ts.getCheckFlags(symbol) & 1 /* Instantiated */) {
47490                 // If symbol being instantiated is itself a instantiation, fetch the original target and combine the
47491                 // type mappers. This ensures that original type identities are properly preserved and that aliases
47492                 // always reference a non-aliases.
47493                 symbol = links.target;
47494                 mapper = combineTypeMappers(links.mapper, mapper);
47495             }
47496             // Keep the flags from the symbol we're instantiating.  Mark that is instantiated, and
47497             // also transient so that we can just store data on it directly.
47498             var result = createSymbol(symbol.flags, symbol.escapedName, 1 /* Instantiated */ | ts.getCheckFlags(symbol) & (8 /* Readonly */ | 4096 /* Late */ | 16384 /* OptionalParameter */ | 32768 /* RestParameter */));
47499             result.declarations = symbol.declarations;
47500             result.parent = symbol.parent;
47501             result.target = symbol;
47502             result.mapper = mapper;
47503             if (symbol.valueDeclaration) {
47504                 result.valueDeclaration = symbol.valueDeclaration;
47505             }
47506             if (links.nameType) {
47507                 result.nameType = links.nameType;
47508             }
47509             return result;
47510         }
47511         function getObjectTypeInstantiation(type, mapper) {
47512             var target = type.objectFlags & 64 /* Instantiated */ ? type.target : type;
47513             var node = type.objectFlags & 4 /* Reference */ ? type.node : type.symbol.declarations[0];
47514             var links = getNodeLinks(node);
47515             var typeParameters = links.outerTypeParameters;
47516             if (!typeParameters) {
47517                 // The first time an anonymous type is instantiated we compute and store a list of the type
47518                 // parameters that are in scope (and therefore potentially referenced). For type literals that
47519                 // aren't the right hand side of a generic type alias declaration we optimize by reducing the
47520                 // set of type parameters to those that are possibly referenced in the literal.
47521                 var declaration_1 = node;
47522                 if (ts.isInJSFile(declaration_1)) {
47523                     var paramTag = ts.findAncestor(declaration_1, ts.isJSDocParameterTag);
47524                     if (paramTag) {
47525                         var paramSymbol = ts.getParameterSymbolFromJSDoc(paramTag);
47526                         if (paramSymbol) {
47527                             declaration_1 = paramSymbol.valueDeclaration;
47528                         }
47529                     }
47530                 }
47531                 var outerTypeParameters = getOuterTypeParameters(declaration_1, /*includeThisTypes*/ true);
47532                 if (isJSConstructor(declaration_1)) {
47533                     var templateTagParameters = getTypeParametersFromDeclaration(declaration_1);
47534                     outerTypeParameters = ts.addRange(outerTypeParameters, templateTagParameters);
47535                 }
47536                 typeParameters = outerTypeParameters || ts.emptyArray;
47537                 typeParameters = (target.objectFlags & 4 /* Reference */ || target.symbol.flags & 2048 /* TypeLiteral */) && !target.aliasTypeArguments ?
47538                     ts.filter(typeParameters, function (tp) { return isTypeParameterPossiblyReferenced(tp, declaration_1); }) :
47539                     typeParameters;
47540                 links.outerTypeParameters = typeParameters;
47541                 if (typeParameters.length) {
47542                     links.instantiations = ts.createMap();
47543                     links.instantiations.set(getTypeListId(typeParameters), target);
47544                 }
47545             }
47546             if (typeParameters.length) {
47547                 // We are instantiating an anonymous type that has one or more type parameters in scope. Apply the
47548                 // mapper to the type parameters to produce the effective list of type arguments, and compute the
47549                 // instantiation cache key from the type IDs of the type arguments.
47550                 var combinedMapper_1 = combineTypeMappers(type.mapper, mapper);
47551                 var typeArguments = ts.map(typeParameters, function (t) { return getMappedType(t, combinedMapper_1); });
47552                 var id = getTypeListId(typeArguments);
47553                 var result = links.instantiations.get(id);
47554                 if (!result) {
47555                     var newMapper = createTypeMapper(typeParameters, typeArguments);
47556                     result = target.objectFlags & 4 /* Reference */ ? createDeferredTypeReference(type.target, type.node, newMapper) :
47557                         target.objectFlags & 32 /* Mapped */ ? instantiateMappedType(target, newMapper) :
47558                             instantiateAnonymousType(target, newMapper);
47559                     links.instantiations.set(id, result);
47560                 }
47561                 return result;
47562             }
47563             return type;
47564         }
47565         function maybeTypeParameterReference(node) {
47566             return !(node.kind === 153 /* QualifiedName */ ||
47567                 node.parent.kind === 169 /* TypeReference */ && node.parent.typeArguments && node === node.parent.typeName ||
47568                 node.parent.kind === 188 /* ImportType */ && node.parent.typeArguments && node === node.parent.qualifier);
47569         }
47570         function isTypeParameterPossiblyReferenced(tp, node) {
47571             // If the type parameter doesn't have exactly one declaration, if there are invening statement blocks
47572             // between the node and the type parameter declaration, if the node contains actual references to the
47573             // type parameter, or if the node contains type queries, we consider the type parameter possibly referenced.
47574             if (tp.symbol && tp.symbol.declarations && tp.symbol.declarations.length === 1) {
47575                 var container = tp.symbol.declarations[0].parent;
47576                 for (var n = node; n !== container; n = n.parent) {
47577                     if (!n || n.kind === 223 /* Block */ || n.kind === 180 /* ConditionalType */ && ts.forEachChild(n.extendsType, containsReference)) {
47578                         return true;
47579                     }
47580                 }
47581                 return !!ts.forEachChild(node, containsReference);
47582             }
47583             return true;
47584             function containsReference(node) {
47585                 switch (node.kind) {
47586                     case 183 /* ThisType */:
47587                         return !!tp.isThisType;
47588                     case 75 /* Identifier */:
47589                         return !tp.isThisType && ts.isPartOfTypeNode(node) && maybeTypeParameterReference(node) &&
47590                             getTypeFromTypeNodeWorker(node) === tp; // use worker because we're looking for === equality
47591                     case 172 /* TypeQuery */:
47592                         return true;
47593                 }
47594                 return !!ts.forEachChild(node, containsReference);
47595             }
47596         }
47597         function getHomomorphicTypeVariable(type) {
47598             var constraintType = getConstraintTypeFromMappedType(type);
47599             if (constraintType.flags & 4194304 /* Index */) {
47600                 var typeVariable = getActualTypeVariable(constraintType.type);
47601                 if (typeVariable.flags & 262144 /* TypeParameter */) {
47602                     return typeVariable;
47603                 }
47604             }
47605             return undefined;
47606         }
47607         function instantiateMappedType(type, mapper) {
47608             // For a homomorphic mapped type { [P in keyof T]: X }, where T is some type variable, the mapping
47609             // operation depends on T as follows:
47610             // * If T is a primitive type no mapping is performed and the result is simply T.
47611             // * If T is a union type we distribute the mapped type over the union.
47612             // * If T is an array we map to an array where the element type has been transformed.
47613             // * If T is a tuple we map to a tuple where the element types have been transformed.
47614             // * Otherwise we map to an object type where the type of each property has been transformed.
47615             // For example, when T is instantiated to a union type A | B, we produce { [P in keyof A]: X } |
47616             // { [P in keyof B]: X }, and when when T is instantiated to a union type A | undefined, we produce
47617             // { [P in keyof A]: X } | undefined.
47618             var typeVariable = getHomomorphicTypeVariable(type);
47619             if (typeVariable) {
47620                 var mappedTypeVariable = instantiateType(typeVariable, mapper);
47621                 if (typeVariable !== mappedTypeVariable) {
47622                     return mapType(getReducedType(mappedTypeVariable), function (t) {
47623                         if (t.flags & (3 /* AnyOrUnknown */ | 58982400 /* InstantiableNonPrimitive */ | 524288 /* Object */ | 2097152 /* Intersection */) && t !== wildcardType && t !== errorType) {
47624                             var replacementMapper = prependTypeMapping(typeVariable, t, mapper);
47625                             return isArrayType(t) ? instantiateMappedArrayType(t, type, replacementMapper) :
47626                                 isTupleType(t) ? instantiateMappedTupleType(t, type, replacementMapper) :
47627                                     instantiateAnonymousType(type, replacementMapper);
47628                         }
47629                         return t;
47630                     });
47631                 }
47632             }
47633             return instantiateAnonymousType(type, mapper);
47634         }
47635         function getModifiedReadonlyState(state, modifiers) {
47636             return modifiers & 1 /* IncludeReadonly */ ? true : modifiers & 2 /* ExcludeReadonly */ ? false : state;
47637         }
47638         function instantiateMappedArrayType(arrayType, mappedType, mapper) {
47639             var elementType = instantiateMappedTypeTemplate(mappedType, numberType, /*isOptional*/ true, mapper);
47640             return elementType === errorType ? errorType :
47641                 createArrayType(elementType, getModifiedReadonlyState(isReadonlyArrayType(arrayType), getMappedTypeModifiers(mappedType)));
47642         }
47643         function instantiateMappedTupleType(tupleType, mappedType, mapper) {
47644             var minLength = tupleType.target.minLength;
47645             var elementTypes = ts.map(getTypeArguments(tupleType), function (_, i) {
47646                 return instantiateMappedTypeTemplate(mappedType, getLiteralType("" + i), i >= minLength, mapper);
47647             });
47648             var modifiers = getMappedTypeModifiers(mappedType);
47649             var newMinLength = modifiers & 4 /* IncludeOptional */ ? 0 :
47650                 modifiers & 8 /* ExcludeOptional */ ? getTypeReferenceArity(tupleType) - (tupleType.target.hasRestElement ? 1 : 0) :
47651                     minLength;
47652             var newReadonly = getModifiedReadonlyState(tupleType.target.readonly, modifiers);
47653             return ts.contains(elementTypes, errorType) ? errorType :
47654                 createTupleType(elementTypes, newMinLength, tupleType.target.hasRestElement, newReadonly, tupleType.target.associatedNames);
47655         }
47656         function instantiateMappedTypeTemplate(type, key, isOptional, mapper) {
47657             var templateMapper = appendTypeMapping(mapper, getTypeParameterFromMappedType(type), key);
47658             var propType = instantiateType(getTemplateTypeFromMappedType(type.target || type), templateMapper);
47659             var modifiers = getMappedTypeModifiers(type);
47660             return strictNullChecks && modifiers & 4 /* IncludeOptional */ && !maybeTypeOfKind(propType, 32768 /* Undefined */ | 16384 /* Void */) ? getOptionalType(propType) :
47661                 strictNullChecks && modifiers & 8 /* ExcludeOptional */ && isOptional ? getTypeWithFacts(propType, 524288 /* NEUndefined */) :
47662                     propType;
47663         }
47664         function instantiateAnonymousType(type, mapper) {
47665             var result = createObjectType(type.objectFlags | 64 /* Instantiated */, type.symbol);
47666             if (type.objectFlags & 32 /* Mapped */) {
47667                 result.declaration = type.declaration;
47668                 // C.f. instantiateSignature
47669                 var origTypeParameter = getTypeParameterFromMappedType(type);
47670                 var freshTypeParameter = cloneTypeParameter(origTypeParameter);
47671                 result.typeParameter = freshTypeParameter;
47672                 mapper = combineTypeMappers(makeUnaryTypeMapper(origTypeParameter, freshTypeParameter), mapper);
47673                 freshTypeParameter.mapper = mapper;
47674             }
47675             result.target = type;
47676             result.mapper = mapper;
47677             result.aliasSymbol = type.aliasSymbol;
47678             result.aliasTypeArguments = instantiateTypes(type.aliasTypeArguments, mapper);
47679             return result;
47680         }
47681         function getConditionalTypeInstantiation(type, mapper) {
47682             var root = type.root;
47683             if (root.outerTypeParameters) {
47684                 // We are instantiating a conditional type that has one or more type parameters in scope. Apply the
47685                 // mapper to the type parameters to produce the effective list of type arguments, and compute the
47686                 // instantiation cache key from the type IDs of the type arguments.
47687                 var typeArguments = ts.map(root.outerTypeParameters, function (t) { return getMappedType(t, mapper); });
47688                 var id = getTypeListId(typeArguments);
47689                 var result = root.instantiations.get(id);
47690                 if (!result) {
47691                     var newMapper = createTypeMapper(root.outerTypeParameters, typeArguments);
47692                     result = instantiateConditionalType(root, newMapper);
47693                     root.instantiations.set(id, result);
47694                 }
47695                 return result;
47696             }
47697             return type;
47698         }
47699         function instantiateConditionalType(root, mapper) {
47700             // Check if we have a conditional type where the check type is a naked type parameter. If so,
47701             // the conditional type is distributive over union types and when T is instantiated to a union
47702             // type A | B, we produce (A extends U ? X : Y) | (B extends U ? X : Y).
47703             if (root.isDistributive) {
47704                 var checkType_1 = root.checkType;
47705                 var instantiatedType = getMappedType(checkType_1, mapper);
47706                 if (checkType_1 !== instantiatedType && instantiatedType.flags & (1048576 /* Union */ | 131072 /* Never */)) {
47707                     return mapType(instantiatedType, function (t) { return getConditionalType(root, prependTypeMapping(checkType_1, t, mapper)); });
47708                 }
47709             }
47710             return getConditionalType(root, mapper);
47711         }
47712         function instantiateType(type, mapper) {
47713             if (!type || !mapper) {
47714                 return type;
47715             }
47716             if (instantiationDepth === 50 || instantiationCount >= 5000000) {
47717                 // We have reached 50 recursive type instantiations and there is a very high likelyhood we're dealing
47718                 // with a combination of infinite generic types that perpetually generate new type identities. We stop
47719                 // the recursion here by yielding the error type.
47720                 error(currentNode, ts.Diagnostics.Type_instantiation_is_excessively_deep_and_possibly_infinite);
47721                 return errorType;
47722             }
47723             totalInstantiationCount++;
47724             instantiationCount++;
47725             instantiationDepth++;
47726             var result = instantiateTypeWorker(type, mapper);
47727             instantiationDepth--;
47728             return result;
47729         }
47730         /**
47731          * This can be used to avoid the penalty on instantiation depth for types which result from immediate
47732          * simplification. It essentially removes the depth increase done in `instantiateType`.
47733          */
47734         function instantiateTypeWithoutDepthIncrease(type, mapper) {
47735             instantiationDepth--;
47736             var result = instantiateType(type, mapper);
47737             instantiationDepth++;
47738             return result;
47739         }
47740         function instantiateTypeWorker(type, mapper) {
47741             var flags = type.flags;
47742             if (flags & 262144 /* TypeParameter */) {
47743                 return getMappedType(type, mapper);
47744             }
47745             if (flags & 524288 /* Object */) {
47746                 var objectFlags = type.objectFlags;
47747                 if (objectFlags & 16 /* Anonymous */) {
47748                     // If the anonymous type originates in a declaration of a function, method, class, or
47749                     // interface, in an object type literal, or in an object literal expression, we may need
47750                     // to instantiate the type because it might reference a type parameter.
47751                     return couldContainTypeVariables(type) ?
47752                         getObjectTypeInstantiation(type, mapper) : type;
47753                 }
47754                 if (objectFlags & 32 /* Mapped */) {
47755                     return getObjectTypeInstantiation(type, mapper);
47756                 }
47757                 if (objectFlags & 4 /* Reference */) {
47758                     if (type.node) {
47759                         return getObjectTypeInstantiation(type, mapper);
47760                     }
47761                     var resolvedTypeArguments = type.resolvedTypeArguments;
47762                     var newTypeArguments = instantiateTypes(resolvedTypeArguments, mapper);
47763                     return newTypeArguments !== resolvedTypeArguments ? createTypeReference(type.target, newTypeArguments) : type;
47764                 }
47765                 return type;
47766             }
47767             if ((flags & 2097152 /* Intersection */) || (flags & 1048576 /* Union */ && !(flags & 131068 /* Primitive */))) {
47768                 if (!couldContainTypeVariables(type)) {
47769                     return type;
47770                 }
47771                 var types = type.types;
47772                 var newTypes = instantiateTypes(types, mapper);
47773                 return newTypes === types
47774                     ? type
47775                     : (flags & 2097152 /* Intersection */)
47776                         ? getIntersectionType(newTypes, type.aliasSymbol, instantiateTypes(type.aliasTypeArguments, mapper))
47777                         : getUnionType(newTypes, 1 /* Literal */, type.aliasSymbol, instantiateTypes(type.aliasTypeArguments, mapper));
47778             }
47779             if (flags & 4194304 /* Index */) {
47780                 return getIndexType(instantiateType(type.type, mapper));
47781             }
47782             if (flags & 8388608 /* IndexedAccess */) {
47783                 return getIndexedAccessType(instantiateType(type.objectType, mapper), instantiateType(type.indexType, mapper), /*accessNode*/ undefined, type.aliasSymbol, instantiateTypes(type.aliasTypeArguments, mapper));
47784             }
47785             if (flags & 16777216 /* Conditional */) {
47786                 return getConditionalTypeInstantiation(type, combineTypeMappers(type.mapper, mapper));
47787             }
47788             if (flags & 33554432 /* Substitution */) {
47789                 var maybeVariable = instantiateType(type.baseType, mapper);
47790                 if (maybeVariable.flags & 8650752 /* TypeVariable */) {
47791                     return getSubstitutionType(maybeVariable, instantiateType(type.substitute, mapper));
47792                 }
47793                 else {
47794                     var sub = instantiateType(type.substitute, mapper);
47795                     if (sub.flags & 3 /* AnyOrUnknown */ || isTypeAssignableTo(getRestrictiveInstantiation(maybeVariable), getRestrictiveInstantiation(sub))) {
47796                         return maybeVariable;
47797                     }
47798                     return sub;
47799                 }
47800             }
47801             return type;
47802         }
47803         function getPermissiveInstantiation(type) {
47804             return type.flags & (131068 /* Primitive */ | 3 /* AnyOrUnknown */ | 131072 /* Never */) ? type :
47805                 type.permissiveInstantiation || (type.permissiveInstantiation = instantiateType(type, permissiveMapper));
47806         }
47807         function getRestrictiveInstantiation(type) {
47808             if (type.flags & (131068 /* Primitive */ | 3 /* AnyOrUnknown */ | 131072 /* Never */)) {
47809                 return type;
47810             }
47811             if (type.restrictiveInstantiation) {
47812                 return type.restrictiveInstantiation;
47813             }
47814             type.restrictiveInstantiation = instantiateType(type, restrictiveMapper);
47815             // We set the following so we don't attempt to set the restrictive instance of a restrictive instance
47816             // which is redundant - we'll produce new type identities, but all type params have already been mapped.
47817             // This also gives us a way to detect restrictive instances upon comparisons and _disable_ the "distributeive constraint"
47818             // assignability check for them, which is distinctly unsafe, as once you have a restrctive instance, all the type parameters
47819             // are constrained to `unknown` and produce tons of false positives/negatives!
47820             type.restrictiveInstantiation.restrictiveInstantiation = type.restrictiveInstantiation;
47821             return type.restrictiveInstantiation;
47822         }
47823         function instantiateIndexInfo(info, mapper) {
47824             return info && createIndexInfo(instantiateType(info.type, mapper), info.isReadonly, info.declaration);
47825         }
47826         // Returns true if the given expression contains (at any level of nesting) a function or arrow expression
47827         // that is subject to contextual typing.
47828         function isContextSensitive(node) {
47829             ts.Debug.assert(node.kind !== 161 /* MethodDeclaration */ || ts.isObjectLiteralMethod(node));
47830             switch (node.kind) {
47831                 case 201 /* FunctionExpression */:
47832                 case 202 /* ArrowFunction */:
47833                 case 161 /* MethodDeclaration */:
47834                 case 244 /* FunctionDeclaration */: // Function declarations can have context when annotated with a jsdoc @type
47835                     return isContextSensitiveFunctionLikeDeclaration(node);
47836                 case 193 /* ObjectLiteralExpression */:
47837                     return ts.some(node.properties, isContextSensitive);
47838                 case 192 /* ArrayLiteralExpression */:
47839                     return ts.some(node.elements, isContextSensitive);
47840                 case 210 /* ConditionalExpression */:
47841                     return isContextSensitive(node.whenTrue) ||
47842                         isContextSensitive(node.whenFalse);
47843                 case 209 /* BinaryExpression */:
47844                     return (node.operatorToken.kind === 56 /* BarBarToken */ || node.operatorToken.kind === 60 /* QuestionQuestionToken */) &&
47845                         (isContextSensitive(node.left) || isContextSensitive(node.right));
47846                 case 281 /* PropertyAssignment */:
47847                     return isContextSensitive(node.initializer);
47848                 case 200 /* ParenthesizedExpression */:
47849                     return isContextSensitive(node.expression);
47850                 case 274 /* JsxAttributes */:
47851                     return ts.some(node.properties, isContextSensitive) || ts.isJsxOpeningElement(node.parent) && ts.some(node.parent.parent.children, isContextSensitive);
47852                 case 273 /* JsxAttribute */: {
47853                     // If there is no initializer, JSX attribute has a boolean value of true which is not context sensitive.
47854                     var initializer = node.initializer;
47855                     return !!initializer && isContextSensitive(initializer);
47856                 }
47857                 case 276 /* JsxExpression */: {
47858                     // It is possible to that node.expression is undefined (e.g <div x={} />)
47859                     var expression = node.expression;
47860                     return !!expression && isContextSensitive(expression);
47861                 }
47862             }
47863             return false;
47864         }
47865         function isContextSensitiveFunctionLikeDeclaration(node) {
47866             return (!ts.isFunctionDeclaration(node) || ts.isInJSFile(node) && !!getTypeForDeclarationFromJSDocComment(node)) &&
47867                 (hasContextSensitiveParameters(node) || hasContextSensitiveReturnExpression(node));
47868         }
47869         function hasContextSensitiveParameters(node) {
47870             // Functions with type parameters are not context sensitive.
47871             if (!node.typeParameters) {
47872                 // Functions with any parameters that lack type annotations are context sensitive.
47873                 if (ts.some(node.parameters, function (p) { return !ts.getEffectiveTypeAnnotationNode(p); })) {
47874                     return true;
47875                 }
47876                 if (node.kind !== 202 /* ArrowFunction */) {
47877                     // If the first parameter is not an explicit 'this' parameter, then the function has
47878                     // an implicit 'this' parameter which is subject to contextual typing.
47879                     var parameter = ts.firstOrUndefined(node.parameters);
47880                     if (!(parameter && ts.parameterIsThisKeyword(parameter))) {
47881                         return true;
47882                     }
47883                 }
47884             }
47885             return false;
47886         }
47887         function hasContextSensitiveReturnExpression(node) {
47888             // TODO(anhans): A block should be context-sensitive if it has a context-sensitive return value.
47889             return !node.typeParameters && !ts.getEffectiveReturnTypeNode(node) && !!node.body && node.body.kind !== 223 /* Block */ && isContextSensitive(node.body);
47890         }
47891         function isContextSensitiveFunctionOrObjectLiteralMethod(func) {
47892             return (ts.isInJSFile(func) && ts.isFunctionDeclaration(func) || isFunctionExpressionOrArrowFunction(func) || ts.isObjectLiteralMethod(func)) &&
47893                 isContextSensitiveFunctionLikeDeclaration(func);
47894         }
47895         function getTypeWithoutSignatures(type) {
47896             if (type.flags & 524288 /* Object */) {
47897                 var resolved = resolveStructuredTypeMembers(type);
47898                 if (resolved.constructSignatures.length || resolved.callSignatures.length) {
47899                     var result = createObjectType(16 /* Anonymous */, type.symbol);
47900                     result.members = resolved.members;
47901                     result.properties = resolved.properties;
47902                     result.callSignatures = ts.emptyArray;
47903                     result.constructSignatures = ts.emptyArray;
47904                     return result;
47905                 }
47906             }
47907             else if (type.flags & 2097152 /* Intersection */) {
47908                 return getIntersectionType(ts.map(type.types, getTypeWithoutSignatures));
47909             }
47910             return type;
47911         }
47912         // TYPE CHECKING
47913         function isTypeIdenticalTo(source, target) {
47914             return isTypeRelatedTo(source, target, identityRelation);
47915         }
47916         function compareTypesIdentical(source, target) {
47917             return isTypeRelatedTo(source, target, identityRelation) ? -1 /* True */ : 0 /* False */;
47918         }
47919         function compareTypesAssignable(source, target) {
47920             return isTypeRelatedTo(source, target, assignableRelation) ? -1 /* True */ : 0 /* False */;
47921         }
47922         function compareTypesSubtypeOf(source, target) {
47923             return isTypeRelatedTo(source, target, subtypeRelation) ? -1 /* True */ : 0 /* False */;
47924         }
47925         function isTypeSubtypeOf(source, target) {
47926             return isTypeRelatedTo(source, target, subtypeRelation);
47927         }
47928         function isTypeAssignableTo(source, target) {
47929             return isTypeRelatedTo(source, target, assignableRelation);
47930         }
47931         // An object type S is considered to be derived from an object type T if
47932         // S is a union type and every constituent of S is derived from T,
47933         // T is a union type and S is derived from at least one constituent of T, or
47934         // S is a type variable with a base constraint that is derived from T,
47935         // T is one of the global types Object and Function and S is a subtype of T, or
47936         // T occurs directly or indirectly in an 'extends' clause of S.
47937         // Note that this check ignores type parameters and only considers the
47938         // inheritance hierarchy.
47939         function isTypeDerivedFrom(source, target) {
47940             return source.flags & 1048576 /* Union */ ? ts.every(source.types, function (t) { return isTypeDerivedFrom(t, target); }) :
47941                 target.flags & 1048576 /* Union */ ? ts.some(target.types, function (t) { return isTypeDerivedFrom(source, t); }) :
47942                     source.flags & 58982400 /* InstantiableNonPrimitive */ ? isTypeDerivedFrom(getBaseConstraintOfType(source) || unknownType, target) :
47943                         target === globalObjectType ? !!(source.flags & (524288 /* Object */ | 67108864 /* NonPrimitive */)) :
47944                             target === globalFunctionType ? !!(source.flags & 524288 /* Object */) && isFunctionObjectType(source) :
47945                                 hasBaseType(source, getTargetType(target));
47946         }
47947         /**
47948          * This is *not* a bi-directional relationship.
47949          * If one needs to check both directions for comparability, use a second call to this function or 'checkTypeComparableTo'.
47950          *
47951          * 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.
47952          * It is used to check following cases:
47953          *   - the types of the left and right sides of equality/inequality operators (`===`, `!==`, `==`, `!=`).
47954          *   - the types of `case` clause expressions and their respective `switch` expressions.
47955          *   - the type of an expression in a type assertion with the type being asserted.
47956          */
47957         function isTypeComparableTo(source, target) {
47958             return isTypeRelatedTo(source, target, comparableRelation);
47959         }
47960         function areTypesComparable(type1, type2) {
47961             return isTypeComparableTo(type1, type2) || isTypeComparableTo(type2, type1);
47962         }
47963         function checkTypeAssignableTo(source, target, errorNode, headMessage, containingMessageChain, errorOutputObject) {
47964             return checkTypeRelatedTo(source, target, assignableRelation, errorNode, headMessage, containingMessageChain, errorOutputObject);
47965         }
47966         /**
47967          * Like `checkTypeAssignableTo`, but if it would issue an error, instead performs structural comparisons of the types using the given expression node to
47968          * attempt to issue more specific errors on, for example, specific object literal properties or tuple members.
47969          */
47970         function checkTypeAssignableToAndOptionallyElaborate(source, target, errorNode, expr, headMessage, containingMessageChain) {
47971             return checkTypeRelatedToAndOptionallyElaborate(source, target, assignableRelation, errorNode, expr, headMessage, containingMessageChain, /*errorOutputContainer*/ undefined);
47972         }
47973         function checkTypeRelatedToAndOptionallyElaborate(source, target, relation, errorNode, expr, headMessage, containingMessageChain, errorOutputContainer) {
47974             if (isTypeRelatedTo(source, target, relation))
47975                 return true;
47976             if (!errorNode || !elaborateError(expr, source, target, relation, headMessage, containingMessageChain, errorOutputContainer)) {
47977                 return checkTypeRelatedTo(source, target, relation, errorNode, headMessage, containingMessageChain, errorOutputContainer);
47978             }
47979             return false;
47980         }
47981         function isOrHasGenericConditional(type) {
47982             return !!(type.flags & 16777216 /* Conditional */ || (type.flags & 2097152 /* Intersection */ && ts.some(type.types, isOrHasGenericConditional)));
47983         }
47984         function elaborateError(node, source, target, relation, headMessage, containingMessageChain, errorOutputContainer) {
47985             if (!node || isOrHasGenericConditional(target))
47986                 return false;
47987             if (!checkTypeRelatedTo(source, target, relation, /*errorNode*/ undefined)
47988                 && elaborateDidYouMeanToCallOrConstruct(node, source, target, relation, headMessage, containingMessageChain, errorOutputContainer)) {
47989                 return true;
47990             }
47991             switch (node.kind) {
47992                 case 276 /* JsxExpression */:
47993                 case 200 /* ParenthesizedExpression */:
47994                     return elaborateError(node.expression, source, target, relation, headMessage, containingMessageChain, errorOutputContainer);
47995                 case 209 /* BinaryExpression */:
47996                     switch (node.operatorToken.kind) {
47997                         case 62 /* EqualsToken */:
47998                         case 27 /* CommaToken */:
47999                             return elaborateError(node.right, source, target, relation, headMessage, containingMessageChain, errorOutputContainer);
48000                     }
48001                     break;
48002                 case 193 /* ObjectLiteralExpression */:
48003                     return elaborateObjectLiteral(node, source, target, relation, containingMessageChain, errorOutputContainer);
48004                 case 192 /* ArrayLiteralExpression */:
48005                     return elaborateArrayLiteral(node, source, target, relation, containingMessageChain, errorOutputContainer);
48006                 case 274 /* JsxAttributes */:
48007                     return elaborateJsxComponents(node, source, target, relation, containingMessageChain, errorOutputContainer);
48008                 case 202 /* ArrowFunction */:
48009                     return elaborateArrowFunction(node, source, target, relation, containingMessageChain, errorOutputContainer);
48010             }
48011             return false;
48012         }
48013         function elaborateDidYouMeanToCallOrConstruct(node, source, target, relation, headMessage, containingMessageChain, errorOutputContainer) {
48014             var callSignatures = getSignaturesOfType(source, 0 /* Call */);
48015             var constructSignatures = getSignaturesOfType(source, 1 /* Construct */);
48016             for (var _i = 0, _a = [constructSignatures, callSignatures]; _i < _a.length; _i++) {
48017                 var signatures = _a[_i];
48018                 if (ts.some(signatures, function (s) {
48019                     var returnType = getReturnTypeOfSignature(s);
48020                     return !(returnType.flags & (1 /* Any */ | 131072 /* Never */)) && checkTypeRelatedTo(returnType, target, relation, /*errorNode*/ undefined);
48021                 })) {
48022                     var resultObj = errorOutputContainer || {};
48023                     checkTypeAssignableTo(source, target, node, headMessage, containingMessageChain, resultObj);
48024                     var diagnostic = resultObj.errors[resultObj.errors.length - 1];
48025                     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));
48026                     return true;
48027                 }
48028             }
48029             return false;
48030         }
48031         function elaborateArrowFunction(node, source, target, relation, containingMessageChain, errorOutputContainer) {
48032             // Don't elaborate blocks
48033             if (ts.isBlock(node.body)) {
48034                 return false;
48035             }
48036             // Or functions with annotated parameter types
48037             if (ts.some(node.parameters, ts.hasType)) {
48038                 return false;
48039             }
48040             var sourceSig = getSingleCallSignature(source);
48041             if (!sourceSig) {
48042                 return false;
48043             }
48044             var targetSignatures = getSignaturesOfType(target, 0 /* Call */);
48045             if (!ts.length(targetSignatures)) {
48046                 return false;
48047             }
48048             var returnExpression = node.body;
48049             var sourceReturn = getReturnTypeOfSignature(sourceSig);
48050             var targetReturn = getUnionType(ts.map(targetSignatures, getReturnTypeOfSignature));
48051             if (!checkTypeRelatedTo(sourceReturn, targetReturn, relation, /*errorNode*/ undefined)) {
48052                 var elaborated = returnExpression && elaborateError(returnExpression, sourceReturn, targetReturn, relation, /*headMessage*/ undefined, containingMessageChain, errorOutputContainer);
48053                 if (elaborated) {
48054                     return elaborated;
48055                 }
48056                 var resultObj = errorOutputContainer || {};
48057                 checkTypeRelatedTo(sourceReturn, targetReturn, relation, returnExpression, /*message*/ undefined, containingMessageChain, resultObj);
48058                 if (resultObj.errors) {
48059                     if (target.symbol && ts.length(target.symbol.declarations)) {
48060                         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));
48061                     }
48062                     if ((ts.getFunctionFlags(node) & 2 /* Async */) === 0
48063                         // exclude cases where source itself is promisy - this way we don't make a suggestion when relating
48064                         // an IPromise and a Promise that are slightly different
48065                         && !getTypeOfPropertyOfType(sourceReturn, "then")
48066                         && checkTypeRelatedTo(createPromiseType(sourceReturn), targetReturn, relation, /*errorNode*/ undefined)) {
48067                         ts.addRelatedInfo(resultObj.errors[resultObj.errors.length - 1], ts.createDiagnosticForNode(node, ts.Diagnostics.Did_you_mean_to_mark_this_function_as_async));
48068                     }
48069                     return true;
48070                 }
48071             }
48072             return false;
48073         }
48074         function getBestMatchIndexedAccessTypeOrUndefined(source, target, nameType) {
48075             var idx = getIndexedAccessTypeOrUndefined(target, nameType);
48076             if (idx) {
48077                 return idx;
48078             }
48079             if (target.flags & 1048576 /* Union */) {
48080                 var best = getBestMatchingType(source, target);
48081                 if (best) {
48082                     return getIndexedAccessTypeOrUndefined(best, nameType);
48083                 }
48084             }
48085         }
48086         function checkExpressionForMutableLocationWithContextualType(next, sourcePropType) {
48087             next.contextualType = sourcePropType;
48088             try {
48089                 return checkExpressionForMutableLocation(next, 1 /* Contextual */, sourcePropType);
48090             }
48091             finally {
48092                 next.contextualType = undefined;
48093             }
48094         }
48095         /**
48096          * For every element returned from the iterator, checks that element to issue an error on a property of that element's type
48097          * 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`
48098          * Otherwise, we issue an error on _every_ element which fail the assignability check
48099          */
48100         function elaborateElementwise(iterator, source, target, relation, containingMessageChain, errorOutputContainer) {
48101             // Assignability failure - check each prop individually, and if that fails, fall back on the bad error span
48102             var reportedError = false;
48103             for (var status = iterator.next(); !status.done; status = iterator.next()) {
48104                 var _a = status.value, prop = _a.errorNode, next = _a.innerExpression, nameType = _a.nameType, errorMessage = _a.errorMessage;
48105                 var targetPropType = getBestMatchIndexedAccessTypeOrUndefined(source, target, nameType);
48106                 if (!targetPropType || targetPropType.flags & 8388608 /* IndexedAccess */)
48107                     continue; // Don't elaborate on indexes on generic variables
48108                 var sourcePropType = getIndexedAccessTypeOrUndefined(source, nameType);
48109                 if (sourcePropType && !checkTypeRelatedTo(sourcePropType, targetPropType, relation, /*errorNode*/ undefined)) {
48110                     var elaborated = next && elaborateError(next, sourcePropType, targetPropType, relation, /*headMessage*/ undefined, containingMessageChain, errorOutputContainer);
48111                     if (elaborated) {
48112                         reportedError = true;
48113                     }
48114                     else {
48115                         // Issue error on the prop itself, since the prop couldn't elaborate the error
48116                         var resultObj = errorOutputContainer || {};
48117                         // Use the expression type, if available
48118                         var specificSource = next ? checkExpressionForMutableLocationWithContextualType(next, sourcePropType) : sourcePropType;
48119                         var result = checkTypeRelatedTo(specificSource, targetPropType, relation, prop, errorMessage, containingMessageChain, resultObj);
48120                         if (result && specificSource !== sourcePropType) {
48121                             // If for whatever reason the expression type doesn't yield an error, make sure we still issue an error on the sourcePropType
48122                             checkTypeRelatedTo(sourcePropType, targetPropType, relation, prop, errorMessage, containingMessageChain, resultObj);
48123                         }
48124                         if (resultObj.errors) {
48125                             var reportedDiag = resultObj.errors[resultObj.errors.length - 1];
48126                             var propertyName = isTypeUsableAsPropertyName(nameType) ? getPropertyNameFromType(nameType) : undefined;
48127                             var targetProp = propertyName !== undefined ? getPropertyOfType(target, propertyName) : undefined;
48128                             var issuedElaboration = false;
48129                             if (!targetProp) {
48130                                 var indexInfo = isTypeAssignableToKind(nameType, 296 /* NumberLike */) && getIndexInfoOfType(target, 1 /* Number */) ||
48131                                     getIndexInfoOfType(target, 0 /* String */) ||
48132                                     undefined;
48133                                 if (indexInfo && indexInfo.declaration && !ts.getSourceFileOfNode(indexInfo.declaration).hasNoDefaultLib) {
48134                                     issuedElaboration = true;
48135                                     ts.addRelatedInfo(reportedDiag, ts.createDiagnosticForNode(indexInfo.declaration, ts.Diagnostics.The_expected_type_comes_from_this_index_signature));
48136                                 }
48137                             }
48138                             if (!issuedElaboration && (targetProp && ts.length(targetProp.declarations) || target.symbol && ts.length(target.symbol.declarations))) {
48139                                 var targetNode = targetProp && ts.length(targetProp.declarations) ? targetProp.declarations[0] : target.symbol.declarations[0];
48140                                 if (!ts.getSourceFileOfNode(targetNode).hasNoDefaultLib) {
48141                                     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)));
48142                                 }
48143                             }
48144                         }
48145                         reportedError = true;
48146                     }
48147                 }
48148             }
48149             return reportedError;
48150         }
48151         function generateJsxAttributes(node) {
48152             var _i, _a, prop;
48153             return __generator(this, function (_b) {
48154                 switch (_b.label) {
48155                     case 0:
48156                         if (!ts.length(node.properties))
48157                             return [2 /*return*/];
48158                         _i = 0, _a = node.properties;
48159                         _b.label = 1;
48160                     case 1:
48161                         if (!(_i < _a.length)) return [3 /*break*/, 4];
48162                         prop = _a[_i];
48163                         if (ts.isJsxSpreadAttribute(prop))
48164                             return [3 /*break*/, 3];
48165                         return [4 /*yield*/, { errorNode: prop.name, innerExpression: prop.initializer, nameType: getLiteralType(ts.idText(prop.name)) }];
48166                     case 2:
48167                         _b.sent();
48168                         _b.label = 3;
48169                     case 3:
48170                         _i++;
48171                         return [3 /*break*/, 1];
48172                     case 4: return [2 /*return*/];
48173                 }
48174             });
48175         }
48176         function generateJsxChildren(node, getInvalidTextDiagnostic) {
48177             var memberOffset, i, child, nameType, elem;
48178             return __generator(this, function (_a) {
48179                 switch (_a.label) {
48180                     case 0:
48181                         if (!ts.length(node.children))
48182                             return [2 /*return*/];
48183                         memberOffset = 0;
48184                         i = 0;
48185                         _a.label = 1;
48186                     case 1:
48187                         if (!(i < node.children.length)) return [3 /*break*/, 5];
48188                         child = node.children[i];
48189                         nameType = getLiteralType(i - memberOffset);
48190                         elem = getElaborationElementForJsxChild(child, nameType, getInvalidTextDiagnostic);
48191                         if (!elem) return [3 /*break*/, 3];
48192                         return [4 /*yield*/, elem];
48193                     case 2:
48194                         _a.sent();
48195                         return [3 /*break*/, 4];
48196                     case 3:
48197                         memberOffset++;
48198                         _a.label = 4;
48199                     case 4:
48200                         i++;
48201                         return [3 /*break*/, 1];
48202                     case 5: return [2 /*return*/];
48203                 }
48204             });
48205         }
48206         function getElaborationElementForJsxChild(child, nameType, getInvalidTextDiagnostic) {
48207             switch (child.kind) {
48208                 case 276 /* JsxExpression */:
48209                     // child is of the type of the expression
48210                     return { errorNode: child, innerExpression: child.expression, nameType: nameType };
48211                 case 11 /* JsxText */:
48212                     if (child.containsOnlyTriviaWhiteSpaces) {
48213                         break; // Whitespace only jsx text isn't real jsx text
48214                     }
48215                     // child is a string
48216                     return { errorNode: child, innerExpression: undefined, nameType: nameType, errorMessage: getInvalidTextDiagnostic() };
48217                 case 266 /* JsxElement */:
48218                 case 267 /* JsxSelfClosingElement */:
48219                 case 270 /* JsxFragment */:
48220                     // child is of type JSX.Element
48221                     return { errorNode: child, innerExpression: child, nameType: nameType };
48222                 default:
48223                     return ts.Debug.assertNever(child, "Found invalid jsx child");
48224             }
48225         }
48226         function getSemanticJsxChildren(children) {
48227             return ts.filter(children, function (i) { return !ts.isJsxText(i) || !i.containsOnlyTriviaWhiteSpaces; });
48228         }
48229         function elaborateJsxComponents(node, source, target, relation, containingMessageChain, errorOutputContainer) {
48230             var result = elaborateElementwise(generateJsxAttributes(node), source, target, relation, containingMessageChain, errorOutputContainer);
48231             var invalidTextDiagnostic;
48232             if (ts.isJsxOpeningElement(node.parent) && ts.isJsxElement(node.parent.parent)) {
48233                 var containingElement = node.parent.parent;
48234                 var childPropName = getJsxElementChildrenPropertyName(getJsxNamespaceAt(node));
48235                 var childrenPropName = childPropName === undefined ? "children" : ts.unescapeLeadingUnderscores(childPropName);
48236                 var childrenNameType = getLiteralType(childrenPropName);
48237                 var childrenTargetType = getIndexedAccessType(target, childrenNameType);
48238                 var validChildren = getSemanticJsxChildren(containingElement.children);
48239                 if (!ts.length(validChildren)) {
48240                     return result;
48241                 }
48242                 var moreThanOneRealChildren = ts.length(validChildren) > 1;
48243                 var arrayLikeTargetParts = filterType(childrenTargetType, isArrayOrTupleLikeType);
48244                 var nonArrayLikeTargetParts = filterType(childrenTargetType, function (t) { return !isArrayOrTupleLikeType(t); });
48245                 if (moreThanOneRealChildren) {
48246                     if (arrayLikeTargetParts !== neverType) {
48247                         var realSource = createTupleType(checkJsxChildren(containingElement, 0 /* Normal */));
48248                         var children = generateJsxChildren(containingElement, getInvalidTextualChildDiagnostic);
48249                         result = elaborateElementwise(children, realSource, arrayLikeTargetParts, relation, containingMessageChain, errorOutputContainer) || result;
48250                     }
48251                     else if (!isTypeRelatedTo(getIndexedAccessType(source, childrenNameType), childrenTargetType, relation)) {
48252                         // arity mismatch
48253                         result = true;
48254                         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));
48255                         if (errorOutputContainer && errorOutputContainer.skipLogging) {
48256                             (errorOutputContainer.errors || (errorOutputContainer.errors = [])).push(diag);
48257                         }
48258                     }
48259                 }
48260                 else {
48261                     if (nonArrayLikeTargetParts !== neverType) {
48262                         var child = validChildren[0];
48263                         var elem_1 = getElaborationElementForJsxChild(child, childrenNameType, getInvalidTextualChildDiagnostic);
48264                         if (elem_1) {
48265                             result = elaborateElementwise((function () { return __generator(this, function (_a) {
48266                                 switch (_a.label) {
48267                                     case 0: return [4 /*yield*/, elem_1];
48268                                     case 1:
48269                                         _a.sent();
48270                                         return [2 /*return*/];
48271                                 }
48272                             }); })(), source, target, relation, containingMessageChain, errorOutputContainer) || result;
48273                         }
48274                     }
48275                     else if (!isTypeRelatedTo(getIndexedAccessType(source, childrenNameType), childrenTargetType, relation)) {
48276                         // arity mismatch
48277                         result = true;
48278                         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));
48279                         if (errorOutputContainer && errorOutputContainer.skipLogging) {
48280                             (errorOutputContainer.errors || (errorOutputContainer.errors = [])).push(diag);
48281                         }
48282                     }
48283                 }
48284             }
48285             return result;
48286             function getInvalidTextualChildDiagnostic() {
48287                 if (!invalidTextDiagnostic) {
48288                     var tagNameText = ts.getTextOfNode(node.parent.tagName);
48289                     var childPropName = getJsxElementChildrenPropertyName(getJsxNamespaceAt(node));
48290                     var childrenPropName = childPropName === undefined ? "children" : ts.unescapeLeadingUnderscores(childPropName);
48291                     var childrenTargetType = getIndexedAccessType(target, getLiteralType(childrenPropName));
48292                     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;
48293                     invalidTextDiagnostic = __assign(__assign({}, diagnostic), { key: "!!ALREADY FORMATTED!!", message: ts.formatMessage(/*_dummy*/ undefined, diagnostic, tagNameText, childrenPropName, typeToString(childrenTargetType)) });
48294                 }
48295                 return invalidTextDiagnostic;
48296             }
48297         }
48298         function generateLimitedTupleElements(node, target) {
48299             var len, i, elem, nameType;
48300             return __generator(this, function (_a) {
48301                 switch (_a.label) {
48302                     case 0:
48303                         len = ts.length(node.elements);
48304                         if (!len)
48305                             return [2 /*return*/];
48306                         i = 0;
48307                         _a.label = 1;
48308                     case 1:
48309                         if (!(i < len)) return [3 /*break*/, 4];
48310                         // 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
48311                         if (isTupleLikeType(target) && !getPropertyOfType(target, ("" + i)))
48312                             return [3 /*break*/, 3];
48313                         elem = node.elements[i];
48314                         if (ts.isOmittedExpression(elem))
48315                             return [3 /*break*/, 3];
48316                         nameType = getLiteralType(i);
48317                         return [4 /*yield*/, { errorNode: elem, innerExpression: elem, nameType: nameType }];
48318                     case 2:
48319                         _a.sent();
48320                         _a.label = 3;
48321                     case 3:
48322                         i++;
48323                         return [3 /*break*/, 1];
48324                     case 4: return [2 /*return*/];
48325                 }
48326             });
48327         }
48328         function elaborateArrayLiteral(node, source, target, relation, containingMessageChain, errorOutputContainer) {
48329             if (target.flags & 131068 /* Primitive */)
48330                 return false;
48331             if (isTupleLikeType(source)) {
48332                 return elaborateElementwise(generateLimitedTupleElements(node, target), source, target, relation, containingMessageChain, errorOutputContainer);
48333             }
48334             // recreate a tuple from the elements, if possible
48335             // Since we're re-doing the expression type, we need to reapply the contextual type
48336             var oldContext = node.contextualType;
48337             node.contextualType = target;
48338             try {
48339                 var tupleizedType = checkArrayLiteral(node, 1 /* Contextual */, /*forceTuple*/ true);
48340                 node.contextualType = oldContext;
48341                 if (isTupleLikeType(tupleizedType)) {
48342                     return elaborateElementwise(generateLimitedTupleElements(node, target), tupleizedType, target, relation, containingMessageChain, errorOutputContainer);
48343                 }
48344                 return false;
48345             }
48346             finally {
48347                 node.contextualType = oldContext;
48348             }
48349         }
48350         function generateObjectLiteralElements(node) {
48351             var _i, _a, prop, type, _b;
48352             return __generator(this, function (_c) {
48353                 switch (_c.label) {
48354                     case 0:
48355                         if (!ts.length(node.properties))
48356                             return [2 /*return*/];
48357                         _i = 0, _a = node.properties;
48358                         _c.label = 1;
48359                     case 1:
48360                         if (!(_i < _a.length)) return [3 /*break*/, 8];
48361                         prop = _a[_i];
48362                         if (ts.isSpreadAssignment(prop))
48363                             return [3 /*break*/, 7];
48364                         type = getLiteralTypeFromProperty(getSymbolOfNode(prop), 8576 /* StringOrNumberLiteralOrUnique */);
48365                         if (!type || (type.flags & 131072 /* Never */)) {
48366                             return [3 /*break*/, 7];
48367                         }
48368                         _b = prop.kind;
48369                         switch (_b) {
48370                             case 164 /* SetAccessor */: return [3 /*break*/, 2];
48371                             case 163 /* GetAccessor */: return [3 /*break*/, 2];
48372                             case 161 /* MethodDeclaration */: return [3 /*break*/, 2];
48373                             case 282 /* ShorthandPropertyAssignment */: return [3 /*break*/, 2];
48374                             case 281 /* PropertyAssignment */: return [3 /*break*/, 4];
48375                         }
48376                         return [3 /*break*/, 6];
48377                     case 2: return [4 /*yield*/, { errorNode: prop.name, innerExpression: undefined, nameType: type }];
48378                     case 3:
48379                         _c.sent();
48380                         return [3 /*break*/, 7];
48381                     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 }];
48382                     case 5:
48383                         _c.sent();
48384                         return [3 /*break*/, 7];
48385                     case 6:
48386                         ts.Debug.assertNever(prop);
48387                         _c.label = 7;
48388                     case 7:
48389                         _i++;
48390                         return [3 /*break*/, 1];
48391                     case 8: return [2 /*return*/];
48392                 }
48393             });
48394         }
48395         function elaborateObjectLiteral(node, source, target, relation, containingMessageChain, errorOutputContainer) {
48396             if (target.flags & 131068 /* Primitive */)
48397                 return false;
48398             return elaborateElementwise(generateObjectLiteralElements(node), source, target, relation, containingMessageChain, errorOutputContainer);
48399         }
48400         /**
48401          * This is *not* a bi-directional relationship.
48402          * If one needs to check both directions for comparability, use a second call to this function or 'isTypeComparableTo'.
48403          */
48404         function checkTypeComparableTo(source, target, errorNode, headMessage, containingMessageChain) {
48405             return checkTypeRelatedTo(source, target, comparableRelation, errorNode, headMessage, containingMessageChain);
48406         }
48407         function isSignatureAssignableTo(source, target, ignoreReturnTypes) {
48408             return compareSignaturesRelated(source, target, ignoreReturnTypes ? 4 /* IgnoreReturnTypes */ : 0, /*reportErrors*/ false, 
48409             /*errorReporter*/ undefined, /*errorReporter*/ undefined, compareTypesAssignable, /*reportUnreliableMarkers*/ undefined) !== 0 /* False */;
48410         }
48411         /**
48412          * Returns true if `s` is `(...args: any[]) => any` or `(this: any, ...args: any[]) => any`
48413          */
48414         function isAnySignature(s) {
48415             return !s.typeParameters && (!s.thisParameter || isTypeAny(getTypeOfParameter(s.thisParameter))) && s.parameters.length === 1 &&
48416                 signatureHasRestParameter(s) && (getTypeOfParameter(s.parameters[0]) === anyArrayType || isTypeAny(getTypeOfParameter(s.parameters[0]))) &&
48417                 isTypeAny(getReturnTypeOfSignature(s));
48418         }
48419         /**
48420          * See signatureRelatedTo, compareSignaturesIdentical
48421          */
48422         function compareSignaturesRelated(source, target, checkMode, reportErrors, errorReporter, incompatibleErrorReporter, compareTypes, reportUnreliableMarkers) {
48423             // TODO (drosen): De-duplicate code between related functions.
48424             if (source === target) {
48425                 return -1 /* True */;
48426             }
48427             if (isAnySignature(target)) {
48428                 return -1 /* True */;
48429             }
48430             var targetCount = getParameterCount(target);
48431             var sourceHasMoreParameters = !hasEffectiveRestParameter(target) &&
48432                 (checkMode & 8 /* StrictArity */ ? hasEffectiveRestParameter(source) || getParameterCount(source) > targetCount : getMinArgumentCount(source) > targetCount);
48433             if (sourceHasMoreParameters) {
48434                 return 0 /* False */;
48435             }
48436             if (source.typeParameters && source.typeParameters !== target.typeParameters) {
48437                 target = getCanonicalSignature(target);
48438                 source = instantiateSignatureInContextOf(source, target, /*inferenceContext*/ undefined, compareTypes);
48439             }
48440             var sourceCount = getParameterCount(source);
48441             var sourceRestType = getNonArrayRestType(source);
48442             var targetRestType = getNonArrayRestType(target);
48443             if (sourceRestType || targetRestType) {
48444                 void instantiateType(sourceRestType || targetRestType, reportUnreliableMarkers);
48445             }
48446             if (sourceRestType && targetRestType && sourceCount !== targetCount) {
48447                 // We're not able to relate misaligned complex rest parameters
48448                 return 0 /* False */;
48449             }
48450             var kind = target.declaration ? target.declaration.kind : 0 /* Unknown */;
48451             var strictVariance = !(checkMode & 3 /* Callback */) && strictFunctionTypes && kind !== 161 /* MethodDeclaration */ &&
48452                 kind !== 160 /* MethodSignature */ && kind !== 162 /* Constructor */;
48453             var result = -1 /* True */;
48454             var sourceThisType = getThisTypeOfSignature(source);
48455             if (sourceThisType && sourceThisType !== voidType) {
48456                 var targetThisType = getThisTypeOfSignature(target);
48457                 if (targetThisType) {
48458                     // void sources are assignable to anything.
48459                     var related = !strictVariance && compareTypes(sourceThisType, targetThisType, /*reportErrors*/ false)
48460                         || compareTypes(targetThisType, sourceThisType, reportErrors);
48461                     if (!related) {
48462                         if (reportErrors) {
48463                             errorReporter(ts.Diagnostics.The_this_types_of_each_signature_are_incompatible);
48464                         }
48465                         return 0 /* False */;
48466                     }
48467                     result &= related;
48468                 }
48469             }
48470             var paramCount = sourceRestType || targetRestType ? Math.min(sourceCount, targetCount) : Math.max(sourceCount, targetCount);
48471             var restIndex = sourceRestType || targetRestType ? paramCount - 1 : -1;
48472             for (var i = 0; i < paramCount; i++) {
48473                 var sourceType = i === restIndex ? getRestTypeAtPosition(source, i) : getTypeAtPosition(source, i);
48474                 var targetType = i === restIndex ? getRestTypeAtPosition(target, i) : getTypeAtPosition(target, i);
48475                 // In order to ensure that any generic type Foo<T> is at least co-variant with respect to T no matter
48476                 // how Foo uses T, we need to relate parameters bi-variantly (given that parameters are input positions,
48477                 // they naturally relate only contra-variantly). However, if the source and target parameters both have
48478                 // function types with a single call signature, we know we are relating two callback parameters. In
48479                 // that case it is sufficient to only relate the parameters of the signatures co-variantly because,
48480                 // similar to return values, callback parameters are output positions. This means that a Promise<T>,
48481                 // where T is used only in callback parameter positions, will be co-variant (as opposed to bi-variant)
48482                 // with respect to T.
48483                 var sourceSig = checkMode & 3 /* Callback */ ? undefined : getSingleCallSignature(getNonNullableType(sourceType));
48484                 var targetSig = checkMode & 3 /* Callback */ ? undefined : getSingleCallSignature(getNonNullableType(targetType));
48485                 var callbacks = sourceSig && targetSig && !getTypePredicateOfSignature(sourceSig) && !getTypePredicateOfSignature(targetSig) &&
48486                     (getFalsyFlags(sourceType) & 98304 /* Nullable */) === (getFalsyFlags(targetType) & 98304 /* Nullable */);
48487                 var related = callbacks ?
48488                     compareSignaturesRelated(targetSig, sourceSig, (checkMode & 8 /* StrictArity */) | (strictVariance ? 2 /* StrictCallback */ : 1 /* BivariantCallback */), reportErrors, errorReporter, incompatibleErrorReporter, compareTypes, reportUnreliableMarkers) :
48489                     !(checkMode & 3 /* Callback */) && !strictVariance && compareTypes(sourceType, targetType, /*reportErrors*/ false) || compareTypes(targetType, sourceType, reportErrors);
48490                 // With strict arity, (x: number | undefined) => void is a subtype of (x?: number | undefined) => void
48491                 if (related && checkMode & 8 /* StrictArity */ && i >= getMinArgumentCount(source) && i < getMinArgumentCount(target) && compareTypes(sourceType, targetType, /*reportErrors*/ false)) {
48492                     related = 0 /* False */;
48493                 }
48494                 if (!related) {
48495                     if (reportErrors) {
48496                         errorReporter(ts.Diagnostics.Types_of_parameters_0_and_1_are_incompatible, ts.unescapeLeadingUnderscores(getParameterNameAtPosition(source, i)), ts.unescapeLeadingUnderscores(getParameterNameAtPosition(target, i)));
48497                     }
48498                     return 0 /* False */;
48499                 }
48500                 result &= related;
48501             }
48502             if (!(checkMode & 4 /* IgnoreReturnTypes */)) {
48503                 // If a signature resolution is already in-flight, skip issuing a circularity error
48504                 // here and just use the `any` type directly
48505                 var targetReturnType = isResolvingReturnTypeOfSignature(target) ? anyType
48506                     : target.declaration && isJSConstructor(target.declaration) ? getDeclaredTypeOfClassOrInterface(getMergedSymbol(target.declaration.symbol))
48507                         : getReturnTypeOfSignature(target);
48508                 if (targetReturnType === voidType) {
48509                     return result;
48510                 }
48511                 var sourceReturnType = isResolvingReturnTypeOfSignature(source) ? anyType
48512                     : source.declaration && isJSConstructor(source.declaration) ? getDeclaredTypeOfClassOrInterface(getMergedSymbol(source.declaration.symbol))
48513                         : getReturnTypeOfSignature(source);
48514                 // The following block preserves behavior forbidding boolean returning functions from being assignable to type guard returning functions
48515                 var targetTypePredicate = getTypePredicateOfSignature(target);
48516                 if (targetTypePredicate) {
48517                     var sourceTypePredicate = getTypePredicateOfSignature(source);
48518                     if (sourceTypePredicate) {
48519                         result &= compareTypePredicateRelatedTo(sourceTypePredicate, targetTypePredicate, reportErrors, errorReporter, compareTypes);
48520                     }
48521                     else if (ts.isIdentifierTypePredicate(targetTypePredicate)) {
48522                         if (reportErrors) {
48523                             errorReporter(ts.Diagnostics.Signature_0_must_be_a_type_predicate, signatureToString(source));
48524                         }
48525                         return 0 /* False */;
48526                     }
48527                 }
48528                 else {
48529                     // When relating callback signatures, we still need to relate return types bi-variantly as otherwise
48530                     // the containing type wouldn't be co-variant. For example, interface Foo<T> { add(cb: () => T): void }
48531                     // wouldn't be co-variant for T without this rule.
48532                     result &= checkMode & 1 /* BivariantCallback */ && compareTypes(targetReturnType, sourceReturnType, /*reportErrors*/ false) ||
48533                         compareTypes(sourceReturnType, targetReturnType, reportErrors);
48534                     if (!result && reportErrors && incompatibleErrorReporter) {
48535                         incompatibleErrorReporter(sourceReturnType, targetReturnType);
48536                     }
48537                 }
48538             }
48539             return result;
48540         }
48541         function compareTypePredicateRelatedTo(source, target, reportErrors, errorReporter, compareTypes) {
48542             if (source.kind !== target.kind) {
48543                 if (reportErrors) {
48544                     errorReporter(ts.Diagnostics.A_this_based_type_guard_is_not_compatible_with_a_parameter_based_type_guard);
48545                     errorReporter(ts.Diagnostics.Type_predicate_0_is_not_assignable_to_1, typePredicateToString(source), typePredicateToString(target));
48546                 }
48547                 return 0 /* False */;
48548             }
48549             if (source.kind === 1 /* Identifier */ || source.kind === 3 /* AssertsIdentifier */) {
48550                 if (source.parameterIndex !== target.parameterIndex) {
48551                     if (reportErrors) {
48552                         errorReporter(ts.Diagnostics.Parameter_0_is_not_in_the_same_position_as_parameter_1, source.parameterName, target.parameterName);
48553                         errorReporter(ts.Diagnostics.Type_predicate_0_is_not_assignable_to_1, typePredicateToString(source), typePredicateToString(target));
48554                     }
48555                     return 0 /* False */;
48556                 }
48557             }
48558             var related = source.type === target.type ? -1 /* True */ :
48559                 source.type && target.type ? compareTypes(source.type, target.type, reportErrors) :
48560                     0 /* False */;
48561             if (related === 0 /* False */ && reportErrors) {
48562                 errorReporter(ts.Diagnostics.Type_predicate_0_is_not_assignable_to_1, typePredicateToString(source), typePredicateToString(target));
48563             }
48564             return related;
48565         }
48566         function isImplementationCompatibleWithOverload(implementation, overload) {
48567             var erasedSource = getErasedSignature(implementation);
48568             var erasedTarget = getErasedSignature(overload);
48569             // First see if the return types are compatible in either direction.
48570             var sourceReturnType = getReturnTypeOfSignature(erasedSource);
48571             var targetReturnType = getReturnTypeOfSignature(erasedTarget);
48572             if (targetReturnType === voidType
48573                 || isTypeRelatedTo(targetReturnType, sourceReturnType, assignableRelation)
48574                 || isTypeRelatedTo(sourceReturnType, targetReturnType, assignableRelation)) {
48575                 return isSignatureAssignableTo(erasedSource, erasedTarget, /*ignoreReturnTypes*/ true);
48576             }
48577             return false;
48578         }
48579         function isEmptyResolvedType(t) {
48580             return t !== anyFunctionType &&
48581                 t.properties.length === 0 &&
48582                 t.callSignatures.length === 0 &&
48583                 t.constructSignatures.length === 0 &&
48584                 !t.stringIndexInfo &&
48585                 !t.numberIndexInfo;
48586         }
48587         function isEmptyObjectType(type) {
48588             return type.flags & 524288 /* Object */ ? !isGenericMappedType(type) && isEmptyResolvedType(resolveStructuredTypeMembers(type)) :
48589                 type.flags & 67108864 /* NonPrimitive */ ? true :
48590                     type.flags & 1048576 /* Union */ ? ts.some(type.types, isEmptyObjectType) :
48591                         type.flags & 2097152 /* Intersection */ ? ts.every(type.types, isEmptyObjectType) :
48592                             false;
48593         }
48594         function isEmptyAnonymousObjectType(type) {
48595             return !!(ts.getObjectFlags(type) & 16 /* Anonymous */) && isEmptyObjectType(type);
48596         }
48597         function isStringIndexSignatureOnlyType(type) {
48598             return type.flags & 524288 /* Object */ && !isGenericMappedType(type) && getPropertiesOfType(type).length === 0 && getIndexInfoOfType(type, 0 /* String */) && !getIndexInfoOfType(type, 1 /* Number */) ||
48599                 type.flags & 3145728 /* UnionOrIntersection */ && ts.every(type.types, isStringIndexSignatureOnlyType) ||
48600                 false;
48601         }
48602         function isEnumTypeRelatedTo(sourceSymbol, targetSymbol, errorReporter) {
48603             if (sourceSymbol === targetSymbol) {
48604                 return true;
48605             }
48606             var id = getSymbolId(sourceSymbol) + "," + getSymbolId(targetSymbol);
48607             var entry = enumRelation.get(id);
48608             if (entry !== undefined && !(!(entry & 4 /* Reported */) && entry & 2 /* Failed */ && errorReporter)) {
48609                 return !!(entry & 1 /* Succeeded */);
48610             }
48611             if (sourceSymbol.escapedName !== targetSymbol.escapedName || !(sourceSymbol.flags & 256 /* RegularEnum */) || !(targetSymbol.flags & 256 /* RegularEnum */)) {
48612                 enumRelation.set(id, 2 /* Failed */ | 4 /* Reported */);
48613                 return false;
48614             }
48615             var targetEnumType = getTypeOfSymbol(targetSymbol);
48616             for (var _i = 0, _a = getPropertiesOfType(getTypeOfSymbol(sourceSymbol)); _i < _a.length; _i++) {
48617                 var property = _a[_i];
48618                 if (property.flags & 8 /* EnumMember */) {
48619                     var targetProperty = getPropertyOfType(targetEnumType, property.escapedName);
48620                     if (!targetProperty || !(targetProperty.flags & 8 /* EnumMember */)) {
48621                         if (errorReporter) {
48622                             errorReporter(ts.Diagnostics.Property_0_is_missing_in_type_1, ts.symbolName(property), typeToString(getDeclaredTypeOfSymbol(targetSymbol), /*enclosingDeclaration*/ undefined, 64 /* UseFullyQualifiedType */));
48623                             enumRelation.set(id, 2 /* Failed */ | 4 /* Reported */);
48624                         }
48625                         else {
48626                             enumRelation.set(id, 2 /* Failed */);
48627                         }
48628                         return false;
48629                     }
48630                 }
48631             }
48632             enumRelation.set(id, 1 /* Succeeded */);
48633             return true;
48634         }
48635         function isSimpleTypeRelatedTo(source, target, relation, errorReporter) {
48636             var s = source.flags;
48637             var t = target.flags;
48638             if (t & 3 /* AnyOrUnknown */ || s & 131072 /* Never */ || source === wildcardType)
48639                 return true;
48640             if (t & 131072 /* Never */)
48641                 return false;
48642             if (s & 132 /* StringLike */ && t & 4 /* String */)
48643                 return true;
48644             if (s & 128 /* StringLiteral */ && s & 1024 /* EnumLiteral */ &&
48645                 t & 128 /* StringLiteral */ && !(t & 1024 /* EnumLiteral */) &&
48646                 source.value === target.value)
48647                 return true;
48648             if (s & 296 /* NumberLike */ && t & 8 /* Number */)
48649                 return true;
48650             if (s & 256 /* NumberLiteral */ && s & 1024 /* EnumLiteral */ &&
48651                 t & 256 /* NumberLiteral */ && !(t & 1024 /* EnumLiteral */) &&
48652                 source.value === target.value)
48653                 return true;
48654             if (s & 2112 /* BigIntLike */ && t & 64 /* BigInt */)
48655                 return true;
48656             if (s & 528 /* BooleanLike */ && t & 16 /* Boolean */)
48657                 return true;
48658             if (s & 12288 /* ESSymbolLike */ && t & 4096 /* ESSymbol */)
48659                 return true;
48660             if (s & 32 /* Enum */ && t & 32 /* Enum */ && isEnumTypeRelatedTo(source.symbol, target.symbol, errorReporter))
48661                 return true;
48662             if (s & 1024 /* EnumLiteral */ && t & 1024 /* EnumLiteral */) {
48663                 if (s & 1048576 /* Union */ && t & 1048576 /* Union */ && isEnumTypeRelatedTo(source.symbol, target.symbol, errorReporter))
48664                     return true;
48665                 if (s & 2944 /* Literal */ && t & 2944 /* Literal */ &&
48666                     source.value === target.value &&
48667                     isEnumTypeRelatedTo(getParentOfSymbol(source.symbol), getParentOfSymbol(target.symbol), errorReporter))
48668                     return true;
48669             }
48670             if (s & 32768 /* Undefined */ && (!strictNullChecks || t & (32768 /* Undefined */ | 16384 /* Void */)))
48671                 return true;
48672             if (s & 65536 /* Null */ && (!strictNullChecks || t & 65536 /* Null */))
48673                 return true;
48674             if (s & 524288 /* Object */ && t & 67108864 /* NonPrimitive */)
48675                 return true;
48676             if (relation === assignableRelation || relation === comparableRelation) {
48677                 if (s & 1 /* Any */)
48678                     return true;
48679                 // Type number or any numeric literal type is assignable to any numeric enum type or any
48680                 // numeric enum literal type. This rule exists for backwards compatibility reasons because
48681                 // bit-flag enum types sometimes look like literal enum types with numeric literal values.
48682                 if (s & (8 /* Number */ | 256 /* NumberLiteral */) && !(s & 1024 /* EnumLiteral */) && (t & 32 /* Enum */ || t & 256 /* NumberLiteral */ && t & 1024 /* EnumLiteral */))
48683                     return true;
48684             }
48685             return false;
48686         }
48687         function isTypeRelatedTo(source, target, relation) {
48688             if (isFreshLiteralType(source)) {
48689                 source = source.regularType;
48690             }
48691             if (isFreshLiteralType(target)) {
48692                 target = target.regularType;
48693             }
48694             if (source === target) {
48695                 return true;
48696             }
48697             if (relation !== identityRelation) {
48698                 if (relation === comparableRelation && !(target.flags & 131072 /* Never */) && isSimpleTypeRelatedTo(target, source, relation) || isSimpleTypeRelatedTo(source, target, relation)) {
48699                     return true;
48700                 }
48701             }
48702             else {
48703                 if (!(source.flags & 3145728 /* UnionOrIntersection */) && !(target.flags & 3145728 /* UnionOrIntersection */) &&
48704                     source.flags !== target.flags && !(source.flags & 66584576 /* Substructure */))
48705                     return false;
48706             }
48707             if (source.flags & 524288 /* Object */ && target.flags & 524288 /* Object */) {
48708                 var related = relation.get(getRelationKey(source, target, 0 /* None */, relation));
48709                 if (related !== undefined) {
48710                     return !!(related & 1 /* Succeeded */);
48711                 }
48712             }
48713             if (source.flags & 66846720 /* StructuredOrInstantiable */ || target.flags & 66846720 /* StructuredOrInstantiable */) {
48714                 return checkTypeRelatedTo(source, target, relation, /*errorNode*/ undefined);
48715             }
48716             return false;
48717         }
48718         function isIgnoredJsxProperty(source, sourceProp) {
48719             return ts.getObjectFlags(source) & 4096 /* JsxAttributes */ && !isUnhyphenatedJsxName(sourceProp.escapedName);
48720         }
48721         function getNormalizedType(type, writing) {
48722             while (true) {
48723                 var t = isFreshLiteralType(type) ? type.regularType :
48724                     ts.getObjectFlags(type) & 4 /* Reference */ && type.node ? createTypeReference(type.target, getTypeArguments(type)) :
48725                         type.flags & 3145728 /* UnionOrIntersection */ ? getReducedType(type) :
48726                             type.flags & 33554432 /* Substitution */ ? writing ? type.baseType : type.substitute :
48727                                 type.flags & 25165824 /* Simplifiable */ ? getSimplifiedType(type, writing) :
48728                                     type;
48729                 if (t === type)
48730                     break;
48731                 type = t;
48732             }
48733             return type;
48734         }
48735         /**
48736          * Checks if 'source' is related to 'target' (e.g.: is a assignable to).
48737          * @param source The left-hand-side of the relation.
48738          * @param target The right-hand-side of the relation.
48739          * @param relation The relation considered. One of 'identityRelation', 'subtypeRelation', 'assignableRelation', or 'comparableRelation'.
48740          * Used as both to determine which checks are performed and as a cache of previously computed results.
48741          * @param errorNode The suggested node upon which all errors will be reported, if defined. This may or may not be the actual node used.
48742          * @param headMessage If the error chain should be prepended by a head message, then headMessage will be used.
48743          * @param containingMessageChain A chain of errors to prepend any new errors found.
48744          * @param errorOutputContainer Return the diagnostic. Do not log if 'skipLogging' is truthy.
48745          */
48746         function checkTypeRelatedTo(source, target, relation, errorNode, headMessage, containingMessageChain, errorOutputContainer) {
48747             var errorInfo;
48748             var relatedInfo;
48749             var maybeKeys;
48750             var sourceStack;
48751             var targetStack;
48752             var maybeCount = 0;
48753             var depth = 0;
48754             var expandingFlags = 0 /* None */;
48755             var overflow = false;
48756             var overrideNextErrorInfo = 0; // How many `reportRelationError` calls should be skipped in the elaboration pyramid
48757             var lastSkippedInfo;
48758             var incompatibleStack = [];
48759             var inPropertyCheck = false;
48760             ts.Debug.assert(relation !== identityRelation || !errorNode, "no error reporting in identity checking");
48761             var result = isRelatedTo(source, target, /*reportErrors*/ !!errorNode, headMessage);
48762             if (incompatibleStack.length) {
48763                 reportIncompatibleStack();
48764             }
48765             if (overflow) {
48766                 var diag = error(errorNode || currentNode, ts.Diagnostics.Excessive_stack_depth_comparing_types_0_and_1, typeToString(source), typeToString(target));
48767                 if (errorOutputContainer) {
48768                     (errorOutputContainer.errors || (errorOutputContainer.errors = [])).push(diag);
48769                 }
48770             }
48771             else if (errorInfo) {
48772                 if (containingMessageChain) {
48773                     var chain = containingMessageChain();
48774                     if (chain) {
48775                         ts.concatenateDiagnosticMessageChains(chain, errorInfo);
48776                         errorInfo = chain;
48777                     }
48778                 }
48779                 var relatedInformation = void 0;
48780                 // Check if we should issue an extra diagnostic to produce a quickfix for a slightly incorrect import statement
48781                 if (headMessage && errorNode && !result && source.symbol) {
48782                     var links = getSymbolLinks(source.symbol);
48783                     if (links.originatingImport && !ts.isImportCall(links.originatingImport)) {
48784                         var helpfulRetry = checkTypeRelatedTo(getTypeOfSymbol(links.target), target, relation, /*errorNode*/ undefined);
48785                         if (helpfulRetry) {
48786                             // Likely an incorrect import. Issue a helpful diagnostic to produce a quickfix to change the import
48787                             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);
48788                             relatedInformation = ts.append(relatedInformation, diag_1); // Cause the error to appear with the error that triggered it
48789                         }
48790                     }
48791                 }
48792                 var diag = ts.createDiagnosticForNodeFromMessageChain(errorNode, errorInfo, relatedInformation);
48793                 if (relatedInfo) {
48794                     ts.addRelatedInfo.apply(void 0, __spreadArrays([diag], relatedInfo));
48795                 }
48796                 if (errorOutputContainer) {
48797                     (errorOutputContainer.errors || (errorOutputContainer.errors = [])).push(diag);
48798                 }
48799                 if (!errorOutputContainer || !errorOutputContainer.skipLogging) {
48800                     diagnostics.add(diag);
48801                 }
48802             }
48803             if (errorNode && errorOutputContainer && errorOutputContainer.skipLogging && result === 0 /* False */) {
48804                 ts.Debug.assert(!!errorOutputContainer.errors, "missed opportunity to interact with error.");
48805             }
48806             return result !== 0 /* False */;
48807             function resetErrorInfo(saved) {
48808                 errorInfo = saved.errorInfo;
48809                 lastSkippedInfo = saved.lastSkippedInfo;
48810                 incompatibleStack = saved.incompatibleStack;
48811                 overrideNextErrorInfo = saved.overrideNextErrorInfo;
48812                 relatedInfo = saved.relatedInfo;
48813             }
48814             function captureErrorCalculationState() {
48815                 return {
48816                     errorInfo: errorInfo,
48817                     lastSkippedInfo: lastSkippedInfo,
48818                     incompatibleStack: incompatibleStack.slice(),
48819                     overrideNextErrorInfo: overrideNextErrorInfo,
48820                     relatedInfo: !relatedInfo ? undefined : relatedInfo.slice()
48821                 };
48822             }
48823             function reportIncompatibleError(message, arg0, arg1, arg2, arg3) {
48824                 overrideNextErrorInfo++; // Suppress the next relation error
48825                 lastSkippedInfo = undefined; // Reset skipped info cache
48826                 incompatibleStack.push([message, arg0, arg1, arg2, arg3]);
48827             }
48828             function reportIncompatibleStack() {
48829                 var stack = incompatibleStack;
48830                 incompatibleStack = [];
48831                 var info = lastSkippedInfo;
48832                 lastSkippedInfo = undefined;
48833                 if (stack.length === 1) {
48834                     reportError.apply(void 0, stack[0]);
48835                     if (info) {
48836                         // Actually do the last relation error
48837                         reportRelationError.apply(void 0, __spreadArrays([/*headMessage*/ undefined], info));
48838                     }
48839                     return;
48840                 }
48841                 // The first error will be the innermost, while the last will be the outermost - so by popping off the end,
48842                 // we can build from left to right
48843                 var path = "";
48844                 var secondaryRootErrors = [];
48845                 while (stack.length) {
48846                     var _a = stack.pop(), msg = _a[0], args = _a.slice(1);
48847                     switch (msg.code) {
48848                         case ts.Diagnostics.Types_of_property_0_are_incompatible.code: {
48849                             // Parenthesize a `new` if there is one
48850                             if (path.indexOf("new ") === 0) {
48851                                 path = "(" + path + ")";
48852                             }
48853                             var str = "" + args[0];
48854                             // If leading, just print back the arg (irrespective of if it's a valid identifier)
48855                             if (path.length === 0) {
48856                                 path = "" + str;
48857                             }
48858                             // Otherwise write a dotted name if possible
48859                             else if (ts.isIdentifierText(str, compilerOptions.target)) {
48860                                 path = path + "." + str;
48861                             }
48862                             // Failing that, check if the name is already a computed name
48863                             else if (str[0] === "[" && str[str.length - 1] === "]") {
48864                                 path = "" + path + str;
48865                             }
48866                             // And finally write out a computed name as a last resort
48867                             else {
48868                                 path = path + "[" + str + "]";
48869                             }
48870                             break;
48871                         }
48872                         case ts.Diagnostics.Call_signature_return_types_0_and_1_are_incompatible.code:
48873                         case ts.Diagnostics.Construct_signature_return_types_0_and_1_are_incompatible.code:
48874                         case ts.Diagnostics.Call_signatures_with_no_arguments_have_incompatible_return_types_0_and_1.code:
48875                         case ts.Diagnostics.Construct_signatures_with_no_arguments_have_incompatible_return_types_0_and_1.code: {
48876                             if (path.length === 0) {
48877                                 // Don't flatten signature compatability errors at the start of a chain - instead prefer
48878                                 // to unify (the with no arguments bit is excessive for printback) and print them back
48879                                 var mappedMsg = msg;
48880                                 if (msg.code === ts.Diagnostics.Call_signatures_with_no_arguments_have_incompatible_return_types_0_and_1.code) {
48881                                     mappedMsg = ts.Diagnostics.Call_signature_return_types_0_and_1_are_incompatible;
48882                                 }
48883                                 else if (msg.code === ts.Diagnostics.Construct_signatures_with_no_arguments_have_incompatible_return_types_0_and_1.code) {
48884                                     mappedMsg = ts.Diagnostics.Construct_signature_return_types_0_and_1_are_incompatible;
48885                                 }
48886                                 secondaryRootErrors.unshift([mappedMsg, args[0], args[1]]);
48887                             }
48888                             else {
48889                                 var prefix = (msg.code === ts.Diagnostics.Construct_signature_return_types_0_and_1_are_incompatible.code ||
48890                                     msg.code === ts.Diagnostics.Construct_signatures_with_no_arguments_have_incompatible_return_types_0_and_1.code)
48891                                     ? "new "
48892                                     : "";
48893                                 var params = (msg.code === ts.Diagnostics.Call_signatures_with_no_arguments_have_incompatible_return_types_0_and_1.code ||
48894                                     msg.code === ts.Diagnostics.Construct_signatures_with_no_arguments_have_incompatible_return_types_0_and_1.code)
48895                                     ? ""
48896                                     : "...";
48897                                 path = "" + prefix + path + "(" + params + ")";
48898                             }
48899                             break;
48900                         }
48901                         default:
48902                             return ts.Debug.fail("Unhandled Diagnostic: " + msg.code);
48903                     }
48904                 }
48905                 if (path) {
48906                     reportError(path[path.length - 1] === ")"
48907                         ? ts.Diagnostics.The_types_returned_by_0_are_incompatible_between_these_types
48908                         : ts.Diagnostics.The_types_of_0_are_incompatible_between_these_types, path);
48909                 }
48910                 else {
48911                     // Remove the innermost secondary error as it will duplicate the error already reported by `reportRelationError` on entry
48912                     secondaryRootErrors.shift();
48913                 }
48914                 for (var _i = 0, secondaryRootErrors_1 = secondaryRootErrors; _i < secondaryRootErrors_1.length; _i++) {
48915                     var _b = secondaryRootErrors_1[_i], msg = _b[0], args = _b.slice(1);
48916                     var originalValue = msg.elidedInCompatabilityPyramid;
48917                     msg.elidedInCompatabilityPyramid = false; // Teporarily override elision to ensure error is reported
48918                     reportError.apply(void 0, __spreadArrays([msg], args));
48919                     msg.elidedInCompatabilityPyramid = originalValue;
48920                 }
48921                 if (info) {
48922                     // Actually do the last relation error
48923                     reportRelationError.apply(void 0, __spreadArrays([/*headMessage*/ undefined], info));
48924                 }
48925             }
48926             function reportError(message, arg0, arg1, arg2, arg3) {
48927                 ts.Debug.assert(!!errorNode);
48928                 if (incompatibleStack.length)
48929                     reportIncompatibleStack();
48930                 if (message.elidedInCompatabilityPyramid)
48931                     return;
48932                 errorInfo = ts.chainDiagnosticMessages(errorInfo, message, arg0, arg1, arg2, arg3);
48933             }
48934             function associateRelatedInfo(info) {
48935                 ts.Debug.assert(!!errorInfo);
48936                 if (!relatedInfo) {
48937                     relatedInfo = [info];
48938                 }
48939                 else {
48940                     relatedInfo.push(info);
48941                 }
48942             }
48943             function reportRelationError(message, source, target) {
48944                 if (incompatibleStack.length)
48945                     reportIncompatibleStack();
48946                 var _a = getTypeNamesForErrorDisplay(source, target), sourceType = _a[0], targetType = _a[1];
48947                 if (target.flags & 262144 /* TypeParameter */) {
48948                     var constraint = getBaseConstraintOfType(target);
48949                     var constraintElab = constraint && isTypeAssignableTo(source, constraint);
48950                     if (constraintElab) {
48951                         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));
48952                     }
48953                     else {
48954                         reportError(ts.Diagnostics._0_could_be_instantiated_with_an_arbitrary_type_which_could_be_unrelated_to_1, targetType, sourceType);
48955                     }
48956                 }
48957                 if (!message) {
48958                     if (relation === comparableRelation) {
48959                         message = ts.Diagnostics.Type_0_is_not_comparable_to_type_1;
48960                     }
48961                     else if (sourceType === targetType) {
48962                         message = ts.Diagnostics.Type_0_is_not_assignable_to_type_1_Two_different_types_with_this_name_exist_but_they_are_unrelated;
48963                     }
48964                     else {
48965                         message = ts.Diagnostics.Type_0_is_not_assignable_to_type_1;
48966                     }
48967                 }
48968                 reportError(message, sourceType, targetType);
48969             }
48970             function tryElaborateErrorsForPrimitivesAndObjects(source, target) {
48971                 var sourceType = symbolValueDeclarationIsContextSensitive(source.symbol) ? typeToString(source, source.symbol.valueDeclaration) : typeToString(source);
48972                 var targetType = symbolValueDeclarationIsContextSensitive(target.symbol) ? typeToString(target, target.symbol.valueDeclaration) : typeToString(target);
48973                 if ((globalStringType === source && stringType === target) ||
48974                     (globalNumberType === source && numberType === target) ||
48975                     (globalBooleanType === source && booleanType === target) ||
48976                     (getGlobalESSymbolType(/*reportErrors*/ false) === source && esSymbolType === target)) {
48977                     reportError(ts.Diagnostics._0_is_a_primitive_but_1_is_a_wrapper_object_Prefer_using_0_when_possible, targetType, sourceType);
48978                 }
48979             }
48980             /**
48981              * Try and elaborate array and tuple errors. Returns false
48982              * if we have found an elaboration, or we should ignore
48983              * any other elaborations when relating the `source` and
48984              * `target` types.
48985              */
48986             function tryElaborateArrayLikeErrors(source, target, reportErrors) {
48987                 /**
48988                  * The spec for elaboration is:
48989                  * - If the source is a readonly tuple and the target is a mutable array or tuple, elaborate on mutability and skip property elaborations.
48990                  * - If the source is a tuple then skip property elaborations if the target is an array or tuple.
48991                  * - If the source is a readonly array and the target is a mutable array or tuple, elaborate on mutability and skip property elaborations.
48992                  * - If the source an array then skip property elaborations if the target is a tuple.
48993                  */
48994                 if (isTupleType(source)) {
48995                     if (source.target.readonly && isMutableArrayOrTuple(target)) {
48996                         if (reportErrors) {
48997                             reportError(ts.Diagnostics.The_type_0_is_readonly_and_cannot_be_assigned_to_the_mutable_type_1, typeToString(source), typeToString(target));
48998                         }
48999                         return false;
49000                     }
49001                     return isTupleType(target) || isArrayType(target);
49002                 }
49003                 if (isReadonlyArrayType(source) && isMutableArrayOrTuple(target)) {
49004                     if (reportErrors) {
49005                         reportError(ts.Diagnostics.The_type_0_is_readonly_and_cannot_be_assigned_to_the_mutable_type_1, typeToString(source), typeToString(target));
49006                     }
49007                     return false;
49008                 }
49009                 if (isTupleType(target)) {
49010                     return isArrayType(source);
49011                 }
49012                 return true;
49013             }
49014             /**
49015              * Compare two types and return
49016              * * Ternary.True if they are related with no assumptions,
49017              * * Ternary.Maybe if they are related with assumptions of other relationships, or
49018              * * Ternary.False if they are not related.
49019              */
49020             function isRelatedTo(originalSource, originalTarget, reportErrors, headMessage, intersectionState) {
49021                 if (reportErrors === void 0) { reportErrors = false; }
49022                 if (intersectionState === void 0) { intersectionState = 0 /* None */; }
49023                 // Before normalization: if `source` is type an object type, and `target` is primitive,
49024                 // skip all the checks we don't need and just return `isSimpleTypeRelatedTo` result
49025                 if (originalSource.flags & 524288 /* Object */ && originalTarget.flags & 131068 /* Primitive */) {
49026                     if (isSimpleTypeRelatedTo(originalSource, originalTarget, relation, reportErrors ? reportError : undefined)) {
49027                         return -1 /* True */;
49028                     }
49029                     reportErrorResults(originalSource, originalTarget, 0 /* False */, !!(ts.getObjectFlags(originalSource) & 4096 /* JsxAttributes */));
49030                     return 0 /* False */;
49031                 }
49032                 // Normalize the source and target types: Turn fresh literal types into regular literal types,
49033                 // turn deferred type references into regular type references, simplify indexed access and
49034                 // conditional types, and resolve substitution types to either the substitution (on the source
49035                 // side) or the type variable (on the target side).
49036                 var source = getNormalizedType(originalSource, /*writing*/ false);
49037                 var target = getNormalizedType(originalTarget, /*writing*/ true);
49038                 if (source === target)
49039                     return -1 /* True */;
49040                 if (relation === identityRelation) {
49041                     return isIdenticalTo(source, target);
49042                 }
49043                 // We fastpath comparing a type parameter to exactly its constraint, as this is _super_ common,
49044                 // and otherwise, for type parameters in large unions, causes us to need to compare the union to itself,
49045                 // as we break down the _target_ union first, _then_ get the source constraint - so for every
49046                 // member of the target, we attempt to find a match in the source. This avoids that in cases where
49047                 // the target is exactly the constraint.
49048                 if (source.flags & 262144 /* TypeParameter */ && getConstraintOfType(source) === target) {
49049                     return -1 /* True */;
49050                 }
49051                 // Try to see if we're relating something like `Foo` -> `Bar | null | undefined`.
49052                 // If so, reporting the `null` and `undefined` in the type is hardly useful.
49053                 // First, see if we're even relating an object type to a union.
49054                 // Then see if the target is stripped down to a single non-union type.
49055                 // Note
49056                 //  * We actually want to remove null and undefined naively here (rather than using getNonNullableType),
49057                 //    since we don't want to end up with a worse error like "`Foo` is not assignable to `NonNullable<T>`"
49058                 //    when dealing with generics.
49059                 //  * We also don't deal with primitive source types, since we already halt elaboration below.
49060                 if (target.flags & 1048576 /* Union */ && source.flags & 524288 /* Object */ &&
49061                     target.types.length <= 3 && maybeTypeOfKind(target, 98304 /* Nullable */)) {
49062                     var nullStrippedTarget = extractTypesOfKind(target, ~98304 /* Nullable */);
49063                     if (!(nullStrippedTarget.flags & (1048576 /* Union */ | 131072 /* Never */))) {
49064                         if (source === nullStrippedTarget)
49065                             return -1 /* True */;
49066                         target = nullStrippedTarget;
49067                     }
49068                 }
49069                 if (relation === comparableRelation && !(target.flags & 131072 /* Never */) && isSimpleTypeRelatedTo(target, source, relation) ||
49070                     isSimpleTypeRelatedTo(source, target, relation, reportErrors ? reportError : undefined))
49071                     return -1 /* True */;
49072                 var isComparingJsxAttributes = !!(ts.getObjectFlags(source) & 4096 /* JsxAttributes */);
49073                 var isPerformingExcessPropertyChecks = !(intersectionState & 2 /* Target */) && (isObjectLiteralType(source) && ts.getObjectFlags(source) & 32768 /* FreshLiteral */);
49074                 if (isPerformingExcessPropertyChecks) {
49075                     if (hasExcessProperties(source, target, reportErrors)) {
49076                         if (reportErrors) {
49077                             reportRelationError(headMessage, source, target);
49078                         }
49079                         return 0 /* False */;
49080                     }
49081                 }
49082                 var isPerformingCommonPropertyChecks = relation !== comparableRelation && !(intersectionState & 2 /* Target */) &&
49083                     source.flags & (131068 /* Primitive */ | 524288 /* Object */ | 2097152 /* Intersection */) && source !== globalObjectType &&
49084                     target.flags & (524288 /* Object */ | 2097152 /* Intersection */) && isWeakType(target) &&
49085                     (getPropertiesOfType(source).length > 0 || typeHasCallOrConstructSignatures(source));
49086                 if (isPerformingCommonPropertyChecks && !hasCommonProperties(source, target, isComparingJsxAttributes)) {
49087                     if (reportErrors) {
49088                         var calls = getSignaturesOfType(source, 0 /* Call */);
49089                         var constructs = getSignaturesOfType(source, 1 /* Construct */);
49090                         if (calls.length > 0 && isRelatedTo(getReturnTypeOfSignature(calls[0]), target, /*reportErrors*/ false) ||
49091                             constructs.length > 0 && isRelatedTo(getReturnTypeOfSignature(constructs[0]), target, /*reportErrors*/ false)) {
49092                             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));
49093                         }
49094                         else {
49095                             reportError(ts.Diagnostics.Type_0_has_no_properties_in_common_with_type_1, typeToString(source), typeToString(target));
49096                         }
49097                     }
49098                     return 0 /* False */;
49099                 }
49100                 var result = 0 /* False */;
49101                 var saveErrorInfo = captureErrorCalculationState();
49102                 // Note that these checks are specifically ordered to produce correct results. In particular,
49103                 // we need to deconstruct unions before intersections (because unions are always at the top),
49104                 // and we need to handle "each" relations before "some" relations for the same kind of type.
49105                 if (source.flags & 1048576 /* Union */) {
49106                     result = relation === comparableRelation ?
49107                         someTypeRelatedToType(source, target, reportErrors && !(source.flags & 131068 /* Primitive */), intersectionState) :
49108                         eachTypeRelatedToType(source, target, reportErrors && !(source.flags & 131068 /* Primitive */), intersectionState);
49109                 }
49110                 else {
49111                     if (target.flags & 1048576 /* Union */) {
49112                         result = typeRelatedToSomeType(getRegularTypeOfObjectLiteral(source), target, reportErrors && !(source.flags & 131068 /* Primitive */) && !(target.flags & 131068 /* Primitive */));
49113                     }
49114                     else if (target.flags & 2097152 /* Intersection */) {
49115                         result = typeRelatedToEachType(getRegularTypeOfObjectLiteral(source), target, reportErrors, 2 /* Target */);
49116                     }
49117                     else if (source.flags & 2097152 /* Intersection */) {
49118                         // Check to see if any constituents of the intersection are immediately related to the target.
49119                         //
49120                         // Don't report errors though. Checking whether a constituent is related to the source is not actually
49121                         // useful and leads to some confusing error messages. Instead it is better to let the below checks
49122                         // take care of this, or to not elaborate at all. For instance,
49123                         //
49124                         //    - For an object type (such as 'C = A & B'), users are usually more interested in structural errors.
49125                         //
49126                         //    - For a union type (such as '(A | B) = (C & D)'), it's better to hold onto the whole intersection
49127                         //          than to report that 'D' is not assignable to 'A' or 'B'.
49128                         //
49129                         //    - For a primitive type or type parameter (such as 'number = A & B') there is no point in
49130                         //          breaking the intersection apart.
49131                         result = someTypeRelatedToType(source, target, /*reportErrors*/ false, 1 /* Source */);
49132                     }
49133                     if (!result && (source.flags & 66846720 /* StructuredOrInstantiable */ || target.flags & 66846720 /* StructuredOrInstantiable */)) {
49134                         if (result = recursiveTypeRelatedTo(source, target, reportErrors, intersectionState)) {
49135                             resetErrorInfo(saveErrorInfo);
49136                         }
49137                     }
49138                 }
49139                 if (!result && source.flags & (2097152 /* Intersection */ | 262144 /* TypeParameter */)) {
49140                     // The combined constraint of an intersection type is the intersection of the constraints of
49141                     // the constituents. When an intersection type contains instantiable types with union type
49142                     // constraints, there are situations where we need to examine the combined constraint. One is
49143                     // when the target is a union type. Another is when the intersection contains types belonging
49144                     // to one of the disjoint domains. For example, given type variables T and U, each with the
49145                     // constraint 'string | number', the combined constraint of 'T & U' is 'string | number' and
49146                     // we need to check this constraint against a union on the target side. Also, given a type
49147                     // variable V constrained to 'string | number', 'V & number' has a combined constraint of
49148                     // 'string & number | number & number' which reduces to just 'number'.
49149                     // This also handles type parameters, as a type parameter with a union constraint compared against a union
49150                     // needs to have its constraint hoisted into an intersection with said type parameter, this way
49151                     // the type param can be compared with itself in the target (with the influence of its constraint to match other parts)
49152                     // For example, if `T extends 1 | 2` and `U extends 2 | 3` and we compare `T & U` to `T & U & (1 | 2 | 3)`
49153                     var constraint = getEffectiveConstraintOfIntersection(source.flags & 2097152 /* Intersection */ ? source.types : [source], !!(target.flags & 1048576 /* Union */));
49154                     if (constraint && (source.flags & 2097152 /* Intersection */ || target.flags & 1048576 /* Union */)) {
49155                         if (everyType(constraint, function (c) { return c !== source; })) { // Skip comparison if expansion contains the source itself
49156                             // TODO: Stack errors so we get a pyramid for the "normal" comparison above, _and_ a second for this
49157                             if (result = isRelatedTo(constraint, target, /*reportErrors*/ false, /*headMessage*/ undefined, intersectionState)) {
49158                                 resetErrorInfo(saveErrorInfo);
49159                             }
49160                         }
49161                     }
49162                 }
49163                 // For certain combinations involving intersections and optional, excess, or mismatched properties we need
49164                 // an extra property check where the intersection is viewed as a single object. The following are motivating
49165                 // examples that all should be errors, but aren't without this extra property check:
49166                 //
49167                 //   let obj: { a: { x: string } } & { c: number } = { a: { x: 'hello', y: 2 }, c: 5 };  // Nested excess property
49168                 //
49169                 //   declare let wrong: { a: { y: string } };
49170                 //   let weak: { a?: { x?: number } } & { c?: string } = wrong;  // Nested weak object type
49171                 //
49172                 //   function foo<T extends object>(x: { a?: string }, y: T & { a: boolean }) {
49173                 //     x = y;  // Mismatched property in source intersection
49174                 //   }
49175                 //
49176                 // We suppress recursive intersection property checks because they can generate lots of work when relating
49177                 // recursive intersections that are structurally similar but not exactly identical. See #37854.
49178                 if (result && !inPropertyCheck && (target.flags & 2097152 /* Intersection */ && (isPerformingExcessPropertyChecks || isPerformingCommonPropertyChecks) ||
49179                     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 */); }))) {
49180                     inPropertyCheck = true;
49181                     result &= recursiveTypeRelatedTo(source, target, reportErrors, 4 /* PropertyCheck */);
49182                     inPropertyCheck = false;
49183                 }
49184                 reportErrorResults(source, target, result, isComparingJsxAttributes);
49185                 return result;
49186                 function reportErrorResults(source, target, result, isComparingJsxAttributes) {
49187                     if (!result && reportErrors) {
49188                         source = originalSource.aliasSymbol ? originalSource : source;
49189                         target = originalTarget.aliasSymbol ? originalTarget : target;
49190                         var maybeSuppress = overrideNextErrorInfo > 0;
49191                         if (maybeSuppress) {
49192                             overrideNextErrorInfo--;
49193                         }
49194                         if (source.flags & 524288 /* Object */ && target.flags & 524288 /* Object */) {
49195                             var currentError = errorInfo;
49196                             tryElaborateArrayLikeErrors(source, target, reportErrors);
49197                             if (errorInfo !== currentError) {
49198                                 maybeSuppress = !!errorInfo;
49199                             }
49200                         }
49201                         if (source.flags & 524288 /* Object */ && target.flags & 131068 /* Primitive */) {
49202                             tryElaborateErrorsForPrimitivesAndObjects(source, target);
49203                         }
49204                         else if (source.symbol && source.flags & 524288 /* Object */ && globalObjectType === source) {
49205                             reportError(ts.Diagnostics.The_Object_type_is_assignable_to_very_few_other_types_Did_you_mean_to_use_the_any_type_instead);
49206                         }
49207                         else if (isComparingJsxAttributes && target.flags & 2097152 /* Intersection */) {
49208                             var targetTypes = target.types;
49209                             var intrinsicAttributes = getJsxType(JsxNames.IntrinsicAttributes, errorNode);
49210                             var intrinsicClassAttributes = getJsxType(JsxNames.IntrinsicClassAttributes, errorNode);
49211                             if (intrinsicAttributes !== errorType && intrinsicClassAttributes !== errorType &&
49212                                 (ts.contains(targetTypes, intrinsicAttributes) || ts.contains(targetTypes, intrinsicClassAttributes))) {
49213                                 // do not report top error
49214                                 return result;
49215                             }
49216                         }
49217                         else {
49218                             errorInfo = elaborateNeverIntersection(errorInfo, originalTarget);
49219                         }
49220                         if (!headMessage && maybeSuppress) {
49221                             lastSkippedInfo = [source, target];
49222                             // Used by, eg, missing property checking to replace the top-level message with a more informative one
49223                             return result;
49224                         }
49225                         reportRelationError(headMessage, source, target);
49226                     }
49227                 }
49228             }
49229             function isIdenticalTo(source, target) {
49230                 var flags = source.flags & target.flags;
49231                 if (!(flags & 66584576 /* Substructure */)) {
49232                     return 0 /* False */;
49233                 }
49234                 if (flags & 3145728 /* UnionOrIntersection */) {
49235                     var result_5 = eachTypeRelatedToSomeType(source, target);
49236                     if (result_5) {
49237                         result_5 &= eachTypeRelatedToSomeType(target, source);
49238                     }
49239                     return result_5;
49240                 }
49241                 return recursiveTypeRelatedTo(source, target, /*reportErrors*/ false, 0 /* None */);
49242             }
49243             function getTypeOfPropertyInTypes(types, name) {
49244                 var appendPropType = function (propTypes, type) {
49245                     type = getApparentType(type);
49246                     var prop = type.flags & 3145728 /* UnionOrIntersection */ ? getPropertyOfUnionOrIntersectionType(type, name) : getPropertyOfObjectType(type, name);
49247                     var propType = prop && getTypeOfSymbol(prop) || isNumericLiteralName(name) && getIndexTypeOfType(type, 1 /* Number */) || getIndexTypeOfType(type, 0 /* String */) || undefinedType;
49248                     return ts.append(propTypes, propType);
49249                 };
49250                 return getUnionType(ts.reduceLeft(types, appendPropType, /*initial*/ undefined) || ts.emptyArray);
49251             }
49252             function hasExcessProperties(source, target, reportErrors) {
49253                 if (!isExcessPropertyCheckTarget(target) || !noImplicitAny && ts.getObjectFlags(target) & 16384 /* JSLiteral */) {
49254                     return false; // Disable excess property checks on JS literals to simulate having an implicit "index signature" - but only outside of noImplicitAny
49255                 }
49256                 var isComparingJsxAttributes = !!(ts.getObjectFlags(source) & 4096 /* JsxAttributes */);
49257                 if ((relation === assignableRelation || relation === comparableRelation) &&
49258                     (isTypeSubsetOf(globalObjectType, target) || (!isComparingJsxAttributes && isEmptyObjectType(target)))) {
49259                     return false;
49260                 }
49261                 var reducedTarget = target;
49262                 var checkTypes;
49263                 if (target.flags & 1048576 /* Union */) {
49264                     reducedTarget = findMatchingDiscriminantType(source, target, isRelatedTo) || filterPrimitivesIfContainsNonPrimitive(target);
49265                     checkTypes = reducedTarget.flags & 1048576 /* Union */ ? reducedTarget.types : [reducedTarget];
49266                 }
49267                 var _loop_13 = function (prop) {
49268                     if (shouldCheckAsExcessProperty(prop, source.symbol) && !isIgnoredJsxProperty(source, prop)) {
49269                         if (!isKnownProperty(reducedTarget, prop.escapedName, isComparingJsxAttributes)) {
49270                             if (reportErrors) {
49271                                 // Report error in terms of object types in the target as those are the only ones
49272                                 // we check in isKnownProperty.
49273                                 var errorTarget = filterType(reducedTarget, isExcessPropertyCheckTarget);
49274                                 // We know *exactly* where things went wrong when comparing the types.
49275                                 // Use this property as the error node as this will be more helpful in
49276                                 // reasoning about what went wrong.
49277                                 if (!errorNode)
49278                                     return { value: ts.Debug.fail() };
49279                                 if (ts.isJsxAttributes(errorNode) || ts.isJsxOpeningLikeElement(errorNode) || ts.isJsxOpeningLikeElement(errorNode.parent)) {
49280                                     // JsxAttributes has an object-literal flag and undergo same type-assignablity check as normal object-literal.
49281                                     // However, using an object-literal error message will be very confusing to the users so we give different a message.
49282                                     // TODO: Spelling suggestions for excess jsx attributes (needs new diagnostic messages)
49283                                     if (prop.valueDeclaration && ts.isJsxAttribute(prop.valueDeclaration) && ts.getSourceFileOfNode(errorNode) === ts.getSourceFileOfNode(prop.valueDeclaration.name)) {
49284                                         // Note that extraneous children (as in `<NoChild>extra</NoChild>`) don't pass this check,
49285                                         // since `children` is a SyntaxKind.PropertySignature instead of a SyntaxKind.JsxAttribute.
49286                                         errorNode = prop.valueDeclaration.name;
49287                                     }
49288                                     reportError(ts.Diagnostics.Property_0_does_not_exist_on_type_1, symbolToString(prop), typeToString(errorTarget));
49289                                 }
49290                                 else {
49291                                     // use the property's value declaration if the property is assigned inside the literal itself
49292                                     var objectLiteralDeclaration_1 = source.symbol && ts.firstOrUndefined(source.symbol.declarations);
49293                                     var suggestion = void 0;
49294                                     if (prop.valueDeclaration && ts.findAncestor(prop.valueDeclaration, function (d) { return d === objectLiteralDeclaration_1; }) && ts.getSourceFileOfNode(objectLiteralDeclaration_1) === ts.getSourceFileOfNode(errorNode)) {
49295                                         var propDeclaration = prop.valueDeclaration;
49296                                         ts.Debug.assertNode(propDeclaration, ts.isObjectLiteralElementLike);
49297                                         errorNode = propDeclaration;
49298                                         var name = propDeclaration.name;
49299                                         if (ts.isIdentifier(name)) {
49300                                             suggestion = getSuggestionForNonexistentProperty(name, errorTarget);
49301                                         }
49302                                     }
49303                                     if (suggestion !== undefined) {
49304                                         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);
49305                                     }
49306                                     else {
49307                                         reportError(ts.Diagnostics.Object_literal_may_only_specify_known_properties_and_0_does_not_exist_in_type_1, symbolToString(prop), typeToString(errorTarget));
49308                                     }
49309                                 }
49310                             }
49311                             return { value: true };
49312                         }
49313                         if (checkTypes && !isRelatedTo(getTypeOfSymbol(prop), getTypeOfPropertyInTypes(checkTypes, prop.escapedName), reportErrors)) {
49314                             if (reportErrors) {
49315                                 reportIncompatibleError(ts.Diagnostics.Types_of_property_0_are_incompatible, symbolToString(prop));
49316                             }
49317                             return { value: true };
49318                         }
49319                     }
49320                 };
49321                 for (var _i = 0, _a = getPropertiesOfType(source); _i < _a.length; _i++) {
49322                     var prop = _a[_i];
49323                     var state_5 = _loop_13(prop);
49324                     if (typeof state_5 === "object")
49325                         return state_5.value;
49326                 }
49327                 return false;
49328             }
49329             function shouldCheckAsExcessProperty(prop, container) {
49330                 return prop.valueDeclaration && container.valueDeclaration && prop.valueDeclaration.parent === container.valueDeclaration;
49331             }
49332             function eachTypeRelatedToSomeType(source, target) {
49333                 var result = -1 /* True */;
49334                 var sourceTypes = source.types;
49335                 for (var _i = 0, sourceTypes_1 = sourceTypes; _i < sourceTypes_1.length; _i++) {
49336                     var sourceType = sourceTypes_1[_i];
49337                     var related = typeRelatedToSomeType(sourceType, target, /*reportErrors*/ false);
49338                     if (!related) {
49339                         return 0 /* False */;
49340                     }
49341                     result &= related;
49342                 }
49343                 return result;
49344             }
49345             function typeRelatedToSomeType(source, target, reportErrors) {
49346                 var targetTypes = target.types;
49347                 if (target.flags & 1048576 /* Union */ && containsType(targetTypes, source)) {
49348                     return -1 /* True */;
49349                 }
49350                 for (var _i = 0, targetTypes_1 = targetTypes; _i < targetTypes_1.length; _i++) {
49351                     var type = targetTypes_1[_i];
49352                     var related = isRelatedTo(source, type, /*reportErrors*/ false);
49353                     if (related) {
49354                         return related;
49355                     }
49356                 }
49357                 if (reportErrors) {
49358                     var bestMatchingType = getBestMatchingType(source, target, isRelatedTo);
49359                     isRelatedTo(source, bestMatchingType || targetTypes[targetTypes.length - 1], /*reportErrors*/ true);
49360                 }
49361                 return 0 /* False */;
49362             }
49363             function typeRelatedToEachType(source, target, reportErrors, intersectionState) {
49364                 var result = -1 /* True */;
49365                 var targetTypes = target.types;
49366                 for (var _i = 0, targetTypes_2 = targetTypes; _i < targetTypes_2.length; _i++) {
49367                     var targetType = targetTypes_2[_i];
49368                     var related = isRelatedTo(source, targetType, reportErrors, /*headMessage*/ undefined, intersectionState);
49369                     if (!related) {
49370                         return 0 /* False */;
49371                     }
49372                     result &= related;
49373                 }
49374                 return result;
49375             }
49376             function someTypeRelatedToType(source, target, reportErrors, intersectionState) {
49377                 var sourceTypes = source.types;
49378                 if (source.flags & 1048576 /* Union */ && containsType(sourceTypes, target)) {
49379                     return -1 /* True */;
49380                 }
49381                 var len = sourceTypes.length;
49382                 for (var i = 0; i < len; i++) {
49383                     var related = isRelatedTo(sourceTypes[i], target, reportErrors && i === len - 1, /*headMessage*/ undefined, intersectionState);
49384                     if (related) {
49385                         return related;
49386                     }
49387                 }
49388                 return 0 /* False */;
49389             }
49390             function eachTypeRelatedToType(source, target, reportErrors, intersectionState) {
49391                 var result = -1 /* True */;
49392                 var sourceTypes = source.types;
49393                 for (var i = 0; i < sourceTypes.length; i++) {
49394                     var sourceType = sourceTypes[i];
49395                     if (target.flags & 1048576 /* Union */ && target.types.length === sourceTypes.length) {
49396                         // many unions are mappings of one another; in such cases, simply comparing members at the same index can shortcut the comparison
49397                         var related_1 = isRelatedTo(sourceType, target.types[i], /*reportErrors*/ false, /*headMessage*/ undefined, intersectionState);
49398                         if (related_1) {
49399                             result &= related_1;
49400                             continue;
49401                         }
49402                     }
49403                     var related = isRelatedTo(sourceType, target, reportErrors, /*headMessage*/ undefined, intersectionState);
49404                     if (!related) {
49405                         return 0 /* False */;
49406                     }
49407                     result &= related;
49408                 }
49409                 return result;
49410             }
49411             function typeArgumentsRelatedTo(sources, targets, variances, reportErrors, intersectionState) {
49412                 if (sources === void 0) { sources = ts.emptyArray; }
49413                 if (targets === void 0) { targets = ts.emptyArray; }
49414                 if (variances === void 0) { variances = ts.emptyArray; }
49415                 if (sources.length !== targets.length && relation === identityRelation) {
49416                     return 0 /* False */;
49417                 }
49418                 var length = sources.length <= targets.length ? sources.length : targets.length;
49419                 var result = -1 /* True */;
49420                 for (var i = 0; i < length; i++) {
49421                     // When variance information isn't available we default to covariance. This happens
49422                     // in the process of computing variance information for recursive types and when
49423                     // comparing 'this' type arguments.
49424                     var varianceFlags = i < variances.length ? variances[i] : 1 /* Covariant */;
49425                     var variance = varianceFlags & 7 /* VarianceMask */;
49426                     // We ignore arguments for independent type parameters (because they're never witnessed).
49427                     if (variance !== 4 /* Independent */) {
49428                         var s = sources[i];
49429                         var t = targets[i];
49430                         var related = -1 /* True */;
49431                         if (varianceFlags & 8 /* Unmeasurable */) {
49432                             // Even an `Unmeasurable` variance works out without a structural check if the source and target are _identical_.
49433                             // We can't simply assume invariance, because `Unmeasurable` marks nonlinear relations, for example, a relation tained by
49434                             // the `-?` modifier in a mapped type (where, no matter how the inputs are related, the outputs still might not be)
49435                             related = relation === identityRelation ? isRelatedTo(s, t, /*reportErrors*/ false) : compareTypesIdentical(s, t);
49436                         }
49437                         else if (variance === 1 /* Covariant */) {
49438                             related = isRelatedTo(s, t, reportErrors, /*headMessage*/ undefined, intersectionState);
49439                         }
49440                         else if (variance === 2 /* Contravariant */) {
49441                             related = isRelatedTo(t, s, reportErrors, /*headMessage*/ undefined, intersectionState);
49442                         }
49443                         else if (variance === 3 /* Bivariant */) {
49444                             // In the bivariant case we first compare contravariantly without reporting
49445                             // errors. Then, if that doesn't succeed, we compare covariantly with error
49446                             // reporting. Thus, error elaboration will be based on the the covariant check,
49447                             // which is generally easier to reason about.
49448                             related = isRelatedTo(t, s, /*reportErrors*/ false);
49449                             if (!related) {
49450                                 related = isRelatedTo(s, t, reportErrors, /*headMessage*/ undefined, intersectionState);
49451                             }
49452                         }
49453                         else {
49454                             // In the invariant case we first compare covariantly, and only when that
49455                             // succeeds do we proceed to compare contravariantly. Thus, error elaboration
49456                             // will typically be based on the covariant check.
49457                             related = isRelatedTo(s, t, reportErrors, /*headMessage*/ undefined, intersectionState);
49458                             if (related) {
49459                                 related &= isRelatedTo(t, s, reportErrors, /*headMessage*/ undefined, intersectionState);
49460                             }
49461                         }
49462                         if (!related) {
49463                             return 0 /* False */;
49464                         }
49465                         result &= related;
49466                     }
49467                 }
49468                 return result;
49469             }
49470             // Determine if possibly recursive types are related. First, check if the result is already available in the global cache.
49471             // Second, check if we have already started a comparison of the given two types in which case we assume the result to be true.
49472             // Third, check if both types are part of deeply nested chains of generic type instantiations and if so assume the types are
49473             // equal and infinitely expanding. Fourth, if we have reached a depth of 100 nested comparisons, assume we have runaway recursion
49474             // and issue an error. Otherwise, actually compare the structure of the two types.
49475             function recursiveTypeRelatedTo(source, target, reportErrors, intersectionState) {
49476                 if (overflow) {
49477                     return 0 /* False */;
49478                 }
49479                 var id = getRelationKey(source, target, intersectionState | (inPropertyCheck ? 8 /* InPropertyCheck */ : 0), relation);
49480                 var entry = relation.get(id);
49481                 if (entry !== undefined) {
49482                     if (reportErrors && entry & 2 /* Failed */ && !(entry & 4 /* Reported */)) {
49483                         // We are elaborating errors and the cached result is an unreported failure. The result will be reported
49484                         // as a failure, and should be updated as a reported failure by the bottom of this function.
49485                     }
49486                     else {
49487                         if (outofbandVarianceMarkerHandler) {
49488                             // We're in the middle of variance checking - integrate any unmeasurable/unreliable flags from this cached component
49489                             var saved = entry & 24 /* ReportsMask */;
49490                             if (saved & 8 /* ReportsUnmeasurable */) {
49491                                 instantiateType(source, makeFunctionTypeMapper(reportUnmeasurableMarkers));
49492                             }
49493                             if (saved & 16 /* ReportsUnreliable */) {
49494                                 instantiateType(source, makeFunctionTypeMapper(reportUnreliableMarkers));
49495                             }
49496                         }
49497                         return entry & 1 /* Succeeded */ ? -1 /* True */ : 0 /* False */;
49498                     }
49499                 }
49500                 if (!maybeKeys) {
49501                     maybeKeys = [];
49502                     sourceStack = [];
49503                     targetStack = [];
49504                 }
49505                 else {
49506                     for (var i = 0; i < maybeCount; i++) {
49507                         // If source and target are already being compared, consider them related with assumptions
49508                         if (id === maybeKeys[i]) {
49509                             return 1 /* Maybe */;
49510                         }
49511                     }
49512                     if (depth === 100) {
49513                         overflow = true;
49514                         return 0 /* False */;
49515                     }
49516                 }
49517                 var maybeStart = maybeCount;
49518                 maybeKeys[maybeCount] = id;
49519                 maybeCount++;
49520                 sourceStack[depth] = source;
49521                 targetStack[depth] = target;
49522                 depth++;
49523                 var saveExpandingFlags = expandingFlags;
49524                 if (!(expandingFlags & 1 /* Source */) && isDeeplyNestedType(source, sourceStack, depth))
49525                     expandingFlags |= 1 /* Source */;
49526                 if (!(expandingFlags & 2 /* Target */) && isDeeplyNestedType(target, targetStack, depth))
49527                     expandingFlags |= 2 /* Target */;
49528                 var originalHandler;
49529                 var propagatingVarianceFlags = 0;
49530                 if (outofbandVarianceMarkerHandler) {
49531                     originalHandler = outofbandVarianceMarkerHandler;
49532                     outofbandVarianceMarkerHandler = function (onlyUnreliable) {
49533                         propagatingVarianceFlags |= onlyUnreliable ? 16 /* ReportsUnreliable */ : 8 /* ReportsUnmeasurable */;
49534                         return originalHandler(onlyUnreliable);
49535                     };
49536                 }
49537                 var result = expandingFlags !== 3 /* Both */ ? structuredTypeRelatedTo(source, target, reportErrors, intersectionState) : 1 /* Maybe */;
49538                 if (outofbandVarianceMarkerHandler) {
49539                     outofbandVarianceMarkerHandler = originalHandler;
49540                 }
49541                 expandingFlags = saveExpandingFlags;
49542                 depth--;
49543                 if (result) {
49544                     if (result === -1 /* True */ || depth === 0) {
49545                         // If result is definitely true, record all maybe keys as having succeeded
49546                         for (var i = maybeStart; i < maybeCount; i++) {
49547                             relation.set(maybeKeys[i], 1 /* Succeeded */ | propagatingVarianceFlags);
49548                         }
49549                         maybeCount = maybeStart;
49550                     }
49551                 }
49552                 else {
49553                     // A false result goes straight into global cache (when something is false under
49554                     // assumptions it will also be false without assumptions)
49555                     relation.set(id, (reportErrors ? 4 /* Reported */ : 0) | 2 /* Failed */ | propagatingVarianceFlags);
49556                     maybeCount = maybeStart;
49557                 }
49558                 return result;
49559             }
49560             function structuredTypeRelatedTo(source, target, reportErrors, intersectionState) {
49561                 if (intersectionState & 4 /* PropertyCheck */) {
49562                     return propertiesRelatedTo(source, target, reportErrors, /*excludedProperties*/ undefined, 0 /* None */);
49563                 }
49564                 var flags = source.flags & target.flags;
49565                 if (relation === identityRelation && !(flags & 524288 /* Object */)) {
49566                     if (flags & 4194304 /* Index */) {
49567                         return isRelatedTo(source.type, target.type, /*reportErrors*/ false);
49568                     }
49569                     var result_6 = 0 /* False */;
49570                     if (flags & 8388608 /* IndexedAccess */) {
49571                         if (result_6 = isRelatedTo(source.objectType, target.objectType, /*reportErrors*/ false)) {
49572                             if (result_6 &= isRelatedTo(source.indexType, target.indexType, /*reportErrors*/ false)) {
49573                                 return result_6;
49574                             }
49575                         }
49576                     }
49577                     if (flags & 16777216 /* Conditional */) {
49578                         if (source.root.isDistributive === target.root.isDistributive) {
49579                             if (result_6 = isRelatedTo(source.checkType, target.checkType, /*reportErrors*/ false)) {
49580                                 if (result_6 &= isRelatedTo(source.extendsType, target.extendsType, /*reportErrors*/ false)) {
49581                                     if (result_6 &= isRelatedTo(getTrueTypeFromConditionalType(source), getTrueTypeFromConditionalType(target), /*reportErrors*/ false)) {
49582                                         if (result_6 &= isRelatedTo(getFalseTypeFromConditionalType(source), getFalseTypeFromConditionalType(target), /*reportErrors*/ false)) {
49583                                             return result_6;
49584                                         }
49585                                     }
49586                                 }
49587                             }
49588                         }
49589                     }
49590                     if (flags & 33554432 /* Substitution */) {
49591                         return isRelatedTo(source.substitute, target.substitute, /*reportErrors*/ false);
49592                     }
49593                     return 0 /* False */;
49594                 }
49595                 var result;
49596                 var originalErrorInfo;
49597                 var varianceCheckFailed = false;
49598                 var saveErrorInfo = captureErrorCalculationState();
49599                 // We limit alias variance probing to only object and conditional types since their alias behavior
49600                 // is more predictable than other, interned types, which may or may not have an alias depending on
49601                 // the order in which things were checked.
49602                 if (source.flags & (524288 /* Object */ | 16777216 /* Conditional */) && source.aliasSymbol &&
49603                     source.aliasTypeArguments && source.aliasSymbol === target.aliasSymbol &&
49604                     !(source.aliasTypeArgumentsContainsMarker || target.aliasTypeArgumentsContainsMarker)) {
49605                     var variances = getAliasVariances(source.aliasSymbol);
49606                     if (variances === ts.emptyArray) {
49607                         return 1 /* Maybe */;
49608                     }
49609                     var varianceResult = relateVariances(source.aliasTypeArguments, target.aliasTypeArguments, variances, intersectionState);
49610                     if (varianceResult !== undefined) {
49611                         return varianceResult;
49612                     }
49613                 }
49614                 if (target.flags & 262144 /* TypeParameter */) {
49615                     // 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].
49616                     if (ts.getObjectFlags(source) & 32 /* Mapped */ && isRelatedTo(getIndexType(target), getConstraintTypeFromMappedType(source))) {
49617                         if (!(getMappedTypeModifiers(source) & 4 /* IncludeOptional */)) {
49618                             var templateType = getTemplateTypeFromMappedType(source);
49619                             var indexedAccessType = getIndexedAccessType(target, getTypeParameterFromMappedType(source));
49620                             if (result = isRelatedTo(templateType, indexedAccessType, reportErrors)) {
49621                                 return result;
49622                             }
49623                         }
49624                     }
49625                 }
49626                 else if (target.flags & 4194304 /* Index */) {
49627                     // A keyof S is related to a keyof T if T is related to S.
49628                     if (source.flags & 4194304 /* Index */) {
49629                         if (result = isRelatedTo(target.type, source.type, /*reportErrors*/ false)) {
49630                             return result;
49631                         }
49632                     }
49633                     // A type S is assignable to keyof T if S is assignable to keyof C, where C is the
49634                     // simplified form of T or, if T doesn't simplify, the constraint of T.
49635                     var constraint = getSimplifiedTypeOrConstraint(target.type);
49636                     if (constraint) {
49637                         // We require Ternary.True here such that circular constraints don't cause
49638                         // false positives. For example, given 'T extends { [K in keyof T]: string }',
49639                         // 'keyof T' has itself as its constraint and produces a Ternary.Maybe when
49640                         // related to other types.
49641                         if (isRelatedTo(source, getIndexType(constraint, target.stringsOnly), reportErrors) === -1 /* True */) {
49642                             return -1 /* True */;
49643                         }
49644                     }
49645                 }
49646                 else if (target.flags & 8388608 /* IndexedAccess */) {
49647                     // A type S is related to a type T[K] if S is related to C, where C is the base
49648                     // constraint of T[K] for writing.
49649                     if (relation !== identityRelation) {
49650                         var objectType = target.objectType;
49651                         var indexType = target.indexType;
49652                         var baseObjectType = getBaseConstraintOfType(objectType) || objectType;
49653                         var baseIndexType = getBaseConstraintOfType(indexType) || indexType;
49654                         if (!isGenericObjectType(baseObjectType) && !isGenericIndexType(baseIndexType)) {
49655                             var accessFlags = 2 /* Writing */ | (baseObjectType !== objectType ? 1 /* NoIndexSignatures */ : 0);
49656                             var constraint = getIndexedAccessTypeOrUndefined(baseObjectType, baseIndexType, /*accessNode*/ undefined, accessFlags);
49657                             if (constraint && (result = isRelatedTo(source, constraint, reportErrors))) {
49658                                 return result;
49659                             }
49660                         }
49661                     }
49662                 }
49663                 else if (isGenericMappedType(target)) {
49664                     // A source type T is related to a target type { [P in X]: T[P] }
49665                     var template = getTemplateTypeFromMappedType(target);
49666                     var modifiers = getMappedTypeModifiers(target);
49667                     if (!(modifiers & 8 /* ExcludeOptional */)) {
49668                         if (template.flags & 8388608 /* IndexedAccess */ && template.objectType === source &&
49669                             template.indexType === getTypeParameterFromMappedType(target)) {
49670                             return -1 /* True */;
49671                         }
49672                         if (!isGenericMappedType(source)) {
49673                             var targetConstraint = getConstraintTypeFromMappedType(target);
49674                             var sourceKeys = getIndexType(source, /*stringsOnly*/ undefined, /*noIndexSignatures*/ true);
49675                             var includeOptional = modifiers & 4 /* IncludeOptional */;
49676                             var filteredByApplicability = includeOptional ? intersectTypes(targetConstraint, sourceKeys) : undefined;
49677                             // 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.
49678                             // 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.
49679                             if (includeOptional
49680                                 ? !(filteredByApplicability.flags & 131072 /* Never */)
49681                                 : isRelatedTo(targetConstraint, sourceKeys)) {
49682                                 var typeParameter = getTypeParameterFromMappedType(target);
49683                                 var indexingType = filteredByApplicability ? getIntersectionType([filteredByApplicability, typeParameter]) : typeParameter;
49684                                 var indexedAccessType = getIndexedAccessType(source, indexingType);
49685                                 var templateType = getTemplateTypeFromMappedType(target);
49686                                 if (result = isRelatedTo(indexedAccessType, templateType, reportErrors)) {
49687                                     return result;
49688                                 }
49689                             }
49690                             originalErrorInfo = errorInfo;
49691                             resetErrorInfo(saveErrorInfo);
49692                         }
49693                     }
49694                 }
49695                 if (source.flags & 8650752 /* TypeVariable */) {
49696                     if (source.flags & 8388608 /* IndexedAccess */ && target.flags & 8388608 /* IndexedAccess */) {
49697                         // A type S[K] is related to a type T[J] if S is related to T and K is related to J.
49698                         if (result = isRelatedTo(source.objectType, target.objectType, reportErrors)) {
49699                             result &= isRelatedTo(source.indexType, target.indexType, reportErrors);
49700                         }
49701                         if (result) {
49702                             resetErrorInfo(saveErrorInfo);
49703                             return result;
49704                         }
49705                     }
49706                     else {
49707                         var constraint = getConstraintOfType(source);
49708                         if (!constraint || (source.flags & 262144 /* TypeParameter */ && constraint.flags & 1 /* Any */)) {
49709                             // A type variable with no constraint is not related to the non-primitive object type.
49710                             if (result = isRelatedTo(emptyObjectType, extractTypesOfKind(target, ~67108864 /* NonPrimitive */))) {
49711                                 resetErrorInfo(saveErrorInfo);
49712                                 return result;
49713                             }
49714                         }
49715                         // 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
49716                         else if (result = isRelatedTo(constraint, target, /*reportErrors*/ false, /*headMessage*/ undefined, intersectionState)) {
49717                             resetErrorInfo(saveErrorInfo);
49718                             return result;
49719                         }
49720                         // slower, fuller, this-instantiated check (necessary when comparing raw `this` types from base classes), see `subclassWithPolymorphicThisIsAssignable.ts` test for example
49721                         else if (result = isRelatedTo(getTypeWithThisArgument(constraint, source), target, reportErrors, /*headMessage*/ undefined, intersectionState)) {
49722                             resetErrorInfo(saveErrorInfo);
49723                             return result;
49724                         }
49725                     }
49726                 }
49727                 else if (source.flags & 4194304 /* Index */) {
49728                     if (result = isRelatedTo(keyofConstraintType, target, reportErrors)) {
49729                         resetErrorInfo(saveErrorInfo);
49730                         return result;
49731                     }
49732                 }
49733                 else if (source.flags & 16777216 /* Conditional */) {
49734                     if (target.flags & 16777216 /* Conditional */) {
49735                         // Two conditional types 'T1 extends U1 ? X1 : Y1' and 'T2 extends U2 ? X2 : Y2' are related if
49736                         // one of T1 and T2 is related to the other, U1 and U2 are identical types, X1 is related to X2,
49737                         // and Y1 is related to Y2.
49738                         var sourceParams = source.root.inferTypeParameters;
49739                         var sourceExtends = source.extendsType;
49740                         var mapper = void 0;
49741                         if (sourceParams) {
49742                             // If the source has infer type parameters, we instantiate them in the context of the target
49743                             var ctx = createInferenceContext(sourceParams, /*signature*/ undefined, 0 /* None */, isRelatedTo);
49744                             inferTypes(ctx.inferences, target.extendsType, sourceExtends, 128 /* NoConstraints */ | 256 /* AlwaysStrict */);
49745                             sourceExtends = instantiateType(sourceExtends, ctx.mapper);
49746                             mapper = ctx.mapper;
49747                         }
49748                         if (isTypeIdenticalTo(sourceExtends, target.extendsType) &&
49749                             (isRelatedTo(source.checkType, target.checkType) || isRelatedTo(target.checkType, source.checkType))) {
49750                             if (result = isRelatedTo(instantiateType(getTrueTypeFromConditionalType(source), mapper), getTrueTypeFromConditionalType(target), reportErrors)) {
49751                                 result &= isRelatedTo(getFalseTypeFromConditionalType(source), getFalseTypeFromConditionalType(target), reportErrors);
49752                             }
49753                             if (result) {
49754                                 resetErrorInfo(saveErrorInfo);
49755                                 return result;
49756                             }
49757                         }
49758                     }
49759                     else {
49760                         // conditionals aren't related to one another via distributive constraint as it is much too inaccurate and allows way
49761                         // more assignments than are desirable (since it maps the source check type to its constraint, it loses information)
49762                         var distributiveConstraint = getConstraintOfDistributiveConditionalType(source);
49763                         if (distributiveConstraint) {
49764                             if (result = isRelatedTo(distributiveConstraint, target, reportErrors)) {
49765                                 resetErrorInfo(saveErrorInfo);
49766                                 return result;
49767                             }
49768                         }
49769                     }
49770                     // conditionals _can_ be related to one another via normal constraint, as, eg, `A extends B ? O : never` should be assignable to `O`
49771                     // when `O` is a conditional (`never` is trivially aissgnable to `O`, as is `O`!).
49772                     var defaultConstraint = getDefaultConstraintOfConditionalType(source);
49773                     if (defaultConstraint) {
49774                         if (result = isRelatedTo(defaultConstraint, target, reportErrors)) {
49775                             resetErrorInfo(saveErrorInfo);
49776                             return result;
49777                         }
49778                     }
49779                 }
49780                 else {
49781                     // An empty object type is related to any mapped type that includes a '?' modifier.
49782                     if (relation !== subtypeRelation && relation !== strictSubtypeRelation && isPartialMappedType(target) && isEmptyObjectType(source)) {
49783                         return -1 /* True */;
49784                     }
49785                     if (isGenericMappedType(target)) {
49786                         if (isGenericMappedType(source)) {
49787                             if (result = mappedTypeRelatedTo(source, target, reportErrors)) {
49788                                 resetErrorInfo(saveErrorInfo);
49789                                 return result;
49790                             }
49791                         }
49792                         return 0 /* False */;
49793                     }
49794                     var sourceIsPrimitive = !!(source.flags & 131068 /* Primitive */);
49795                     if (relation !== identityRelation) {
49796                         source = getApparentType(source);
49797                     }
49798                     else if (isGenericMappedType(source)) {
49799                         return 0 /* False */;
49800                     }
49801                     if (ts.getObjectFlags(source) & 4 /* Reference */ && ts.getObjectFlags(target) & 4 /* Reference */ && source.target === target.target &&
49802                         !(ts.getObjectFlags(source) & 8192 /* MarkerType */ || ts.getObjectFlags(target) & 8192 /* MarkerType */)) {
49803                         // We have type references to the same generic type, and the type references are not marker
49804                         // type references (which are intended by be compared structurally). Obtain the variance
49805                         // information for the type parameters and relate the type arguments accordingly.
49806                         var variances = getVariances(source.target);
49807                         // We return Ternary.Maybe for a recursive invocation of getVariances (signalled by emptyArray). This
49808                         // effectively means we measure variance only from type parameter occurrences that aren't nested in
49809                         // recursive instantiations of the generic type.
49810                         if (variances === ts.emptyArray) {
49811                             return 1 /* Maybe */;
49812                         }
49813                         var varianceResult = relateVariances(getTypeArguments(source), getTypeArguments(target), variances, intersectionState);
49814                         if (varianceResult !== undefined) {
49815                             return varianceResult;
49816                         }
49817                     }
49818                     else if (isReadonlyArrayType(target) ? isArrayType(source) || isTupleType(source) : isArrayType(target) && isTupleType(source) && !source.target.readonly) {
49819                         if (relation !== identityRelation) {
49820                             return isRelatedTo(getIndexTypeOfType(source, 1 /* Number */) || anyType, getIndexTypeOfType(target, 1 /* Number */) || anyType, reportErrors);
49821                         }
49822                         else {
49823                             // By flags alone, we know that the `target` is a readonly array while the source is a normal array or tuple
49824                             // or `target` is an array and source is a tuple - in both cases the types cannot be identical, by construction
49825                             return 0 /* False */;
49826                         }
49827                     }
49828                     // Consider a fresh empty object literal type "closed" under the subtype relationship - this way `{} <- {[idx: string]: any} <- fresh({})`
49829                     // and not `{} <- fresh({}) <- {[idx: string]: any}`
49830                     else if ((relation === subtypeRelation || relation === strictSubtypeRelation) && isEmptyObjectType(target) && ts.getObjectFlags(target) & 32768 /* FreshLiteral */ && !isEmptyObjectType(source)) {
49831                         return 0 /* False */;
49832                     }
49833                     // Even if relationship doesn't hold for unions, intersections, or generic type references,
49834                     // it may hold in a structural comparison.
49835                     // In a check of the form X = A & B, we will have previously checked if A relates to X or B relates
49836                     // to X. Failing both of those we want to check if the aggregation of A and B's members structurally
49837                     // relates to X. Thus, we include intersection types on the source side here.
49838                     if (source.flags & (524288 /* Object */ | 2097152 /* Intersection */) && target.flags & 524288 /* Object */) {
49839                         // Report structural errors only if we haven't reported any errors yet
49840                         var reportStructuralErrors = reportErrors && errorInfo === saveErrorInfo.errorInfo && !sourceIsPrimitive;
49841                         result = propertiesRelatedTo(source, target, reportStructuralErrors, /*excludedProperties*/ undefined, intersectionState);
49842                         if (result) {
49843                             result &= signaturesRelatedTo(source, target, 0 /* Call */, reportStructuralErrors);
49844                             if (result) {
49845                                 result &= signaturesRelatedTo(source, target, 1 /* Construct */, reportStructuralErrors);
49846                                 if (result) {
49847                                     result &= indexTypesRelatedTo(source, target, 0 /* String */, sourceIsPrimitive, reportStructuralErrors, intersectionState);
49848                                     if (result) {
49849                                         result &= indexTypesRelatedTo(source, target, 1 /* Number */, sourceIsPrimitive, reportStructuralErrors, intersectionState);
49850                                     }
49851                                 }
49852                             }
49853                         }
49854                         if (varianceCheckFailed && result) {
49855                             errorInfo = originalErrorInfo || errorInfo || saveErrorInfo.errorInfo; // Use variance error (there is no structural one) and return false
49856                         }
49857                         else if (result) {
49858                             return result;
49859                         }
49860                     }
49861                     // If S is an object type and T is a discriminated union, S may be related to T if
49862                     // there exists a constituent of T for every combination of the discriminants of S
49863                     // with respect to T. We do not report errors here, as we will use the existing
49864                     // error result from checking each constituent of the union.
49865                     if (source.flags & (524288 /* Object */ | 2097152 /* Intersection */) && target.flags & 1048576 /* Union */) {
49866                         var objectOnlyTarget = extractTypesOfKind(target, 524288 /* Object */ | 2097152 /* Intersection */ | 33554432 /* Substitution */);
49867                         if (objectOnlyTarget.flags & 1048576 /* Union */) {
49868                             var result_7 = typeRelatedToDiscriminatedType(source, objectOnlyTarget);
49869                             if (result_7) {
49870                                 return result_7;
49871                             }
49872                         }
49873                     }
49874                 }
49875                 return 0 /* False */;
49876                 function relateVariances(sourceTypeArguments, targetTypeArguments, variances, intersectionState) {
49877                     if (result = typeArgumentsRelatedTo(sourceTypeArguments, targetTypeArguments, variances, reportErrors, intersectionState)) {
49878                         return result;
49879                     }
49880                     if (ts.some(variances, function (v) { return !!(v & 24 /* AllowsStructuralFallback */); })) {
49881                         // If some type parameter was `Unmeasurable` or `Unreliable`, and we couldn't pass by assuming it was identical, then we
49882                         // have to allow a structural fallback check
49883                         // We elide the variance-based error elaborations, since those might not be too helpful, since we'll potentially
49884                         // be assuming identity of the type parameter.
49885                         originalErrorInfo = undefined;
49886                         resetErrorInfo(saveErrorInfo);
49887                         return undefined;
49888                     }
49889                     var allowStructuralFallback = targetTypeArguments && hasCovariantVoidArgument(targetTypeArguments, variances);
49890                     varianceCheckFailed = !allowStructuralFallback;
49891                     // The type arguments did not relate appropriately, but it may be because we have no variance
49892                     // information (in which case typeArgumentsRelatedTo defaulted to covariance for all type
49893                     // arguments). It might also be the case that the target type has a 'void' type argument for
49894                     // a covariant type parameter that is only used in return positions within the generic type
49895                     // (in which case any type argument is permitted on the source side). In those cases we proceed
49896                     // with a structural comparison. Otherwise, we know for certain the instantiations aren't
49897                     // related and we can return here.
49898                     if (variances !== ts.emptyArray && !allowStructuralFallback) {
49899                         // In some cases generic types that are covariant in regular type checking mode become
49900                         // invariant in --strictFunctionTypes mode because one or more type parameters are used in
49901                         // both co- and contravariant positions. In order to make it easier to diagnose *why* such
49902                         // types are invariant, if any of the type parameters are invariant we reset the reported
49903                         // errors and instead force a structural comparison (which will include elaborations that
49904                         // reveal the reason).
49905                         // We can switch on `reportErrors` here, since varianceCheckFailed guarantees we return `False`,
49906                         // we can return `False` early here to skip calculating the structural error message we don't need.
49907                         if (varianceCheckFailed && !(reportErrors && ts.some(variances, function (v) { return (v & 7 /* VarianceMask */) === 0 /* Invariant */; }))) {
49908                             return 0 /* False */;
49909                         }
49910                         // We remember the original error information so we can restore it in case the structural
49911                         // comparison unexpectedly succeeds. This can happen when the structural comparison result
49912                         // is a Ternary.Maybe for example caused by the recursion depth limiter.
49913                         originalErrorInfo = errorInfo;
49914                         resetErrorInfo(saveErrorInfo);
49915                     }
49916                 }
49917             }
49918             function reportUnmeasurableMarkers(p) {
49919                 if (outofbandVarianceMarkerHandler && (p === markerSuperType || p === markerSubType || p === markerOtherType)) {
49920                     outofbandVarianceMarkerHandler(/*onlyUnreliable*/ false);
49921                 }
49922                 return p;
49923             }
49924             function reportUnreliableMarkers(p) {
49925                 if (outofbandVarianceMarkerHandler && (p === markerSuperType || p === markerSubType || p === markerOtherType)) {
49926                     outofbandVarianceMarkerHandler(/*onlyUnreliable*/ true);
49927                 }
49928                 return p;
49929             }
49930             // A type [P in S]: X is related to a type [Q in T]: Y if T is related to S and X' is
49931             // related to Y, where X' is an instantiation of X in which P is replaced with Q. Notice
49932             // that S and T are contra-variant whereas X and Y are co-variant.
49933             function mappedTypeRelatedTo(source, target, reportErrors) {
49934                 var modifiersRelated = relation === comparableRelation || (relation === identityRelation ? getMappedTypeModifiers(source) === getMappedTypeModifiers(target) :
49935                     getCombinedMappedTypeOptionality(source) <= getCombinedMappedTypeOptionality(target));
49936                 if (modifiersRelated) {
49937                     var result_8;
49938                     var targetConstraint = getConstraintTypeFromMappedType(target);
49939                     var sourceConstraint = instantiateType(getConstraintTypeFromMappedType(source), makeFunctionTypeMapper(getCombinedMappedTypeOptionality(source) < 0 ? reportUnmeasurableMarkers : reportUnreliableMarkers));
49940                     if (result_8 = isRelatedTo(targetConstraint, sourceConstraint, reportErrors)) {
49941                         var mapper = createTypeMapper([getTypeParameterFromMappedType(source)], [getTypeParameterFromMappedType(target)]);
49942                         return result_8 & isRelatedTo(instantiateType(getTemplateTypeFromMappedType(source), mapper), getTemplateTypeFromMappedType(target), reportErrors);
49943                     }
49944                 }
49945                 return 0 /* False */;
49946             }
49947             function typeRelatedToDiscriminatedType(source, target) {
49948                 // 1. Generate the combinations of discriminant properties & types 'source' can satisfy.
49949                 //    a. If the number of combinations is above a set limit, the comparison is too complex.
49950                 // 2. Filter 'target' to the subset of types whose discriminants exist in the matrix.
49951                 //    a. If 'target' does not satisfy all discriminants in the matrix, 'source' is not related.
49952                 // 3. For each type in the filtered 'target', determine if all non-discriminant properties of
49953                 //    'target' are related to a property in 'source'.
49954                 //
49955                 // NOTE: See ~/tests/cases/conformance/types/typeRelationships/assignmentCompatibility/assignmentCompatWithDiscriminatedUnion.ts
49956                 //       for examples.
49957                 var sourceProperties = getPropertiesOfType(source);
49958                 var sourcePropertiesFiltered = findDiscriminantProperties(sourceProperties, target);
49959                 if (!sourcePropertiesFiltered)
49960                     return 0 /* False */;
49961                 // Though we could compute the number of combinations as we generate
49962                 // the matrix, this would incur additional memory overhead due to
49963                 // array allocations. To reduce this overhead, we first compute
49964                 // the number of combinations to ensure we will not surpass our
49965                 // fixed limit before incurring the cost of any allocations:
49966                 var numCombinations = 1;
49967                 for (var _i = 0, sourcePropertiesFiltered_1 = sourcePropertiesFiltered; _i < sourcePropertiesFiltered_1.length; _i++) {
49968                     var sourceProperty = sourcePropertiesFiltered_1[_i];
49969                     numCombinations *= countTypes(getTypeOfSymbol(sourceProperty));
49970                     if (numCombinations > 25) {
49971                         // We've reached the complexity limit.
49972                         return 0 /* False */;
49973                     }
49974                 }
49975                 // Compute the set of types for each discriminant property.
49976                 var sourceDiscriminantTypes = new Array(sourcePropertiesFiltered.length);
49977                 var excludedProperties = ts.createUnderscoreEscapedMap();
49978                 for (var i = 0; i < sourcePropertiesFiltered.length; i++) {
49979                     var sourceProperty = sourcePropertiesFiltered[i];
49980                     var sourcePropertyType = getTypeOfSymbol(sourceProperty);
49981                     sourceDiscriminantTypes[i] = sourcePropertyType.flags & 1048576 /* Union */
49982                         ? sourcePropertyType.types
49983                         : [sourcePropertyType];
49984                     excludedProperties.set(sourceProperty.escapedName, true);
49985                 }
49986                 // Match each combination of the cartesian product of discriminant properties to one or more
49987                 // constituents of 'target'. If any combination does not have a match then 'source' is not relatable.
49988                 var discriminantCombinations = ts.cartesianProduct(sourceDiscriminantTypes);
49989                 var matchingTypes = [];
49990                 var _loop_14 = function (combination) {
49991                     var hasMatch = false;
49992                     outer: for (var _i = 0, _a = target.types; _i < _a.length; _i++) {
49993                         var type = _a[_i];
49994                         var _loop_15 = function (i) {
49995                             var sourceProperty = sourcePropertiesFiltered[i];
49996                             var targetProperty = getPropertyOfType(type, sourceProperty.escapedName);
49997                             if (!targetProperty)
49998                                 return "continue-outer";
49999                             if (sourceProperty === targetProperty)
50000                                 return "continue";
50001                             // We compare the source property to the target in the context of a single discriminant type.
50002                             var related = propertyRelatedTo(source, target, sourceProperty, targetProperty, function (_) { return combination[i]; }, /*reportErrors*/ false, 0 /* None */, /*skipOptional*/ strictNullChecks || relation === comparableRelation);
50003                             // If the target property could not be found, or if the properties were not related,
50004                             // then this constituent is not a match.
50005                             if (!related) {
50006                                 return "continue-outer";
50007                             }
50008                         };
50009                         for (var i = 0; i < sourcePropertiesFiltered.length; i++) {
50010                             var state_7 = _loop_15(i);
50011                             switch (state_7) {
50012                                 case "continue-outer": continue outer;
50013                             }
50014                         }
50015                         ts.pushIfUnique(matchingTypes, type, ts.equateValues);
50016                         hasMatch = true;
50017                     }
50018                     if (!hasMatch) {
50019                         return { value: 0 /* False */ };
50020                     }
50021                 };
50022                 for (var _a = 0, discriminantCombinations_1 = discriminantCombinations; _a < discriminantCombinations_1.length; _a++) {
50023                     var combination = discriminantCombinations_1[_a];
50024                     var state_6 = _loop_14(combination);
50025                     if (typeof state_6 === "object")
50026                         return state_6.value;
50027                 }
50028                 // Compare the remaining non-discriminant properties of each match.
50029                 var result = -1 /* True */;
50030                 for (var _b = 0, matchingTypes_1 = matchingTypes; _b < matchingTypes_1.length; _b++) {
50031                     var type = matchingTypes_1[_b];
50032                     result &= propertiesRelatedTo(source, type, /*reportErrors*/ false, excludedProperties, 0 /* None */);
50033                     if (result) {
50034                         result &= signaturesRelatedTo(source, type, 0 /* Call */, /*reportStructuralErrors*/ false);
50035                         if (result) {
50036                             result &= signaturesRelatedTo(source, type, 1 /* Construct */, /*reportStructuralErrors*/ false);
50037                             if (result) {
50038                                 result &= indexTypesRelatedTo(source, type, 0 /* String */, /*sourceIsPrimitive*/ false, /*reportStructuralErrors*/ false, 0 /* None */);
50039                                 if (result) {
50040                                     result &= indexTypesRelatedTo(source, type, 1 /* Number */, /*sourceIsPrimitive*/ false, /*reportStructuralErrors*/ false, 0 /* None */);
50041                                 }
50042                             }
50043                         }
50044                     }
50045                     if (!result) {
50046                         return result;
50047                     }
50048                 }
50049                 return result;
50050             }
50051             function excludeProperties(properties, excludedProperties) {
50052                 if (!excludedProperties || properties.length === 0)
50053                     return properties;
50054                 var result;
50055                 for (var i = 0; i < properties.length; i++) {
50056                     if (!excludedProperties.has(properties[i].escapedName)) {
50057                         if (result) {
50058                             result.push(properties[i]);
50059                         }
50060                     }
50061                     else if (!result) {
50062                         result = properties.slice(0, i);
50063                     }
50064                 }
50065                 return result || properties;
50066             }
50067             function isPropertySymbolTypeRelated(sourceProp, targetProp, getTypeOfSourceProperty, reportErrors, intersectionState) {
50068                 var targetIsOptional = strictNullChecks && !!(ts.getCheckFlags(targetProp) & 48 /* Partial */);
50069                 var source = getTypeOfSourceProperty(sourceProp);
50070                 if (ts.getCheckFlags(targetProp) & 65536 /* DeferredType */ && !getSymbolLinks(targetProp).type) {
50071                     // Rather than resolving (and normalizing) the type, relate constituent-by-constituent without performing normalization or seconadary passes
50072                     var links = getSymbolLinks(targetProp);
50073                     ts.Debug.assertIsDefined(links.deferralParent);
50074                     ts.Debug.assertIsDefined(links.deferralConstituents);
50075                     var unionParent = !!(links.deferralParent.flags & 1048576 /* Union */);
50076                     var result_9 = unionParent ? 0 /* False */ : -1 /* True */;
50077                     var targetTypes = links.deferralConstituents;
50078                     for (var _i = 0, targetTypes_3 = targetTypes; _i < targetTypes_3.length; _i++) {
50079                         var targetType = targetTypes_3[_i];
50080                         var related = isRelatedTo(source, targetType, /*reportErrors*/ false, /*headMessage*/ undefined, unionParent ? 0 : 2 /* Target */);
50081                         if (!unionParent) {
50082                             if (!related) {
50083                                 // Can't assign to a target individually - have to fallback to assigning to the _whole_ intersection (which forces normalization)
50084                                 return isRelatedTo(source, addOptionality(getTypeOfSymbol(targetProp), targetIsOptional), reportErrors);
50085                             }
50086                             result_9 &= related;
50087                         }
50088                         else {
50089                             if (related) {
50090                                 return related;
50091                             }
50092                         }
50093                     }
50094                     if (unionParent && !result_9 && targetIsOptional) {
50095                         result_9 = isRelatedTo(source, undefinedType);
50096                     }
50097                     if (unionParent && !result_9 && reportErrors) {
50098                         // The easiest way to get the right errors here is to un-defer (which may be costly)
50099                         // If it turns out this is too costly too often, we can replicate the error handling logic within
50100                         // typeRelatedToSomeType without the discriminatable type branch (as that requires a manifest union
50101                         // type on which to hand discriminable properties, which we are expressly trying to avoid here)
50102                         return isRelatedTo(source, addOptionality(getTypeOfSymbol(targetProp), targetIsOptional), reportErrors);
50103                     }
50104                     return result_9;
50105                 }
50106                 else {
50107                     return isRelatedTo(source, addOptionality(getTypeOfSymbol(targetProp), targetIsOptional), reportErrors, /*headMessage*/ undefined, intersectionState);
50108                 }
50109             }
50110             function propertyRelatedTo(source, target, sourceProp, targetProp, getTypeOfSourceProperty, reportErrors, intersectionState, skipOptional) {
50111                 var sourcePropFlags = ts.getDeclarationModifierFlagsFromSymbol(sourceProp);
50112                 var targetPropFlags = ts.getDeclarationModifierFlagsFromSymbol(targetProp);
50113                 if (sourcePropFlags & 8 /* Private */ || targetPropFlags & 8 /* Private */) {
50114                     if (sourceProp.valueDeclaration !== targetProp.valueDeclaration) {
50115                         if (reportErrors) {
50116                             if (sourcePropFlags & 8 /* Private */ && targetPropFlags & 8 /* Private */) {
50117                                 reportError(ts.Diagnostics.Types_have_separate_declarations_of_a_private_property_0, symbolToString(targetProp));
50118                             }
50119                             else {
50120                                 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));
50121                             }
50122                         }
50123                         return 0 /* False */;
50124                     }
50125                 }
50126                 else if (targetPropFlags & 16 /* Protected */) {
50127                     if (!isValidOverrideOf(sourceProp, targetProp)) {
50128                         if (reportErrors) {
50129                             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));
50130                         }
50131                         return 0 /* False */;
50132                     }
50133                 }
50134                 else if (sourcePropFlags & 16 /* Protected */) {
50135                     if (reportErrors) {
50136                         reportError(ts.Diagnostics.Property_0_is_protected_in_type_1_but_public_in_type_2, symbolToString(targetProp), typeToString(source), typeToString(target));
50137                     }
50138                     return 0 /* False */;
50139                 }
50140                 // If the target comes from a partial union prop, allow `undefined` in the target type
50141                 var related = isPropertySymbolTypeRelated(sourceProp, targetProp, getTypeOfSourceProperty, reportErrors, intersectionState);
50142                 if (!related) {
50143                     if (reportErrors) {
50144                         reportIncompatibleError(ts.Diagnostics.Types_of_property_0_are_incompatible, symbolToString(targetProp));
50145                     }
50146                     return 0 /* False */;
50147                 }
50148                 // When checking for comparability, be more lenient with optional properties.
50149                 if (!skipOptional && sourceProp.flags & 16777216 /* Optional */ && !(targetProp.flags & 16777216 /* Optional */)) {
50150                     // TypeScript 1.0 spec (April 2014): 3.8.3
50151                     // S is a subtype of a type T, and T is a supertype of S if ...
50152                     // S' and T are object types and, for each member M in T..
50153                     // M is a property and S' contains a property N where
50154                     // if M is a required property, N is also a required property
50155                     // (M - property in T)
50156                     // (N - property in S)
50157                     if (reportErrors) {
50158                         reportError(ts.Diagnostics.Property_0_is_optional_in_type_1_but_required_in_type_2, symbolToString(targetProp), typeToString(source), typeToString(target));
50159                     }
50160                     return 0 /* False */;
50161                 }
50162                 return related;
50163             }
50164             function reportUnmatchedProperty(source, target, unmatchedProperty, requireOptionalProperties) {
50165                 var shouldSkipElaboration = false;
50166                 // give specific error in case where private names have the same description
50167                 if (unmatchedProperty.valueDeclaration
50168                     && ts.isNamedDeclaration(unmatchedProperty.valueDeclaration)
50169                     && ts.isPrivateIdentifier(unmatchedProperty.valueDeclaration.name)
50170                     && source.symbol
50171                     && source.symbol.flags & 32 /* Class */) {
50172                     var privateIdentifierDescription = unmatchedProperty.valueDeclaration.name.escapedText;
50173                     var symbolTableKey = ts.getSymbolNameForPrivateIdentifier(source.symbol, privateIdentifierDescription);
50174                     if (symbolTableKey && getPropertyOfType(source, symbolTableKey)) {
50175                         var sourceName = ts.getDeclarationName(source.symbol.valueDeclaration);
50176                         var targetName = ts.getDeclarationName(target.symbol.valueDeclaration);
50177                         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));
50178                         return;
50179                     }
50180                 }
50181                 var props = ts.arrayFrom(getUnmatchedProperties(source, target, requireOptionalProperties, /*matchDiscriminantProperties*/ false));
50182                 if (!headMessage || (headMessage.code !== ts.Diagnostics.Class_0_incorrectly_implements_interface_1.code &&
50183                     headMessage.code !== ts.Diagnostics.Class_0_incorrectly_implements_class_1_Did_you_mean_to_extend_1_and_inherit_its_members_as_a_subclass.code)) {
50184                     shouldSkipElaboration = true; // Retain top-level error for interface implementing issues, otherwise omit it
50185                 }
50186                 if (props.length === 1) {
50187                     var propName = symbolToString(unmatchedProperty);
50188                     reportError.apply(void 0, __spreadArrays([ts.Diagnostics.Property_0_is_missing_in_type_1_but_required_in_type_2, propName], getTypeNamesForErrorDisplay(source, target)));
50189                     if (ts.length(unmatchedProperty.declarations)) {
50190                         associateRelatedInfo(ts.createDiagnosticForNode(unmatchedProperty.declarations[0], ts.Diagnostics._0_is_declared_here, propName));
50191                     }
50192                     if (shouldSkipElaboration && errorInfo) {
50193                         overrideNextErrorInfo++;
50194                     }
50195                 }
50196                 else if (tryElaborateArrayLikeErrors(source, target, /*reportErrors*/ false)) {
50197                     if (props.length > 5) { // arbitrary cutoff for too-long list form
50198                         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);
50199                     }
50200                     else {
50201                         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(", "));
50202                     }
50203                     if (shouldSkipElaboration && errorInfo) {
50204                         overrideNextErrorInfo++;
50205                     }
50206                 }
50207                 // No array like or unmatched property error - just issue top level error (errorInfo = undefined)
50208             }
50209             function propertiesRelatedTo(source, target, reportErrors, excludedProperties, intersectionState) {
50210                 if (relation === identityRelation) {
50211                     return propertiesIdenticalTo(source, target, excludedProperties);
50212                 }
50213                 var requireOptionalProperties = (relation === subtypeRelation || relation === strictSubtypeRelation) && !isObjectLiteralType(source) && !isEmptyArrayLiteralType(source) && !isTupleType(source);
50214                 var unmatchedProperty = getUnmatchedProperty(source, target, requireOptionalProperties, /*matchDiscriminantProperties*/ false);
50215                 if (unmatchedProperty) {
50216                     if (reportErrors) {
50217                         reportUnmatchedProperty(source, target, unmatchedProperty, requireOptionalProperties);
50218                     }
50219                     return 0 /* False */;
50220                 }
50221                 if (isObjectLiteralType(target)) {
50222                     for (var _i = 0, _a = excludeProperties(getPropertiesOfType(source), excludedProperties); _i < _a.length; _i++) {
50223                         var sourceProp = _a[_i];
50224                         if (!getPropertyOfObjectType(target, sourceProp.escapedName)) {
50225                             var sourceType = getTypeOfSymbol(sourceProp);
50226                             if (!(sourceType === undefinedType || sourceType === undefinedWideningType || sourceType === optionalType)) {
50227                                 if (reportErrors) {
50228                                     reportError(ts.Diagnostics.Property_0_does_not_exist_on_type_1, symbolToString(sourceProp), typeToString(target));
50229                                 }
50230                                 return 0 /* False */;
50231                             }
50232                         }
50233                     }
50234                 }
50235                 var result = -1 /* True */;
50236                 if (isTupleType(target)) {
50237                     var targetRestType = getRestTypeOfTupleType(target);
50238                     if (targetRestType) {
50239                         if (!isTupleType(source)) {
50240                             return 0 /* False */;
50241                         }
50242                         var sourceRestType = getRestTypeOfTupleType(source);
50243                         if (sourceRestType && !isRelatedTo(sourceRestType, targetRestType, reportErrors)) {
50244                             if (reportErrors) {
50245                                 reportError(ts.Diagnostics.Rest_signatures_are_incompatible);
50246                             }
50247                             return 0 /* False */;
50248                         }
50249                         var targetCount = getTypeReferenceArity(target) - 1;
50250                         var sourceCount = getTypeReferenceArity(source) - (sourceRestType ? 1 : 0);
50251                         var sourceTypeArguments = getTypeArguments(source);
50252                         for (var i = targetCount; i < sourceCount; i++) {
50253                             var related = isRelatedTo(sourceTypeArguments[i], targetRestType, reportErrors);
50254                             if (!related) {
50255                                 if (reportErrors) {
50256                                     reportError(ts.Diagnostics.Property_0_is_incompatible_with_rest_element_type, "" + i);
50257                                 }
50258                                 return 0 /* False */;
50259                             }
50260                             result &= related;
50261                         }
50262                     }
50263                 }
50264                 // 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_
50265                 // from the target union, across all members
50266                 var properties = getPropertiesOfType(target);
50267                 var numericNamesOnly = isTupleType(source) && isTupleType(target);
50268                 for (var _b = 0, _c = excludeProperties(properties, excludedProperties); _b < _c.length; _b++) {
50269                     var targetProp = _c[_b];
50270                     var name = targetProp.escapedName;
50271                     if (!(targetProp.flags & 4194304 /* Prototype */) && (!numericNamesOnly || isNumericLiteralName(name) || name === "length")) {
50272                         var sourceProp = getPropertyOfType(source, name);
50273                         if (sourceProp && sourceProp !== targetProp) {
50274                             var related = propertyRelatedTo(source, target, sourceProp, targetProp, getTypeOfSymbol, reportErrors, intersectionState, relation === comparableRelation);
50275                             if (!related) {
50276                                 return 0 /* False */;
50277                             }
50278                             result &= related;
50279                         }
50280                     }
50281                 }
50282                 return result;
50283             }
50284             function propertiesIdenticalTo(source, target, excludedProperties) {
50285                 if (!(source.flags & 524288 /* Object */ && target.flags & 524288 /* Object */)) {
50286                     return 0 /* False */;
50287                 }
50288                 var sourceProperties = excludeProperties(getPropertiesOfObjectType(source), excludedProperties);
50289                 var targetProperties = excludeProperties(getPropertiesOfObjectType(target), excludedProperties);
50290                 if (sourceProperties.length !== targetProperties.length) {
50291                     return 0 /* False */;
50292                 }
50293                 var result = -1 /* True */;
50294                 for (var _i = 0, sourceProperties_1 = sourceProperties; _i < sourceProperties_1.length; _i++) {
50295                     var sourceProp = sourceProperties_1[_i];
50296                     var targetProp = getPropertyOfObjectType(target, sourceProp.escapedName);
50297                     if (!targetProp) {
50298                         return 0 /* False */;
50299                     }
50300                     var related = compareProperties(sourceProp, targetProp, isRelatedTo);
50301                     if (!related) {
50302                         return 0 /* False */;
50303                     }
50304                     result &= related;
50305                 }
50306                 return result;
50307             }
50308             function signaturesRelatedTo(source, target, kind, reportErrors) {
50309                 if (relation === identityRelation) {
50310                     return signaturesIdenticalTo(source, target, kind);
50311                 }
50312                 if (target === anyFunctionType || source === anyFunctionType) {
50313                     return -1 /* True */;
50314                 }
50315                 var sourceIsJSConstructor = source.symbol && isJSConstructor(source.symbol.valueDeclaration);
50316                 var targetIsJSConstructor = target.symbol && isJSConstructor(target.symbol.valueDeclaration);
50317                 var sourceSignatures = getSignaturesOfType(source, (sourceIsJSConstructor && kind === 1 /* Construct */) ?
50318                     0 /* Call */ : kind);
50319                 var targetSignatures = getSignaturesOfType(target, (targetIsJSConstructor && kind === 1 /* Construct */) ?
50320                     0 /* Call */ : kind);
50321                 if (kind === 1 /* Construct */ && sourceSignatures.length && targetSignatures.length) {
50322                     if (ts.isAbstractConstructorType(source) && !ts.isAbstractConstructorType(target)) {
50323                         // An abstract constructor type is not assignable to a non-abstract constructor type
50324                         // as it would otherwise be possible to new an abstract class. Note that the assignability
50325                         // check we perform for an extends clause excludes construct signatures from the target,
50326                         // so this check never proceeds.
50327                         if (reportErrors) {
50328                             reportError(ts.Diagnostics.Cannot_assign_an_abstract_constructor_type_to_a_non_abstract_constructor_type);
50329                         }
50330                         return 0 /* False */;
50331                     }
50332                     if (!constructorVisibilitiesAreCompatible(sourceSignatures[0], targetSignatures[0], reportErrors)) {
50333                         return 0 /* False */;
50334                     }
50335                 }
50336                 var result = -1 /* True */;
50337                 var saveErrorInfo = captureErrorCalculationState();
50338                 var incompatibleReporter = kind === 1 /* Construct */ ? reportIncompatibleConstructSignatureReturn : reportIncompatibleCallSignatureReturn;
50339                 if (ts.getObjectFlags(source) & 64 /* Instantiated */ && ts.getObjectFlags(target) & 64 /* Instantiated */ && source.symbol === target.symbol) {
50340                     // We have instantiations of the same anonymous type (which typically will be the type of a
50341                     // method). Simply do a pairwise comparison of the signatures in the two signature lists instead
50342                     // of the much more expensive N * M comparison matrix we explore below. We erase type parameters
50343                     // as they are known to always be the same.
50344                     for (var i = 0; i < targetSignatures.length; i++) {
50345                         var related = signatureRelatedTo(sourceSignatures[i], targetSignatures[i], /*erase*/ true, reportErrors, incompatibleReporter(sourceSignatures[i], targetSignatures[i]));
50346                         if (!related) {
50347                             return 0 /* False */;
50348                         }
50349                         result &= related;
50350                     }
50351                 }
50352                 else if (sourceSignatures.length === 1 && targetSignatures.length === 1) {
50353                     // For simple functions (functions with a single signature) we only erase type parameters for
50354                     // the comparable relation. Otherwise, if the source signature is generic, we instantiate it
50355                     // in the context of the target signature before checking the relationship. Ideally we'd do
50356                     // this regardless of the number of signatures, but the potential costs are prohibitive due
50357                     // to the quadratic nature of the logic below.
50358                     var eraseGenerics = relation === comparableRelation || !!compilerOptions.noStrictGenericChecks;
50359                     result = signatureRelatedTo(sourceSignatures[0], targetSignatures[0], eraseGenerics, reportErrors, incompatibleReporter(sourceSignatures[0], targetSignatures[0]));
50360                 }
50361                 else {
50362                     outer: for (var _i = 0, targetSignatures_1 = targetSignatures; _i < targetSignatures_1.length; _i++) {
50363                         var t = targetSignatures_1[_i];
50364                         // Only elaborate errors from the first failure
50365                         var shouldElaborateErrors = reportErrors;
50366                         for (var _a = 0, sourceSignatures_1 = sourceSignatures; _a < sourceSignatures_1.length; _a++) {
50367                             var s = sourceSignatures_1[_a];
50368                             var related = signatureRelatedTo(s, t, /*erase*/ true, shouldElaborateErrors, incompatibleReporter(s, t));
50369                             if (related) {
50370                                 result &= related;
50371                                 resetErrorInfo(saveErrorInfo);
50372                                 continue outer;
50373                             }
50374                             shouldElaborateErrors = false;
50375                         }
50376                         if (shouldElaborateErrors) {
50377                             reportError(ts.Diagnostics.Type_0_provides_no_match_for_the_signature_1, typeToString(source), signatureToString(t, /*enclosingDeclaration*/ undefined, /*flags*/ undefined, kind));
50378                         }
50379                         return 0 /* False */;
50380                     }
50381                 }
50382                 return result;
50383             }
50384             function reportIncompatibleCallSignatureReturn(siga, sigb) {
50385                 if (siga.parameters.length === 0 && sigb.parameters.length === 0) {
50386                     return function (source, target) { return reportIncompatibleError(ts.Diagnostics.Call_signatures_with_no_arguments_have_incompatible_return_types_0_and_1, typeToString(source), typeToString(target)); };
50387                 }
50388                 return function (source, target) { return reportIncompatibleError(ts.Diagnostics.Call_signature_return_types_0_and_1_are_incompatible, typeToString(source), typeToString(target)); };
50389             }
50390             function reportIncompatibleConstructSignatureReturn(siga, sigb) {
50391                 if (siga.parameters.length === 0 && sigb.parameters.length === 0) {
50392                     return function (source, target) { return reportIncompatibleError(ts.Diagnostics.Construct_signatures_with_no_arguments_have_incompatible_return_types_0_and_1, typeToString(source), typeToString(target)); };
50393                 }
50394                 return function (source, target) { return reportIncompatibleError(ts.Diagnostics.Construct_signature_return_types_0_and_1_are_incompatible, typeToString(source), typeToString(target)); };
50395             }
50396             /**
50397              * See signatureAssignableTo, compareSignaturesIdentical
50398              */
50399             function signatureRelatedTo(source, target, erase, reportErrors, incompatibleReporter) {
50400                 return compareSignaturesRelated(erase ? getErasedSignature(source) : source, erase ? getErasedSignature(target) : target, relation === strictSubtypeRelation ? 8 /* StrictArity */ : 0, reportErrors, reportError, incompatibleReporter, isRelatedTo, makeFunctionTypeMapper(reportUnreliableMarkers));
50401             }
50402             function signaturesIdenticalTo(source, target, kind) {
50403                 var sourceSignatures = getSignaturesOfType(source, kind);
50404                 var targetSignatures = getSignaturesOfType(target, kind);
50405                 if (sourceSignatures.length !== targetSignatures.length) {
50406                     return 0 /* False */;
50407                 }
50408                 var result = -1 /* True */;
50409                 for (var i = 0; i < sourceSignatures.length; i++) {
50410                     var related = compareSignaturesIdentical(sourceSignatures[i], targetSignatures[i], /*partialMatch*/ false, /*ignoreThisTypes*/ false, /*ignoreReturnTypes*/ false, isRelatedTo);
50411                     if (!related) {
50412                         return 0 /* False */;
50413                     }
50414                     result &= related;
50415                 }
50416                 return result;
50417             }
50418             function eachPropertyRelatedTo(source, target, kind, reportErrors) {
50419                 var result = -1 /* True */;
50420                 var props = source.flags & 2097152 /* Intersection */ ? getPropertiesOfUnionOrIntersectionType(source) : getPropertiesOfObjectType(source);
50421                 for (var _i = 0, props_2 = props; _i < props_2.length; _i++) {
50422                     var prop = props_2[_i];
50423                     // Skip over ignored JSX and symbol-named members
50424                     if (isIgnoredJsxProperty(source, prop)) {
50425                         continue;
50426                     }
50427                     var nameType = getSymbolLinks(prop).nameType;
50428                     if (nameType && nameType.flags & 8192 /* UniqueESSymbol */) {
50429                         continue;
50430                     }
50431                     if (kind === 0 /* String */ || isNumericLiteralName(prop.escapedName)) {
50432                         var related = isRelatedTo(getTypeOfSymbol(prop), target, reportErrors);
50433                         if (!related) {
50434                             if (reportErrors) {
50435                                 reportError(ts.Diagnostics.Property_0_is_incompatible_with_index_signature, symbolToString(prop));
50436                             }
50437                             return 0 /* False */;
50438                         }
50439                         result &= related;
50440                     }
50441                 }
50442                 return result;
50443             }
50444             function indexTypeRelatedTo(sourceType, targetType, reportErrors) {
50445                 var related = isRelatedTo(sourceType, targetType, reportErrors);
50446                 if (!related && reportErrors) {
50447                     reportError(ts.Diagnostics.Index_signatures_are_incompatible);
50448                 }
50449                 return related;
50450             }
50451             function indexTypesRelatedTo(source, target, kind, sourceIsPrimitive, reportErrors, intersectionState) {
50452                 if (relation === identityRelation) {
50453                     return indexTypesIdenticalTo(source, target, kind);
50454                 }
50455                 var targetType = getIndexTypeOfType(target, kind);
50456                 if (!targetType || targetType.flags & 1 /* Any */ && !sourceIsPrimitive) {
50457                     // Index signature of type any permits assignment from everything but primitives
50458                     return -1 /* True */;
50459                 }
50460                 if (isGenericMappedType(source)) {
50461                     // A generic mapped type { [P in K]: T } is related to an index signature { [x: string]: U }
50462                     // if T is related to U.
50463                     return kind === 0 /* String */ ? isRelatedTo(getTemplateTypeFromMappedType(source), targetType, reportErrors) : 0 /* False */;
50464                 }
50465                 var indexType = getIndexTypeOfType(source, kind) || kind === 1 /* Number */ && getIndexTypeOfType(source, 0 /* String */);
50466                 if (indexType) {
50467                     return indexTypeRelatedTo(indexType, targetType, reportErrors);
50468                 }
50469                 if (!(intersectionState & 1 /* Source */) && isObjectTypeWithInferableIndex(source)) {
50470                     // Intersection constituents are never considered to have an inferred index signature
50471                     var related = eachPropertyRelatedTo(source, targetType, kind, reportErrors);
50472                     if (related && kind === 0 /* String */) {
50473                         var numberIndexType = getIndexTypeOfType(source, 1 /* Number */);
50474                         if (numberIndexType) {
50475                             related &= indexTypeRelatedTo(numberIndexType, targetType, reportErrors);
50476                         }
50477                     }
50478                     return related;
50479                 }
50480                 if (reportErrors) {
50481                     reportError(ts.Diagnostics.Index_signature_is_missing_in_type_0, typeToString(source));
50482                 }
50483                 return 0 /* False */;
50484             }
50485             function indexTypesIdenticalTo(source, target, indexKind) {
50486                 var targetInfo = getIndexInfoOfType(target, indexKind);
50487                 var sourceInfo = getIndexInfoOfType(source, indexKind);
50488                 if (!sourceInfo && !targetInfo) {
50489                     return -1 /* True */;
50490                 }
50491                 if (sourceInfo && targetInfo && sourceInfo.isReadonly === targetInfo.isReadonly) {
50492                     return isRelatedTo(sourceInfo.type, targetInfo.type);
50493                 }
50494                 return 0 /* False */;
50495             }
50496             function constructorVisibilitiesAreCompatible(sourceSignature, targetSignature, reportErrors) {
50497                 if (!sourceSignature.declaration || !targetSignature.declaration) {
50498                     return true;
50499                 }
50500                 var sourceAccessibility = ts.getSelectedModifierFlags(sourceSignature.declaration, 24 /* NonPublicAccessibilityModifier */);
50501                 var targetAccessibility = ts.getSelectedModifierFlags(targetSignature.declaration, 24 /* NonPublicAccessibilityModifier */);
50502                 // A public, protected and private signature is assignable to a private signature.
50503                 if (targetAccessibility === 8 /* Private */) {
50504                     return true;
50505                 }
50506                 // A public and protected signature is assignable to a protected signature.
50507                 if (targetAccessibility === 16 /* Protected */ && sourceAccessibility !== 8 /* Private */) {
50508                     return true;
50509                 }
50510                 // Only a public signature is assignable to public signature.
50511                 if (targetAccessibility !== 16 /* Protected */ && !sourceAccessibility) {
50512                     return true;
50513                 }
50514                 if (reportErrors) {
50515                     reportError(ts.Diagnostics.Cannot_assign_a_0_constructor_type_to_a_1_constructor_type, visibilityToString(sourceAccessibility), visibilityToString(targetAccessibility));
50516                 }
50517                 return false;
50518             }
50519         }
50520         function getBestMatchingType(source, target, isRelatedTo) {
50521             if (isRelatedTo === void 0) { isRelatedTo = compareTypesAssignable; }
50522             return findMatchingDiscriminantType(source, target, isRelatedTo, /*skipPartial*/ true) ||
50523                 findMatchingTypeReferenceOrTypeAliasReference(source, target) ||
50524                 findBestTypeForObjectLiteral(source, target) ||
50525                 findBestTypeForInvokable(source, target) ||
50526                 findMostOverlappyType(source, target);
50527         }
50528         function discriminateTypeByDiscriminableItems(target, discriminators, related, defaultValue, skipPartial) {
50529             // undefined=unknown, true=discriminated, false=not discriminated
50530             // The state of each type progresses from left to right. Discriminated types stop at 'true'.
50531             var discriminable = target.types.map(function (_) { return undefined; });
50532             for (var _i = 0, discriminators_1 = discriminators; _i < discriminators_1.length; _i++) {
50533                 var _a = discriminators_1[_i], getDiscriminatingType = _a[0], propertyName = _a[1];
50534                 var targetProp = getUnionOrIntersectionProperty(target, propertyName);
50535                 if (skipPartial && targetProp && ts.getCheckFlags(targetProp) & 16 /* ReadPartial */) {
50536                     continue;
50537                 }
50538                 var i = 0;
50539                 for (var _b = 0, _c = target.types; _b < _c.length; _b++) {
50540                     var type = _c[_b];
50541                     var targetType = getTypeOfPropertyOfType(type, propertyName);
50542                     if (targetType && related(getDiscriminatingType(), targetType)) {
50543                         discriminable[i] = discriminable[i] === undefined ? true : discriminable[i];
50544                     }
50545                     else {
50546                         discriminable[i] = false;
50547                     }
50548                     i++;
50549                 }
50550             }
50551             var match = discriminable.indexOf(/*searchElement*/ true);
50552             // make sure exactly 1 matches before returning it
50553             return match === -1 || discriminable.indexOf(/*searchElement*/ true, match + 1) !== -1 ? defaultValue : target.types[match];
50554         }
50555         /**
50556          * A type is 'weak' if it is an object type with at least one optional property
50557          * and no required properties, call/construct signatures or index signatures
50558          */
50559         function isWeakType(type) {
50560             if (type.flags & 524288 /* Object */) {
50561                 var resolved = resolveStructuredTypeMembers(type);
50562                 return resolved.callSignatures.length === 0 && resolved.constructSignatures.length === 0 &&
50563                     !resolved.stringIndexInfo && !resolved.numberIndexInfo &&
50564                     resolved.properties.length > 0 &&
50565                     ts.every(resolved.properties, function (p) { return !!(p.flags & 16777216 /* Optional */); });
50566             }
50567             if (type.flags & 2097152 /* Intersection */) {
50568                 return ts.every(type.types, isWeakType);
50569             }
50570             return false;
50571         }
50572         function hasCommonProperties(source, target, isComparingJsxAttributes) {
50573             for (var _i = 0, _a = getPropertiesOfType(source); _i < _a.length; _i++) {
50574                 var prop = _a[_i];
50575                 if (isKnownProperty(target, prop.escapedName, isComparingJsxAttributes)) {
50576                     return true;
50577                 }
50578             }
50579             return false;
50580         }
50581         // Return a type reference where the source type parameter is replaced with the target marker
50582         // type, and flag the result as a marker type reference.
50583         function getMarkerTypeReference(type, source, target) {
50584             var result = createTypeReference(type, ts.map(type.typeParameters, function (t) { return t === source ? target : t; }));
50585             result.objectFlags |= 8192 /* MarkerType */;
50586             return result;
50587         }
50588         function getAliasVariances(symbol) {
50589             var links = getSymbolLinks(symbol);
50590             return getVariancesWorker(links.typeParameters, links, function (_links, param, marker) {
50591                 var type = getTypeAliasInstantiation(symbol, instantiateTypes(links.typeParameters, makeUnaryTypeMapper(param, marker)));
50592                 type.aliasTypeArgumentsContainsMarker = true;
50593                 return type;
50594             });
50595         }
50596         // Return an array containing the variance of each type parameter. The variance is effectively
50597         // a digest of the type comparisons that occur for each type argument when instantiations of the
50598         // generic type are structurally compared. We infer the variance information by comparing
50599         // instantiations of the generic type for type arguments with known relations. The function
50600         // returns the emptyArray singleton when invoked recursively for the given generic type.
50601         function getVariancesWorker(typeParameters, cache, createMarkerType) {
50602             if (typeParameters === void 0) { typeParameters = ts.emptyArray; }
50603             var variances = cache.variances;
50604             if (!variances) {
50605                 // The emptyArray singleton is used to signal a recursive invocation.
50606                 cache.variances = ts.emptyArray;
50607                 variances = [];
50608                 var _loop_16 = function (tp) {
50609                     var unmeasurable = false;
50610                     var unreliable = false;
50611                     var oldHandler = outofbandVarianceMarkerHandler;
50612                     outofbandVarianceMarkerHandler = function (onlyUnreliable) { return onlyUnreliable ? unreliable = true : unmeasurable = true; };
50613                     // We first compare instantiations where the type parameter is replaced with
50614                     // marker types that have a known subtype relationship. From this we can infer
50615                     // invariance, covariance, contravariance or bivariance.
50616                     var typeWithSuper = createMarkerType(cache, tp, markerSuperType);
50617                     var typeWithSub = createMarkerType(cache, tp, markerSubType);
50618                     var variance = (isTypeAssignableTo(typeWithSub, typeWithSuper) ? 1 /* Covariant */ : 0) |
50619                         (isTypeAssignableTo(typeWithSuper, typeWithSub) ? 2 /* Contravariant */ : 0);
50620                     // If the instantiations appear to be related bivariantly it may be because the
50621                     // type parameter is independent (i.e. it isn't witnessed anywhere in the generic
50622                     // type). To determine this we compare instantiations where the type parameter is
50623                     // replaced with marker types that are known to be unrelated.
50624                     if (variance === 3 /* Bivariant */ && isTypeAssignableTo(createMarkerType(cache, tp, markerOtherType), typeWithSuper)) {
50625                         variance = 4 /* Independent */;
50626                     }
50627                     outofbandVarianceMarkerHandler = oldHandler;
50628                     if (unmeasurable || unreliable) {
50629                         if (unmeasurable) {
50630                             variance |= 8 /* Unmeasurable */;
50631                         }
50632                         if (unreliable) {
50633                             variance |= 16 /* Unreliable */;
50634                         }
50635                     }
50636                     variances.push(variance);
50637                 };
50638                 for (var _i = 0, typeParameters_1 = typeParameters; _i < typeParameters_1.length; _i++) {
50639                     var tp = typeParameters_1[_i];
50640                     _loop_16(tp);
50641                 }
50642                 cache.variances = variances;
50643             }
50644             return variances;
50645         }
50646         function getVariances(type) {
50647             // Arrays and tuples are known to be covariant, no need to spend time computing this.
50648             if (type === globalArrayType || type === globalReadonlyArrayType || type.objectFlags & 8 /* Tuple */) {
50649                 return arrayVariances;
50650             }
50651             return getVariancesWorker(type.typeParameters, type, getMarkerTypeReference);
50652         }
50653         // Return true if the given type reference has a 'void' type argument for a covariant type parameter.
50654         // See comment at call in recursiveTypeRelatedTo for when this case matters.
50655         function hasCovariantVoidArgument(typeArguments, variances) {
50656             for (var i = 0; i < variances.length; i++) {
50657                 if ((variances[i] & 7 /* VarianceMask */) === 1 /* Covariant */ && typeArguments[i].flags & 16384 /* Void */) {
50658                     return true;
50659                 }
50660             }
50661             return false;
50662         }
50663         function isUnconstrainedTypeParameter(type) {
50664             return type.flags & 262144 /* TypeParameter */ && !getConstraintOfTypeParameter(type);
50665         }
50666         function isNonDeferredTypeReference(type) {
50667             return !!(ts.getObjectFlags(type) & 4 /* Reference */) && !type.node;
50668         }
50669         function isTypeReferenceWithGenericArguments(type) {
50670             return isNonDeferredTypeReference(type) && ts.some(getTypeArguments(type), function (t) { return isUnconstrainedTypeParameter(t) || isTypeReferenceWithGenericArguments(t); });
50671         }
50672         /**
50673          * getTypeReferenceId(A<T, number, U>) returns "111=0-12=1"
50674          *   where A.id=111 and number.id=12
50675          */
50676         function getTypeReferenceId(type, typeParameters, depth) {
50677             if (depth === void 0) { depth = 0; }
50678             var result = "" + type.target.id;
50679             for (var _i = 0, _a = getTypeArguments(type); _i < _a.length; _i++) {
50680                 var t = _a[_i];
50681                 if (isUnconstrainedTypeParameter(t)) {
50682                     var index = typeParameters.indexOf(t);
50683                     if (index < 0) {
50684                         index = typeParameters.length;
50685                         typeParameters.push(t);
50686                     }
50687                     result += "=" + index;
50688                 }
50689                 else if (depth < 4 && isTypeReferenceWithGenericArguments(t)) {
50690                     result += "<" + getTypeReferenceId(t, typeParameters, depth + 1) + ">";
50691                 }
50692                 else {
50693                     result += "-" + t.id;
50694                 }
50695             }
50696             return result;
50697         }
50698         /**
50699          * To improve caching, the relation key for two generic types uses the target's id plus ids of the type parameters.
50700          * For other cases, the types ids are used.
50701          */
50702         function getRelationKey(source, target, intersectionState, relation) {
50703             if (relation === identityRelation && source.id > target.id) {
50704                 var temp = source;
50705                 source = target;
50706                 target = temp;
50707             }
50708             var postFix = intersectionState ? ":" + intersectionState : "";
50709             if (isTypeReferenceWithGenericArguments(source) && isTypeReferenceWithGenericArguments(target)) {
50710                 var typeParameters = [];
50711                 return getTypeReferenceId(source, typeParameters) + "," + getTypeReferenceId(target, typeParameters) + postFix;
50712             }
50713             return source.id + "," + target.id + postFix;
50714         }
50715         // Invoke the callback for each underlying property symbol of the given symbol and return the first
50716         // value that isn't undefined.
50717         function forEachProperty(prop, callback) {
50718             if (ts.getCheckFlags(prop) & 6 /* Synthetic */) {
50719                 for (var _i = 0, _a = prop.containingType.types; _i < _a.length; _i++) {
50720                     var t = _a[_i];
50721                     var p = getPropertyOfType(t, prop.escapedName);
50722                     var result = p && forEachProperty(p, callback);
50723                     if (result) {
50724                         return result;
50725                     }
50726                 }
50727                 return undefined;
50728             }
50729             return callback(prop);
50730         }
50731         // Return the declaring class type of a property or undefined if property not declared in class
50732         function getDeclaringClass(prop) {
50733             return prop.parent && prop.parent.flags & 32 /* Class */ ? getDeclaredTypeOfSymbol(getParentOfSymbol(prop)) : undefined;
50734         }
50735         // Return true if some underlying source property is declared in a class that derives
50736         // from the given base class.
50737         function isPropertyInClassDerivedFrom(prop, baseClass) {
50738             return forEachProperty(prop, function (sp) {
50739                 var sourceClass = getDeclaringClass(sp);
50740                 return sourceClass ? hasBaseType(sourceClass, baseClass) : false;
50741             });
50742         }
50743         // Return true if source property is a valid override of protected parts of target property.
50744         function isValidOverrideOf(sourceProp, targetProp) {
50745             return !forEachProperty(targetProp, function (tp) { return ts.getDeclarationModifierFlagsFromSymbol(tp) & 16 /* Protected */ ?
50746                 !isPropertyInClassDerivedFrom(sourceProp, getDeclaringClass(tp)) : false; });
50747         }
50748         // Return true if the given class derives from each of the declaring classes of the protected
50749         // constituents of the given property.
50750         function isClassDerivedFromDeclaringClasses(checkClass, prop) {
50751             return forEachProperty(prop, function (p) { return ts.getDeclarationModifierFlagsFromSymbol(p) & 16 /* Protected */ ?
50752                 !hasBaseType(checkClass, getDeclaringClass(p)) : false; }) ? undefined : checkClass;
50753         }
50754         // Return true if the given type is deeply nested. We consider this to be the case when structural type comparisons
50755         // for 5 or more occurrences or instantiations of the type have been recorded on the given stack. It is possible,
50756         // though highly unlikely, for this test to be true in a situation where a chain of instantiations is not infinitely
50757         // expanding. Effectively, we will generate a false positive when two types are structurally equal to at least 5
50758         // levels, but unequal at some level beyond that.
50759         // In addition, this will also detect when an indexed access has been chained off of 5 or more times (which is essentially
50760         // the dual of the structural comparison), and likewise mark the type as deeply nested, potentially adding false positives
50761         // for finite but deeply expanding indexed accesses (eg, for `Q[P1][P2][P3][P4][P5]`).
50762         function isDeeplyNestedType(type, stack, depth) {
50763             // We track all object types that have an associated symbol (representing the origin of the type)
50764             if (depth >= 5 && type.flags & 524288 /* Object */ && !isObjectOrArrayLiteralType(type)) {
50765                 var symbol = type.symbol;
50766                 if (symbol) {
50767                     var count = 0;
50768                     for (var i = 0; i < depth; i++) {
50769                         var t = stack[i];
50770                         if (t.flags & 524288 /* Object */ && t.symbol === symbol) {
50771                             count++;
50772                             if (count >= 5)
50773                                 return true;
50774                         }
50775                     }
50776                 }
50777             }
50778             if (depth >= 5 && type.flags & 8388608 /* IndexedAccess */) {
50779                 var root = getRootObjectTypeFromIndexedAccessChain(type);
50780                 var count = 0;
50781                 for (var i = 0; i < depth; i++) {
50782                     var t = stack[i];
50783                     if (getRootObjectTypeFromIndexedAccessChain(t) === root) {
50784                         count++;
50785                         if (count >= 5)
50786                             return true;
50787                     }
50788                 }
50789             }
50790             return false;
50791         }
50792         /**
50793          * Gets the leftmost object type in a chain of indexed accesses, eg, in A[P][Q], returns A
50794          */
50795         function getRootObjectTypeFromIndexedAccessChain(type) {
50796             var t = type;
50797             while (t.flags & 8388608 /* IndexedAccess */) {
50798                 t = t.objectType;
50799             }
50800             return t;
50801         }
50802         function isPropertyIdenticalTo(sourceProp, targetProp) {
50803             return compareProperties(sourceProp, targetProp, compareTypesIdentical) !== 0 /* False */;
50804         }
50805         function compareProperties(sourceProp, targetProp, compareTypes) {
50806             // Two members are considered identical when
50807             // - they are public properties with identical names, optionality, and types,
50808             // - they are private or protected properties originating in the same declaration and having identical types
50809             if (sourceProp === targetProp) {
50810                 return -1 /* True */;
50811             }
50812             var sourcePropAccessibility = ts.getDeclarationModifierFlagsFromSymbol(sourceProp) & 24 /* NonPublicAccessibilityModifier */;
50813             var targetPropAccessibility = ts.getDeclarationModifierFlagsFromSymbol(targetProp) & 24 /* NonPublicAccessibilityModifier */;
50814             if (sourcePropAccessibility !== targetPropAccessibility) {
50815                 return 0 /* False */;
50816             }
50817             if (sourcePropAccessibility) {
50818                 if (getTargetSymbol(sourceProp) !== getTargetSymbol(targetProp)) {
50819                     return 0 /* False */;
50820                 }
50821             }
50822             else {
50823                 if ((sourceProp.flags & 16777216 /* Optional */) !== (targetProp.flags & 16777216 /* Optional */)) {
50824                     return 0 /* False */;
50825                 }
50826             }
50827             if (isReadonlySymbol(sourceProp) !== isReadonlySymbol(targetProp)) {
50828                 return 0 /* False */;
50829             }
50830             return compareTypes(getTypeOfSymbol(sourceProp), getTypeOfSymbol(targetProp));
50831         }
50832         function isMatchingSignature(source, target, partialMatch) {
50833             var sourceParameterCount = getParameterCount(source);
50834             var targetParameterCount = getParameterCount(target);
50835             var sourceMinArgumentCount = getMinArgumentCount(source);
50836             var targetMinArgumentCount = getMinArgumentCount(target);
50837             var sourceHasRestParameter = hasEffectiveRestParameter(source);
50838             var targetHasRestParameter = hasEffectiveRestParameter(target);
50839             // A source signature matches a target signature if the two signatures have the same number of required,
50840             // optional, and rest parameters.
50841             if (sourceParameterCount === targetParameterCount &&
50842                 sourceMinArgumentCount === targetMinArgumentCount &&
50843                 sourceHasRestParameter === targetHasRestParameter) {
50844                 return true;
50845             }
50846             // A source signature partially matches a target signature if the target signature has no fewer required
50847             // parameters
50848             if (partialMatch && sourceMinArgumentCount <= targetMinArgumentCount) {
50849                 return true;
50850             }
50851             return false;
50852         }
50853         /**
50854          * See signatureRelatedTo, compareSignaturesIdentical
50855          */
50856         function compareSignaturesIdentical(source, target, partialMatch, ignoreThisTypes, ignoreReturnTypes, compareTypes) {
50857             // TODO (drosen): De-duplicate code between related functions.
50858             if (source === target) {
50859                 return -1 /* True */;
50860             }
50861             if (!(isMatchingSignature(source, target, partialMatch))) {
50862                 return 0 /* False */;
50863             }
50864             // Check that the two signatures have the same number of type parameters.
50865             if (ts.length(source.typeParameters) !== ts.length(target.typeParameters)) {
50866                 return 0 /* False */;
50867             }
50868             // Check that type parameter constraints and defaults match. If they do, instantiate the source
50869             // signature with the type parameters of the target signature and continue the comparison.
50870             if (target.typeParameters) {
50871                 var mapper = createTypeMapper(source.typeParameters, target.typeParameters);
50872                 for (var i = 0; i < target.typeParameters.length; i++) {
50873                     var s = source.typeParameters[i];
50874                     var t = target.typeParameters[i];
50875                     if (!(s === t || compareTypes(instantiateType(getConstraintFromTypeParameter(s), mapper) || unknownType, getConstraintFromTypeParameter(t) || unknownType) &&
50876                         compareTypes(instantiateType(getDefaultFromTypeParameter(s), mapper) || unknownType, getDefaultFromTypeParameter(t) || unknownType))) {
50877                         return 0 /* False */;
50878                     }
50879                 }
50880                 source = instantiateSignature(source, mapper, /*eraseTypeParameters*/ true);
50881             }
50882             var result = -1 /* True */;
50883             if (!ignoreThisTypes) {
50884                 var sourceThisType = getThisTypeOfSignature(source);
50885                 if (sourceThisType) {
50886                     var targetThisType = getThisTypeOfSignature(target);
50887                     if (targetThisType) {
50888                         var related = compareTypes(sourceThisType, targetThisType);
50889                         if (!related) {
50890                             return 0 /* False */;
50891                         }
50892                         result &= related;
50893                     }
50894                 }
50895             }
50896             var targetLen = getParameterCount(target);
50897             for (var i = 0; i < targetLen; i++) {
50898                 var s = getTypeAtPosition(source, i);
50899                 var t = getTypeAtPosition(target, i);
50900                 var related = compareTypes(t, s);
50901                 if (!related) {
50902                     return 0 /* False */;
50903                 }
50904                 result &= related;
50905             }
50906             if (!ignoreReturnTypes) {
50907                 var sourceTypePredicate = getTypePredicateOfSignature(source);
50908                 var targetTypePredicate = getTypePredicateOfSignature(target);
50909                 result &= sourceTypePredicate || targetTypePredicate ?
50910                     compareTypePredicatesIdentical(sourceTypePredicate, targetTypePredicate, compareTypes) :
50911                     compareTypes(getReturnTypeOfSignature(source), getReturnTypeOfSignature(target));
50912             }
50913             return result;
50914         }
50915         function compareTypePredicatesIdentical(source, target, compareTypes) {
50916             return !(source && target && typePredicateKindsMatch(source, target)) ? 0 /* False */ :
50917                 source.type === target.type ? -1 /* True */ :
50918                     source.type && target.type ? compareTypes(source.type, target.type) :
50919                         0 /* False */;
50920         }
50921         function literalTypesWithSameBaseType(types) {
50922             var commonBaseType;
50923             for (var _i = 0, types_12 = types; _i < types_12.length; _i++) {
50924                 var t = types_12[_i];
50925                 var baseType = getBaseTypeOfLiteralType(t);
50926                 if (!commonBaseType) {
50927                     commonBaseType = baseType;
50928                 }
50929                 if (baseType === t || baseType !== commonBaseType) {
50930                     return false;
50931                 }
50932             }
50933             return true;
50934         }
50935         // When the candidate types are all literal types with the same base type, return a union
50936         // of those literal types. Otherwise, return the leftmost type for which no type to the
50937         // right is a supertype.
50938         function getSupertypeOrUnion(types) {
50939             return literalTypesWithSameBaseType(types) ?
50940                 getUnionType(types) :
50941                 ts.reduceLeft(types, function (s, t) { return isTypeSubtypeOf(s, t) ? t : s; });
50942         }
50943         function getCommonSupertype(types) {
50944             if (!strictNullChecks) {
50945                 return getSupertypeOrUnion(types);
50946             }
50947             var primaryTypes = ts.filter(types, function (t) { return !(t.flags & 98304 /* Nullable */); });
50948             return primaryTypes.length ?
50949                 getNullableType(getSupertypeOrUnion(primaryTypes), getFalsyFlagsOfTypes(types) & 98304 /* Nullable */) :
50950                 getUnionType(types, 2 /* Subtype */);
50951         }
50952         // Return the leftmost type for which no type to the right is a subtype.
50953         function getCommonSubtype(types) {
50954             return ts.reduceLeft(types, function (s, t) { return isTypeSubtypeOf(t, s) ? t : s; });
50955         }
50956         function isArrayType(type) {
50957             return !!(ts.getObjectFlags(type) & 4 /* Reference */) && (type.target === globalArrayType || type.target === globalReadonlyArrayType);
50958         }
50959         function isReadonlyArrayType(type) {
50960             return !!(ts.getObjectFlags(type) & 4 /* Reference */) && type.target === globalReadonlyArrayType;
50961         }
50962         function isMutableArrayOrTuple(type) {
50963             return isArrayType(type) && !isReadonlyArrayType(type) || isTupleType(type) && !type.target.readonly;
50964         }
50965         function getElementTypeOfArrayType(type) {
50966             return isArrayType(type) ? getTypeArguments(type)[0] : undefined;
50967         }
50968         function isArrayLikeType(type) {
50969             // A type is array-like if it is a reference to the global Array or global ReadonlyArray type,
50970             // or if it is not the undefined or null type and if it is assignable to ReadonlyArray<any>
50971             return isArrayType(type) || !(type.flags & 98304 /* Nullable */) && isTypeAssignableTo(type, anyReadonlyArrayType);
50972         }
50973         function isEmptyArrayLiteralType(type) {
50974             var elementType = isArrayType(type) ? getTypeArguments(type)[0] : undefined;
50975             return elementType === undefinedWideningType || elementType === implicitNeverType;
50976         }
50977         function isTupleLikeType(type) {
50978             return isTupleType(type) || !!getPropertyOfType(type, "0");
50979         }
50980         function isArrayOrTupleLikeType(type) {
50981             return isArrayLikeType(type) || isTupleLikeType(type);
50982         }
50983         function getTupleElementType(type, index) {
50984             var propType = getTypeOfPropertyOfType(type, "" + index);
50985             if (propType) {
50986                 return propType;
50987             }
50988             if (everyType(type, isTupleType)) {
50989                 return mapType(type, function (t) { return getRestTypeOfTupleType(t) || undefinedType; });
50990             }
50991             return undefined;
50992         }
50993         function isNeitherUnitTypeNorNever(type) {
50994             return !(type.flags & (109440 /* Unit */ | 131072 /* Never */));
50995         }
50996         function isUnitType(type) {
50997             return !!(type.flags & 109440 /* Unit */);
50998         }
50999         function isLiteralType(type) {
51000             return type.flags & 16 /* Boolean */ ? true :
51001                 type.flags & 1048576 /* Union */ ? type.flags & 1024 /* EnumLiteral */ ? true : ts.every(type.types, isUnitType) :
51002                     isUnitType(type);
51003         }
51004         function getBaseTypeOfLiteralType(type) {
51005             return type.flags & 1024 /* EnumLiteral */ ? getBaseTypeOfEnumLiteralType(type) :
51006                 type.flags & 128 /* StringLiteral */ ? stringType :
51007                     type.flags & 256 /* NumberLiteral */ ? numberType :
51008                         type.flags & 2048 /* BigIntLiteral */ ? bigintType :
51009                             type.flags & 512 /* BooleanLiteral */ ? booleanType :
51010                                 type.flags & 1048576 /* Union */ ? getUnionType(ts.sameMap(type.types, getBaseTypeOfLiteralType)) :
51011                                     type;
51012         }
51013         function getWidenedLiteralType(type) {
51014             return type.flags & 1024 /* EnumLiteral */ && isFreshLiteralType(type) ? getBaseTypeOfEnumLiteralType(type) :
51015                 type.flags & 128 /* StringLiteral */ && isFreshLiteralType(type) ? stringType :
51016                     type.flags & 256 /* NumberLiteral */ && isFreshLiteralType(type) ? numberType :
51017                         type.flags & 2048 /* BigIntLiteral */ && isFreshLiteralType(type) ? bigintType :
51018                             type.flags & 512 /* BooleanLiteral */ && isFreshLiteralType(type) ? booleanType :
51019                                 type.flags & 1048576 /* Union */ ? getUnionType(ts.sameMap(type.types, getWidenedLiteralType)) :
51020                                     type;
51021         }
51022         function getWidenedUniqueESSymbolType(type) {
51023             return type.flags & 8192 /* UniqueESSymbol */ ? esSymbolType :
51024                 type.flags & 1048576 /* Union */ ? getUnionType(ts.sameMap(type.types, getWidenedUniqueESSymbolType)) :
51025                     type;
51026         }
51027         function getWidenedLiteralLikeTypeForContextualType(type, contextualType) {
51028             if (!isLiteralOfContextualType(type, contextualType)) {
51029                 type = getWidenedUniqueESSymbolType(getWidenedLiteralType(type));
51030             }
51031             return type;
51032         }
51033         function getWidenedLiteralLikeTypeForContextualReturnTypeIfNeeded(type, contextualSignatureReturnType, isAsync) {
51034             if (type && isUnitType(type)) {
51035                 var contextualType = !contextualSignatureReturnType ? undefined :
51036                     isAsync ? getPromisedTypeOfPromise(contextualSignatureReturnType) :
51037                         contextualSignatureReturnType;
51038                 type = getWidenedLiteralLikeTypeForContextualType(type, contextualType);
51039             }
51040             return type;
51041         }
51042         function getWidenedLiteralLikeTypeForContextualIterationTypeIfNeeded(type, contextualSignatureReturnType, kind, isAsyncGenerator) {
51043             if (type && isUnitType(type)) {
51044                 var contextualType = !contextualSignatureReturnType ? undefined :
51045                     getIterationTypeOfGeneratorFunctionReturnType(kind, contextualSignatureReturnType, isAsyncGenerator);
51046                 type = getWidenedLiteralLikeTypeForContextualType(type, contextualType);
51047             }
51048             return type;
51049         }
51050         /**
51051          * Check if a Type was written as a tuple type literal.
51052          * Prefer using isTupleLikeType() unless the use of `elementTypes`/`getTypeArguments` is required.
51053          */
51054         function isTupleType(type) {
51055             return !!(ts.getObjectFlags(type) & 4 /* Reference */ && type.target.objectFlags & 8 /* Tuple */);
51056         }
51057         function getRestTypeOfTupleType(type) {
51058             return type.target.hasRestElement ? getTypeArguments(type)[type.target.typeParameters.length - 1] : undefined;
51059         }
51060         function getRestArrayTypeOfTupleType(type) {
51061             var restType = getRestTypeOfTupleType(type);
51062             return restType && createArrayType(restType);
51063         }
51064         function getLengthOfTupleType(type) {
51065             return getTypeReferenceArity(type) - (type.target.hasRestElement ? 1 : 0);
51066         }
51067         function isZeroBigInt(_a) {
51068             var value = _a.value;
51069             return value.base10Value === "0";
51070         }
51071         function getFalsyFlagsOfTypes(types) {
51072             var result = 0;
51073             for (var _i = 0, types_13 = types; _i < types_13.length; _i++) {
51074                 var t = types_13[_i];
51075                 result |= getFalsyFlags(t);
51076             }
51077             return result;
51078         }
51079         // Returns the String, Number, Boolean, StringLiteral, NumberLiteral, BooleanLiteral, Void, Undefined, or Null
51080         // flags for the string, number, boolean, "", 0, false, void, undefined, or null types respectively. Returns
51081         // no flags for all other types (including non-falsy literal types).
51082         function getFalsyFlags(type) {
51083             return type.flags & 1048576 /* Union */ ? getFalsyFlagsOfTypes(type.types) :
51084                 type.flags & 128 /* StringLiteral */ ? type.value === "" ? 128 /* StringLiteral */ : 0 :
51085                     type.flags & 256 /* NumberLiteral */ ? type.value === 0 ? 256 /* NumberLiteral */ : 0 :
51086                         type.flags & 2048 /* BigIntLiteral */ ? isZeroBigInt(type) ? 2048 /* BigIntLiteral */ : 0 :
51087                             type.flags & 512 /* BooleanLiteral */ ? (type === falseType || type === regularFalseType) ? 512 /* BooleanLiteral */ : 0 :
51088                                 type.flags & 117724 /* PossiblyFalsy */;
51089         }
51090         function removeDefinitelyFalsyTypes(type) {
51091             return getFalsyFlags(type) & 117632 /* DefinitelyFalsy */ ?
51092                 filterType(type, function (t) { return !(getFalsyFlags(t) & 117632 /* DefinitelyFalsy */); }) :
51093                 type;
51094         }
51095         function extractDefinitelyFalsyTypes(type) {
51096             return mapType(type, getDefinitelyFalsyPartOfType);
51097         }
51098         function getDefinitelyFalsyPartOfType(type) {
51099             return type.flags & 4 /* String */ ? emptyStringType :
51100                 type.flags & 8 /* Number */ ? zeroType :
51101                     type.flags & 64 /* BigInt */ ? zeroBigIntType :
51102                         type === regularFalseType ||
51103                             type === falseType ||
51104                             type.flags & (16384 /* Void */ | 32768 /* Undefined */ | 65536 /* Null */) ||
51105                             type.flags & 128 /* StringLiteral */ && type.value === "" ||
51106                             type.flags & 256 /* NumberLiteral */ && type.value === 0 ||
51107                             type.flags & 2048 /* BigIntLiteral */ && isZeroBigInt(type) ? type :
51108                             neverType;
51109         }
51110         /**
51111          * Add undefined or null or both to a type if they are missing.
51112          * @param type - type to add undefined and/or null to if not present
51113          * @param flags - Either TypeFlags.Undefined or TypeFlags.Null, or both
51114          */
51115         function getNullableType(type, flags) {
51116             var missing = (flags & ~type.flags) & (32768 /* Undefined */ | 65536 /* Null */);
51117             return missing === 0 ? type :
51118                 missing === 32768 /* Undefined */ ? getUnionType([type, undefinedType]) :
51119                     missing === 65536 /* Null */ ? getUnionType([type, nullType]) :
51120                         getUnionType([type, undefinedType, nullType]);
51121         }
51122         function getOptionalType(type) {
51123             ts.Debug.assert(strictNullChecks);
51124             return type.flags & 32768 /* Undefined */ ? type : getUnionType([type, undefinedType]);
51125         }
51126         function getGlobalNonNullableTypeInstantiation(type) {
51127             if (!deferredGlobalNonNullableTypeAlias) {
51128                 deferredGlobalNonNullableTypeAlias = getGlobalSymbol("NonNullable", 524288 /* TypeAlias */, /*diagnostic*/ undefined) || unknownSymbol;
51129             }
51130             // Use NonNullable global type alias if available to improve quick info/declaration emit
51131             if (deferredGlobalNonNullableTypeAlias !== unknownSymbol) {
51132                 return getTypeAliasInstantiation(deferredGlobalNonNullableTypeAlias, [type]);
51133             }
51134             return getTypeWithFacts(type, 2097152 /* NEUndefinedOrNull */); // Type alias unavailable, fall back to non-higher-order behavior
51135         }
51136         function getNonNullableType(type) {
51137             return strictNullChecks ? getGlobalNonNullableTypeInstantiation(type) : type;
51138         }
51139         function addOptionalTypeMarker(type) {
51140             return strictNullChecks ? getUnionType([type, optionalType]) : type;
51141         }
51142         function isNotOptionalTypeMarker(type) {
51143             return type !== optionalType;
51144         }
51145         function removeOptionalTypeMarker(type) {
51146             return strictNullChecks ? filterType(type, isNotOptionalTypeMarker) : type;
51147         }
51148         function propagateOptionalTypeMarker(type, node, wasOptional) {
51149             return wasOptional ? ts.isOutermostOptionalChain(node) ? getOptionalType(type) : addOptionalTypeMarker(type) : type;
51150         }
51151         function getOptionalExpressionType(exprType, expression) {
51152             return ts.isExpressionOfOptionalChainRoot(expression) ? getNonNullableType(exprType) :
51153                 ts.isOptionalChain(expression) ? removeOptionalTypeMarker(exprType) :
51154                     exprType;
51155         }
51156         /**
51157          * Is source potentially coercible to target type under `==`.
51158          * Assumes that `source` is a constituent of a union, hence
51159          * the boolean literal flag on the LHS, but not on the RHS.
51160          *
51161          * This does not fully replicate the semantics of `==`. The
51162          * intention is to catch cases that are clearly not right.
51163          *
51164          * Comparing (string | number) to number should not remove the
51165          * string element.
51166          *
51167          * Comparing (string | number) to 1 will remove the string
51168          * element, though this is not sound. This is a pragmatic
51169          * choice.
51170          *
51171          * @see narrowTypeByEquality
51172          *
51173          * @param source
51174          * @param target
51175          */
51176         function isCoercibleUnderDoubleEquals(source, target) {
51177             return ((source.flags & (8 /* Number */ | 4 /* String */ | 512 /* BooleanLiteral */)) !== 0)
51178                 && ((target.flags & (8 /* Number */ | 4 /* String */ | 16 /* Boolean */)) !== 0);
51179         }
51180         /**
51181          * Return true if type was inferred from an object literal, written as an object type literal, or is the shape of a module
51182          * with no call or construct signatures.
51183          */
51184         function isObjectTypeWithInferableIndex(type) {
51185             return type.flags & 2097152 /* Intersection */ ? ts.every(type.types, isObjectTypeWithInferableIndex) :
51186                 !!(type.symbol && (type.symbol.flags & (4096 /* ObjectLiteral */ | 2048 /* TypeLiteral */ | 384 /* Enum */ | 512 /* ValueModule */)) !== 0 &&
51187                     !typeHasCallOrConstructSignatures(type)) || !!(ts.getObjectFlags(type) & 2048 /* ReverseMapped */ && isObjectTypeWithInferableIndex(type.source));
51188         }
51189         function createSymbolWithType(source, type) {
51190             var symbol = createSymbol(source.flags, source.escapedName, ts.getCheckFlags(source) & 8 /* Readonly */);
51191             symbol.declarations = source.declarations;
51192             symbol.parent = source.parent;
51193             symbol.type = type;
51194             symbol.target = source;
51195             if (source.valueDeclaration) {
51196                 symbol.valueDeclaration = source.valueDeclaration;
51197             }
51198             var nameType = getSymbolLinks(source).nameType;
51199             if (nameType) {
51200                 symbol.nameType = nameType;
51201             }
51202             return symbol;
51203         }
51204         function transformTypeOfMembers(type, f) {
51205             var members = ts.createSymbolTable();
51206             for (var _i = 0, _a = getPropertiesOfObjectType(type); _i < _a.length; _i++) {
51207                 var property = _a[_i];
51208                 var original = getTypeOfSymbol(property);
51209                 var updated = f(original);
51210                 members.set(property.escapedName, updated === original ? property : createSymbolWithType(property, updated));
51211             }
51212             return members;
51213         }
51214         /**
51215          * If the the provided object literal is subject to the excess properties check,
51216          * create a new that is exempt. Recursively mark object literal members as exempt.
51217          * Leave signatures alone since they are not subject to the check.
51218          */
51219         function getRegularTypeOfObjectLiteral(type) {
51220             if (!(isObjectLiteralType(type) && ts.getObjectFlags(type) & 32768 /* FreshLiteral */)) {
51221                 return type;
51222             }
51223             var regularType = type.regularType;
51224             if (regularType) {
51225                 return regularType;
51226             }
51227             var resolved = type;
51228             var members = transformTypeOfMembers(type, getRegularTypeOfObjectLiteral);
51229             var regularNew = createAnonymousType(resolved.symbol, members, resolved.callSignatures, resolved.constructSignatures, resolved.stringIndexInfo, resolved.numberIndexInfo);
51230             regularNew.flags = resolved.flags;
51231             regularNew.objectFlags |= resolved.objectFlags & ~32768 /* FreshLiteral */;
51232             type.regularType = regularNew;
51233             return regularNew;
51234         }
51235         function createWideningContext(parent, propertyName, siblings) {
51236             return { parent: parent, propertyName: propertyName, siblings: siblings, resolvedProperties: undefined };
51237         }
51238         function getSiblingsOfContext(context) {
51239             if (!context.siblings) {
51240                 var siblings_1 = [];
51241                 for (var _i = 0, _a = getSiblingsOfContext(context.parent); _i < _a.length; _i++) {
51242                     var type = _a[_i];
51243                     if (isObjectLiteralType(type)) {
51244                         var prop = getPropertyOfObjectType(type, context.propertyName);
51245                         if (prop) {
51246                             forEachType(getTypeOfSymbol(prop), function (t) {
51247                                 siblings_1.push(t);
51248                             });
51249                         }
51250                     }
51251                 }
51252                 context.siblings = siblings_1;
51253             }
51254             return context.siblings;
51255         }
51256         function getPropertiesOfContext(context) {
51257             if (!context.resolvedProperties) {
51258                 var names = ts.createMap();
51259                 for (var _i = 0, _a = getSiblingsOfContext(context); _i < _a.length; _i++) {
51260                     var t = _a[_i];
51261                     if (isObjectLiteralType(t) && !(ts.getObjectFlags(t) & 1024 /* ContainsSpread */)) {
51262                         for (var _b = 0, _c = getPropertiesOfType(t); _b < _c.length; _b++) {
51263                             var prop = _c[_b];
51264                             names.set(prop.escapedName, prop);
51265                         }
51266                     }
51267                 }
51268                 context.resolvedProperties = ts.arrayFrom(names.values());
51269             }
51270             return context.resolvedProperties;
51271         }
51272         function getWidenedProperty(prop, context) {
51273             if (!(prop.flags & 4 /* Property */)) {
51274                 // Since get accessors already widen their return value there is no need to
51275                 // widen accessor based properties here.
51276                 return prop;
51277             }
51278             var original = getTypeOfSymbol(prop);
51279             var propContext = context && createWideningContext(context, prop.escapedName, /*siblings*/ undefined);
51280             var widened = getWidenedTypeWithContext(original, propContext);
51281             return widened === original ? prop : createSymbolWithType(prop, widened);
51282         }
51283         function getUndefinedProperty(prop) {
51284             var cached = undefinedProperties.get(prop.escapedName);
51285             if (cached) {
51286                 return cached;
51287             }
51288             var result = createSymbolWithType(prop, undefinedType);
51289             result.flags |= 16777216 /* Optional */;
51290             undefinedProperties.set(prop.escapedName, result);
51291             return result;
51292         }
51293         function getWidenedTypeOfObjectLiteral(type, context) {
51294             var members = ts.createSymbolTable();
51295             for (var _i = 0, _a = getPropertiesOfObjectType(type); _i < _a.length; _i++) {
51296                 var prop = _a[_i];
51297                 members.set(prop.escapedName, getWidenedProperty(prop, context));
51298             }
51299             if (context) {
51300                 for (var _b = 0, _c = getPropertiesOfContext(context); _b < _c.length; _b++) {
51301                     var prop = _c[_b];
51302                     if (!members.has(prop.escapedName)) {
51303                         members.set(prop.escapedName, getUndefinedProperty(prop));
51304                     }
51305                 }
51306             }
51307             var stringIndexInfo = getIndexInfoOfType(type, 0 /* String */);
51308             var numberIndexInfo = getIndexInfoOfType(type, 1 /* Number */);
51309             var result = createAnonymousType(type.symbol, members, ts.emptyArray, ts.emptyArray, stringIndexInfo && createIndexInfo(getWidenedType(stringIndexInfo.type), stringIndexInfo.isReadonly), numberIndexInfo && createIndexInfo(getWidenedType(numberIndexInfo.type), numberIndexInfo.isReadonly));
51310             result.objectFlags |= (ts.getObjectFlags(type) & (16384 /* JSLiteral */ | 2097152 /* NonInferrableType */)); // Retain js literal flag through widening
51311             return result;
51312         }
51313         function getWidenedType(type) {
51314             return getWidenedTypeWithContext(type, /*context*/ undefined);
51315         }
51316         function getWidenedTypeWithContext(type, context) {
51317             if (ts.getObjectFlags(type) & 1572864 /* RequiresWidening */) {
51318                 if (context === undefined && type.widened) {
51319                     return type.widened;
51320                 }
51321                 var result = void 0;
51322                 if (type.flags & (1 /* Any */ | 98304 /* Nullable */)) {
51323                     result = anyType;
51324                 }
51325                 else if (isObjectLiteralType(type)) {
51326                     result = getWidenedTypeOfObjectLiteral(type, context);
51327                 }
51328                 else if (type.flags & 1048576 /* Union */) {
51329                     var unionContext_1 = context || createWideningContext(/*parent*/ undefined, /*propertyName*/ undefined, type.types);
51330                     var widenedTypes = ts.sameMap(type.types, function (t) { return t.flags & 98304 /* Nullable */ ? t : getWidenedTypeWithContext(t, unionContext_1); });
51331                     // Widening an empty object literal transitions from a highly restrictive type to
51332                     // a highly inclusive one. For that reason we perform subtype reduction here if the
51333                     // union includes empty object types (e.g. reducing {} | string to just {}).
51334                     result = getUnionType(widenedTypes, ts.some(widenedTypes, isEmptyObjectType) ? 2 /* Subtype */ : 1 /* Literal */);
51335                 }
51336                 else if (type.flags & 2097152 /* Intersection */) {
51337                     result = getIntersectionType(ts.sameMap(type.types, getWidenedType));
51338                 }
51339                 else if (isArrayType(type) || isTupleType(type)) {
51340                     result = createTypeReference(type.target, ts.sameMap(getTypeArguments(type), getWidenedType));
51341                 }
51342                 if (result && context === undefined) {
51343                     type.widened = result;
51344                 }
51345                 return result || type;
51346             }
51347             return type;
51348         }
51349         /**
51350          * Reports implicit any errors that occur as a result of widening 'null' and 'undefined'
51351          * to 'any'. A call to reportWideningErrorsInType is normally accompanied by a call to
51352          * getWidenedType. But in some cases getWidenedType is called without reporting errors
51353          * (type argument inference is an example).
51354          *
51355          * The return value indicates whether an error was in fact reported. The particular circumstances
51356          * are on a best effort basis. Currently, if the null or undefined that causes widening is inside
51357          * an object literal property (arbitrarily deeply), this function reports an error. If no error is
51358          * reported, reportImplicitAnyError is a suitable fallback to report a general error.
51359          */
51360         function reportWideningErrorsInType(type) {
51361             var errorReported = false;
51362             if (ts.getObjectFlags(type) & 524288 /* ContainsWideningType */) {
51363                 if (type.flags & 1048576 /* Union */) {
51364                     if (ts.some(type.types, isEmptyObjectType)) {
51365                         errorReported = true;
51366                     }
51367                     else {
51368                         for (var _i = 0, _a = type.types; _i < _a.length; _i++) {
51369                             var t = _a[_i];
51370                             if (reportWideningErrorsInType(t)) {
51371                                 errorReported = true;
51372                             }
51373                         }
51374                     }
51375                 }
51376                 if (isArrayType(type) || isTupleType(type)) {
51377                     for (var _b = 0, _c = getTypeArguments(type); _b < _c.length; _b++) {
51378                         var t = _c[_b];
51379                         if (reportWideningErrorsInType(t)) {
51380                             errorReported = true;
51381                         }
51382                     }
51383                 }
51384                 if (isObjectLiteralType(type)) {
51385                     for (var _d = 0, _e = getPropertiesOfObjectType(type); _d < _e.length; _d++) {
51386                         var p = _e[_d];
51387                         var t = getTypeOfSymbol(p);
51388                         if (ts.getObjectFlags(t) & 524288 /* ContainsWideningType */) {
51389                             if (!reportWideningErrorsInType(t)) {
51390                                 error(p.valueDeclaration, ts.Diagnostics.Object_literal_s_property_0_implicitly_has_an_1_type, symbolToString(p), typeToString(getWidenedType(t)));
51391                             }
51392                             errorReported = true;
51393                         }
51394                     }
51395                 }
51396             }
51397             return errorReported;
51398         }
51399         function reportImplicitAny(declaration, type, wideningKind) {
51400             var typeAsString = typeToString(getWidenedType(type));
51401             if (ts.isInJSFile(declaration) && !ts.isCheckJsEnabledForFile(ts.getSourceFileOfNode(declaration), compilerOptions)) {
51402                 // Only report implicit any errors/suggestions in TS and ts-check JS files
51403                 return;
51404             }
51405             var diagnostic;
51406             switch (declaration.kind) {
51407                 case 209 /* BinaryExpression */:
51408                 case 159 /* PropertyDeclaration */:
51409                 case 158 /* PropertySignature */:
51410                     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;
51411                     break;
51412                 case 156 /* Parameter */:
51413                     var param = declaration;
51414                     if (ts.isIdentifier(param.name) &&
51415                         (ts.isCallSignatureDeclaration(param.parent) || ts.isMethodSignature(param.parent) || ts.isFunctionTypeNode(param.parent)) &&
51416                         param.parent.parameters.indexOf(param) > -1 &&
51417                         (resolveName(param, param.name.escapedText, 788968 /* Type */, undefined, param.name.escapedText, /*isUse*/ true) ||
51418                             param.name.originalKeywordKind && ts.isTypeNodeKind(param.name.originalKeywordKind))) {
51419                         var newName = "arg" + param.parent.parameters.indexOf(param);
51420                         errorOrSuggestion(noImplicitAny, declaration, ts.Diagnostics.Parameter_has_a_name_but_no_type_Did_you_mean_0_Colon_1, newName, ts.declarationNameToString(param.name));
51421                         return;
51422                     }
51423                     diagnostic = declaration.dotDotDotToken ?
51424                         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 :
51425                         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;
51426                     break;
51427                 case 191 /* BindingElement */:
51428                     diagnostic = ts.Diagnostics.Binding_element_0_implicitly_has_an_1_type;
51429                     if (!noImplicitAny) {
51430                         // Don't issue a suggestion for binding elements since the codefix doesn't yet support them.
51431                         return;
51432                     }
51433                     break;
51434                 case 300 /* JSDocFunctionType */:
51435                     error(declaration, ts.Diagnostics.Function_type_which_lacks_return_type_annotation_implicitly_has_an_0_return_type, typeAsString);
51436                     return;
51437                 case 244 /* FunctionDeclaration */:
51438                 case 161 /* MethodDeclaration */:
51439                 case 160 /* MethodSignature */:
51440                 case 163 /* GetAccessor */:
51441                 case 164 /* SetAccessor */:
51442                 case 201 /* FunctionExpression */:
51443                 case 202 /* ArrowFunction */:
51444                     if (noImplicitAny && !declaration.name) {
51445                         if (wideningKind === 3 /* GeneratorYield */) {
51446                             error(declaration, ts.Diagnostics.Generator_implicitly_has_yield_type_0_because_it_does_not_yield_any_values_Consider_supplying_a_return_type_annotation, typeAsString);
51447                         }
51448                         else {
51449                             error(declaration, ts.Diagnostics.Function_expression_which_lacks_return_type_annotation_implicitly_has_an_0_return_type, typeAsString);
51450                         }
51451                         return;
51452                     }
51453                     diagnostic = !noImplicitAny ? ts.Diagnostics._0_implicitly_has_an_1_return_type_but_a_better_type_may_be_inferred_from_usage :
51454                         wideningKind === 3 /* GeneratorYield */ ? ts.Diagnostics._0_which_lacks_return_type_annotation_implicitly_has_an_1_yield_type :
51455                             ts.Diagnostics._0_which_lacks_return_type_annotation_implicitly_has_an_1_return_type;
51456                     break;
51457                 case 186 /* MappedType */:
51458                     if (noImplicitAny) {
51459                         error(declaration, ts.Diagnostics.Mapped_object_type_implicitly_has_an_any_template_type);
51460                     }
51461                     return;
51462                 default:
51463                     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;
51464             }
51465             errorOrSuggestion(noImplicitAny, declaration, diagnostic, ts.declarationNameToString(ts.getNameOfDeclaration(declaration)), typeAsString);
51466         }
51467         function reportErrorsFromWidening(declaration, type, wideningKind) {
51468             if (produceDiagnostics && noImplicitAny && ts.getObjectFlags(type) & 524288 /* ContainsWideningType */ && (!wideningKind || !getContextualSignatureForFunctionLikeDeclaration(declaration))) {
51469                 // Report implicit any error within type if possible, otherwise report error on declaration
51470                 if (!reportWideningErrorsInType(type)) {
51471                     reportImplicitAny(declaration, type, wideningKind);
51472                 }
51473             }
51474         }
51475         function applyToParameterTypes(source, target, callback) {
51476             var sourceCount = getParameterCount(source);
51477             var targetCount = getParameterCount(target);
51478             var sourceRestType = getEffectiveRestType(source);
51479             var targetRestType = getEffectiveRestType(target);
51480             var targetNonRestCount = targetRestType ? targetCount - 1 : targetCount;
51481             var paramCount = sourceRestType ? targetNonRestCount : Math.min(sourceCount, targetNonRestCount);
51482             var sourceThisType = getThisTypeOfSignature(source);
51483             if (sourceThisType) {
51484                 var targetThisType = getThisTypeOfSignature(target);
51485                 if (targetThisType) {
51486                     callback(sourceThisType, targetThisType);
51487                 }
51488             }
51489             for (var i = 0; i < paramCount; i++) {
51490                 callback(getTypeAtPosition(source, i), getTypeAtPosition(target, i));
51491             }
51492             if (targetRestType) {
51493                 callback(getRestTypeAtPosition(source, paramCount), targetRestType);
51494             }
51495         }
51496         function applyToReturnTypes(source, target, callback) {
51497             var sourceTypePredicate = getTypePredicateOfSignature(source);
51498             var targetTypePredicate = getTypePredicateOfSignature(target);
51499             if (sourceTypePredicate && targetTypePredicate && typePredicateKindsMatch(sourceTypePredicate, targetTypePredicate) && sourceTypePredicate.type && targetTypePredicate.type) {
51500                 callback(sourceTypePredicate.type, targetTypePredicate.type);
51501             }
51502             else {
51503                 callback(getReturnTypeOfSignature(source), getReturnTypeOfSignature(target));
51504             }
51505         }
51506         function createInferenceContext(typeParameters, signature, flags, compareTypes) {
51507             return createInferenceContextWorker(typeParameters.map(createInferenceInfo), signature, flags, compareTypes || compareTypesAssignable);
51508         }
51509         function cloneInferenceContext(context, extraFlags) {
51510             if (extraFlags === void 0) { extraFlags = 0; }
51511             return context && createInferenceContextWorker(ts.map(context.inferences, cloneInferenceInfo), context.signature, context.flags | extraFlags, context.compareTypes);
51512         }
51513         function createInferenceContextWorker(inferences, signature, flags, compareTypes) {
51514             var context = {
51515                 inferences: inferences,
51516                 signature: signature,
51517                 flags: flags,
51518                 compareTypes: compareTypes,
51519                 mapper: makeFunctionTypeMapper(function (t) { return mapToInferredType(context, t, /*fix*/ true); }),
51520                 nonFixingMapper: makeFunctionTypeMapper(function (t) { return mapToInferredType(context, t, /*fix*/ false); }),
51521             };
51522             return context;
51523         }
51524         function mapToInferredType(context, t, fix) {
51525             var inferences = context.inferences;
51526             for (var i = 0; i < inferences.length; i++) {
51527                 var inference = inferences[i];
51528                 if (t === inference.typeParameter) {
51529                     if (fix && !inference.isFixed) {
51530                         clearCachedInferences(inferences);
51531                         inference.isFixed = true;
51532                     }
51533                     return getInferredType(context, i);
51534                 }
51535             }
51536             return t;
51537         }
51538         function clearCachedInferences(inferences) {
51539             for (var _i = 0, inferences_1 = inferences; _i < inferences_1.length; _i++) {
51540                 var inference = inferences_1[_i];
51541                 if (!inference.isFixed) {
51542                     inference.inferredType = undefined;
51543                 }
51544             }
51545         }
51546         function createInferenceInfo(typeParameter) {
51547             return {
51548                 typeParameter: typeParameter,
51549                 candidates: undefined,
51550                 contraCandidates: undefined,
51551                 inferredType: undefined,
51552                 priority: undefined,
51553                 topLevel: true,
51554                 isFixed: false
51555             };
51556         }
51557         function cloneInferenceInfo(inference) {
51558             return {
51559                 typeParameter: inference.typeParameter,
51560                 candidates: inference.candidates && inference.candidates.slice(),
51561                 contraCandidates: inference.contraCandidates && inference.contraCandidates.slice(),
51562                 inferredType: inference.inferredType,
51563                 priority: inference.priority,
51564                 topLevel: inference.topLevel,
51565                 isFixed: inference.isFixed
51566             };
51567         }
51568         function cloneInferredPartOfContext(context) {
51569             var inferences = ts.filter(context.inferences, hasInferenceCandidates);
51570             return inferences.length ?
51571                 createInferenceContextWorker(ts.map(inferences, cloneInferenceInfo), context.signature, context.flags, context.compareTypes) :
51572                 undefined;
51573         }
51574         function getMapperFromContext(context) {
51575             return context && context.mapper;
51576         }
51577         // Return true if the given type could possibly reference a type parameter for which
51578         // we perform type inference (i.e. a type parameter of a generic function). We cache
51579         // results for union and intersection types for performance reasons.
51580         function couldContainTypeVariables(type) {
51581             var objectFlags = ts.getObjectFlags(type);
51582             if (objectFlags & 67108864 /* CouldContainTypeVariablesComputed */) {
51583                 return !!(objectFlags & 134217728 /* CouldContainTypeVariables */);
51584             }
51585             var result = !!(type.flags & 63176704 /* Instantiable */ ||
51586                 objectFlags & 4 /* Reference */ && (type.node || ts.forEach(getTypeArguments(type), couldContainTypeVariables)) ||
51587                 objectFlags & 16 /* Anonymous */ && type.symbol && type.symbol.flags & (16 /* Function */ | 8192 /* Method */ | 32 /* Class */ | 2048 /* TypeLiteral */ | 4096 /* ObjectLiteral */) && type.symbol.declarations ||
51588                 objectFlags & (32 /* Mapped */ | 131072 /* ObjectRestType */) ||
51589                 type.flags & 3145728 /* UnionOrIntersection */ && !(type.flags & 1024 /* EnumLiteral */) && ts.some(type.types, couldContainTypeVariables));
51590             if (type.flags & 3899393 /* ObjectFlagsType */) {
51591                 type.objectFlags |= 67108864 /* CouldContainTypeVariablesComputed */ | (result ? 134217728 /* CouldContainTypeVariables */ : 0);
51592             }
51593             return result;
51594         }
51595         function isTypeParameterAtTopLevel(type, typeParameter) {
51596             return !!(type === typeParameter ||
51597                 type.flags & 3145728 /* UnionOrIntersection */ && ts.some(type.types, function (t) { return isTypeParameterAtTopLevel(t, typeParameter); }) ||
51598                 type.flags & 16777216 /* Conditional */ && (isTypeParameterAtTopLevel(getTrueTypeFromConditionalType(type), typeParameter) ||
51599                     isTypeParameterAtTopLevel(getFalseTypeFromConditionalType(type), typeParameter)));
51600         }
51601         /** Create an object with properties named in the string literal type. Every property has type `any` */
51602         function createEmptyObjectTypeFromStringLiteral(type) {
51603             var members = ts.createSymbolTable();
51604             forEachType(type, function (t) {
51605                 if (!(t.flags & 128 /* StringLiteral */)) {
51606                     return;
51607                 }
51608                 var name = ts.escapeLeadingUnderscores(t.value);
51609                 var literalProp = createSymbol(4 /* Property */, name);
51610                 literalProp.type = anyType;
51611                 if (t.symbol) {
51612                     literalProp.declarations = t.symbol.declarations;
51613                     literalProp.valueDeclaration = t.symbol.valueDeclaration;
51614                 }
51615                 members.set(name, literalProp);
51616             });
51617             var indexInfo = type.flags & 4 /* String */ ? createIndexInfo(emptyObjectType, /*isReadonly*/ false) : undefined;
51618             return createAnonymousType(undefined, members, ts.emptyArray, ts.emptyArray, indexInfo, undefined);
51619         }
51620         /**
51621          * Infer a suitable input type for a homomorphic mapped type { [P in keyof T]: X }. We construct
51622          * an object type with the same set of properties as the source type, where the type of each
51623          * property is computed by inferring from the source property type to X for the type
51624          * variable T[P] (i.e. we treat the type T[P] as the type variable we're inferring for).
51625          */
51626         function inferTypeForHomomorphicMappedType(source, target, constraint) {
51627             var key = source.id + "," + target.id + "," + constraint.id;
51628             if (reverseMappedCache.has(key)) {
51629                 return reverseMappedCache.get(key);
51630             }
51631             reverseMappedCache.set(key, undefined);
51632             var type = createReverseMappedType(source, target, constraint);
51633             reverseMappedCache.set(key, type);
51634             return type;
51635         }
51636         // We consider a type to be partially inferable if it isn't marked non-inferable or if it is
51637         // an object literal type with at least one property of an inferable type. For example, an object
51638         // literal { a: 123, b: x => true } is marked non-inferable because it contains a context sensitive
51639         // arrow function, but is considered partially inferable because property 'a' has an inferable type.
51640         function isPartiallyInferableType(type) {
51641             return !(ts.getObjectFlags(type) & 2097152 /* NonInferrableType */) ||
51642                 isObjectLiteralType(type) && ts.some(getPropertiesOfType(type), function (prop) { return isPartiallyInferableType(getTypeOfSymbol(prop)); });
51643         }
51644         function createReverseMappedType(source, target, constraint) {
51645             // We consider a source type reverse mappable if it has a string index signature or if
51646             // it has one or more properties and is of a partially inferable type.
51647             if (!(getIndexInfoOfType(source, 0 /* String */) || getPropertiesOfType(source).length !== 0 && isPartiallyInferableType(source))) {
51648                 return undefined;
51649             }
51650             // For arrays and tuples we infer new arrays and tuples where the reverse mapping has been
51651             // applied to the element type(s).
51652             if (isArrayType(source)) {
51653                 return createArrayType(inferReverseMappedType(getTypeArguments(source)[0], target, constraint), isReadonlyArrayType(source));
51654             }
51655             if (isTupleType(source)) {
51656                 var elementTypes = ts.map(getTypeArguments(source), function (t) { return inferReverseMappedType(t, target, constraint); });
51657                 var minLength = getMappedTypeModifiers(target) & 4 /* IncludeOptional */ ?
51658                     getTypeReferenceArity(source) - (source.target.hasRestElement ? 1 : 0) : source.target.minLength;
51659                 return createTupleType(elementTypes, minLength, source.target.hasRestElement, source.target.readonly, source.target.associatedNames);
51660             }
51661             // For all other object types we infer a new object type where the reverse mapping has been
51662             // applied to the type of each property.
51663             var reversed = createObjectType(2048 /* ReverseMapped */ | 16 /* Anonymous */, /*symbol*/ undefined);
51664             reversed.source = source;
51665             reversed.mappedType = target;
51666             reversed.constraintType = constraint;
51667             return reversed;
51668         }
51669         function getTypeOfReverseMappedSymbol(symbol) {
51670             return inferReverseMappedType(symbol.propertyType, symbol.mappedType, symbol.constraintType);
51671         }
51672         function inferReverseMappedType(sourceType, target, constraint) {
51673             var typeParameter = getIndexedAccessType(constraint.type, getTypeParameterFromMappedType(target));
51674             var templateType = getTemplateTypeFromMappedType(target);
51675             var inference = createInferenceInfo(typeParameter);
51676             inferTypes([inference], sourceType, templateType);
51677             return getTypeFromInference(inference) || unknownType;
51678         }
51679         function getUnmatchedProperties(source, target, requireOptionalProperties, matchDiscriminantProperties) {
51680             var properties, _i, properties_2, targetProp, sourceProp, targetType, sourceType;
51681             return __generator(this, function (_a) {
51682                 switch (_a.label) {
51683                     case 0:
51684                         properties = getPropertiesOfType(target);
51685                         _i = 0, properties_2 = properties;
51686                         _a.label = 1;
51687                     case 1:
51688                         if (!(_i < properties_2.length)) return [3 /*break*/, 6];
51689                         targetProp = properties_2[_i];
51690                         // TODO: remove this when we support static private identifier fields and find other solutions to get privateNamesAndStaticFields test to pass
51691                         if (isStaticPrivateIdentifierProperty(targetProp)) {
51692                             return [3 /*break*/, 5];
51693                         }
51694                         if (!(requireOptionalProperties || !(targetProp.flags & 16777216 /* Optional */ || ts.getCheckFlags(targetProp) & 48 /* Partial */))) return [3 /*break*/, 5];
51695                         sourceProp = getPropertyOfType(source, targetProp.escapedName);
51696                         if (!!sourceProp) return [3 /*break*/, 3];
51697                         return [4 /*yield*/, targetProp];
51698                     case 2:
51699                         _a.sent();
51700                         return [3 /*break*/, 5];
51701                     case 3:
51702                         if (!matchDiscriminantProperties) return [3 /*break*/, 5];
51703                         targetType = getTypeOfSymbol(targetProp);
51704                         if (!(targetType.flags & 109440 /* Unit */)) return [3 /*break*/, 5];
51705                         sourceType = getTypeOfSymbol(sourceProp);
51706                         if (!!(sourceType.flags & 1 /* Any */ || getRegularTypeOfLiteralType(sourceType) === getRegularTypeOfLiteralType(targetType))) return [3 /*break*/, 5];
51707                         return [4 /*yield*/, targetProp];
51708                     case 4:
51709                         _a.sent();
51710                         _a.label = 5;
51711                     case 5:
51712                         _i++;
51713                         return [3 /*break*/, 1];
51714                     case 6: return [2 /*return*/];
51715                 }
51716             });
51717         }
51718         function getUnmatchedProperty(source, target, requireOptionalProperties, matchDiscriminantProperties) {
51719             var result = getUnmatchedProperties(source, target, requireOptionalProperties, matchDiscriminantProperties).next();
51720             if (!result.done)
51721                 return result.value;
51722         }
51723         function tupleTypesDefinitelyUnrelated(source, target) {
51724             return target.target.minLength > source.target.minLength ||
51725                 !getRestTypeOfTupleType(target) && (!!getRestTypeOfTupleType(source) || getLengthOfTupleType(target) < getLengthOfTupleType(source));
51726         }
51727         function typesDefinitelyUnrelated(source, target) {
51728             // Two tuple types with incompatible arities are definitely unrelated.
51729             // Two object types that each have a property that is unmatched in the other are definitely unrelated.
51730             return isTupleType(source) && isTupleType(target) && tupleTypesDefinitelyUnrelated(source, target) ||
51731                 !!getUnmatchedProperty(source, target, /*requireOptionalProperties*/ false, /*matchDiscriminantProperties*/ true) &&
51732                     !!getUnmatchedProperty(target, source, /*requireOptionalProperties*/ false, /*matchDiscriminantProperties*/ true);
51733         }
51734         function getTypeFromInference(inference) {
51735             return inference.candidates ? getUnionType(inference.candidates, 2 /* Subtype */) :
51736                 inference.contraCandidates ? getIntersectionType(inference.contraCandidates) :
51737                     undefined;
51738         }
51739         function hasSkipDirectInferenceFlag(node) {
51740             return !!getNodeLinks(node).skipDirectInference;
51741         }
51742         function isFromInferenceBlockedSource(type) {
51743             return !!(type.symbol && ts.some(type.symbol.declarations, hasSkipDirectInferenceFlag));
51744         }
51745         function inferTypes(inferences, originalSource, originalTarget, priority, contravariant) {
51746             if (priority === void 0) { priority = 0; }
51747             if (contravariant === void 0) { contravariant = false; }
51748             var symbolOrTypeStack;
51749             var visited;
51750             var bivariant = false;
51751             var propagationType;
51752             var inferencePriority = 512 /* MaxValue */;
51753             var allowComplexConstraintInference = true;
51754             inferFromTypes(originalSource, originalTarget);
51755             function inferFromTypes(source, target) {
51756                 if (!couldContainTypeVariables(target)) {
51757                     return;
51758                 }
51759                 if (source === wildcardType) {
51760                     // We are inferring from an 'any' type. We want to infer this type for every type parameter
51761                     // referenced in the target type, so we record it as the propagation type and infer from the
51762                     // target to itself. Then, as we find candidates we substitute the propagation type.
51763                     var savePropagationType = propagationType;
51764                     propagationType = source;
51765                     inferFromTypes(target, target);
51766                     propagationType = savePropagationType;
51767                     return;
51768                 }
51769                 if (source.aliasSymbol && source.aliasTypeArguments && source.aliasSymbol === target.aliasSymbol) {
51770                     // Source and target are types originating in the same generic type alias declaration.
51771                     // Simply infer from source type arguments to target type arguments.
51772                     inferFromTypeArguments(source.aliasTypeArguments, target.aliasTypeArguments, getAliasVariances(source.aliasSymbol));
51773                     return;
51774                 }
51775                 if (source === target && source.flags & 3145728 /* UnionOrIntersection */) {
51776                     // When source and target are the same union or intersection type, just relate each constituent
51777                     // type to itself.
51778                     for (var _i = 0, _a = source.types; _i < _a.length; _i++) {
51779                         var t = _a[_i];
51780                         inferFromTypes(t, t);
51781                     }
51782                     return;
51783                 }
51784                 if (target.flags & 1048576 /* Union */) {
51785                     // First, infer between identically matching source and target constituents and remove the
51786                     // matching types.
51787                     var _b = inferFromMatchingTypes(source.flags & 1048576 /* Union */ ? source.types : [source], target.types, isTypeOrBaseIdenticalTo), tempSources = _b[0], tempTargets = _b[1];
51788                     // Next, infer between closely matching source and target constituents and remove
51789                     // the matching types. Types closely match when they are instantiations of the same
51790                     // object type or instantiations of the same type alias.
51791                     var _c = inferFromMatchingTypes(tempSources, tempTargets, isTypeCloselyMatchedBy), sources = _c[0], targets = _c[1];
51792                     if (targets.length === 0) {
51793                         return;
51794                     }
51795                     target = getUnionType(targets);
51796                     if (sources.length === 0) {
51797                         // All source constituents have been matched and there is nothing further to infer from.
51798                         // However, simply making no inferences is undesirable because it could ultimately mean
51799                         // inferring a type parameter constraint. Instead, make a lower priority inference from
51800                         // the full source to whatever remains in the target. For example, when inferring from
51801                         // string to 'string | T', make a lower priority inference of string for T.
51802                         inferWithPriority(source, target, 1 /* NakedTypeVariable */);
51803                         return;
51804                     }
51805                     source = getUnionType(sources);
51806                 }
51807                 else if (target.flags & 2097152 /* Intersection */ && ts.some(target.types, function (t) { return !!getInferenceInfoForType(t) || (isGenericMappedType(t) && !!getInferenceInfoForType(getHomomorphicTypeVariable(t) || neverType)); })) {
51808                     // We reduce intersection types only when they contain naked type parameters. For example, when
51809                     // inferring from 'string[] & { extra: any }' to 'string[] & T' we want to remove string[] and
51810                     // infer { extra: any } for T. But when inferring to 'string[] & Iterable<T>' we want to keep the
51811                     // string[] on the source side and infer string for T.
51812                     // Likewise, we consider a homomorphic mapped type constrainted to the target type parameter as similar to a "naked type variable"
51813                     // in such scenarios.
51814                     if (!(source.flags & 1048576 /* Union */)) {
51815                         // Infer between identically matching source and target constituents and remove the matching types.
51816                         var _d = inferFromMatchingTypes(source.flags & 2097152 /* Intersection */ ? source.types : [source], target.types, isTypeIdenticalTo), sources = _d[0], targets = _d[1];
51817                         if (sources.length === 0 || targets.length === 0) {
51818                             return;
51819                         }
51820                         source = getIntersectionType(sources);
51821                         target = getIntersectionType(targets);
51822                     }
51823                 }
51824                 else if (target.flags & (8388608 /* IndexedAccess */ | 33554432 /* Substitution */)) {
51825                     target = getActualTypeVariable(target);
51826                 }
51827                 if (target.flags & 8650752 /* TypeVariable */) {
51828                     // If target is a type parameter, make an inference, unless the source type contains
51829                     // the anyFunctionType (the wildcard type that's used to avoid contextually typing functions).
51830                     // Because the anyFunctionType is internal, it should not be exposed to the user by adding
51831                     // it as an inference candidate. Hopefully, a better candidate will come along that does
51832                     // not contain anyFunctionType when we come back to this argument for its second round
51833                     // of inference. Also, we exclude inferences for silentNeverType (which is used as a wildcard
51834                     // when constructing types from type parameters that had no inference candidates).
51835                     if (ts.getObjectFlags(source) & 2097152 /* NonInferrableType */ || source === nonInferrableAnyType || source === silentNeverType ||
51836                         (priority & 32 /* ReturnType */ && (source === autoType || source === autoArrayType)) || isFromInferenceBlockedSource(source)) {
51837                         return;
51838                     }
51839                     var inference = getInferenceInfoForType(target);
51840                     if (inference) {
51841                         if (!inference.isFixed) {
51842                             if (inference.priority === undefined || priority < inference.priority) {
51843                                 inference.candidates = undefined;
51844                                 inference.contraCandidates = undefined;
51845                                 inference.topLevel = true;
51846                                 inference.priority = priority;
51847                             }
51848                             if (priority === inference.priority) {
51849                                 var candidate = propagationType || source;
51850                                 // We make contravariant inferences only if we are in a pure contravariant position,
51851                                 // i.e. only if we have not descended into a bivariant position.
51852                                 if (contravariant && !bivariant) {
51853                                     if (!ts.contains(inference.contraCandidates, candidate)) {
51854                                         inference.contraCandidates = ts.append(inference.contraCandidates, candidate);
51855                                         clearCachedInferences(inferences);
51856                                     }
51857                                 }
51858                                 else if (!ts.contains(inference.candidates, candidate)) {
51859                                     inference.candidates = ts.append(inference.candidates, candidate);
51860                                     clearCachedInferences(inferences);
51861                                 }
51862                             }
51863                             if (!(priority & 32 /* ReturnType */) && target.flags & 262144 /* TypeParameter */ && inference.topLevel && !isTypeParameterAtTopLevel(originalTarget, target)) {
51864                                 inference.topLevel = false;
51865                                 clearCachedInferences(inferences);
51866                             }
51867                         }
51868                         inferencePriority = Math.min(inferencePriority, priority);
51869                         return;
51870                     }
51871                     else {
51872                         // Infer to the simplified version of an indexed access, if possible, to (hopefully) expose more bare type parameters to the inference engine
51873                         var simplified = getSimplifiedType(target, /*writing*/ false);
51874                         if (simplified !== target) {
51875                             invokeOnce(source, simplified, inferFromTypes);
51876                         }
51877                         else if (target.flags & 8388608 /* IndexedAccess */) {
51878                             var indexType = getSimplifiedType(target.indexType, /*writing*/ false);
51879                             // Generally simplifications of instantiable indexes are avoided to keep relationship checking correct, however if our target is an access, we can consider
51880                             // that key of that access to be "instantiated", since we're looking to find the infernce goal in any way we can.
51881                             if (indexType.flags & 63176704 /* Instantiable */) {
51882                                 var simplified_1 = distributeIndexOverObjectType(getSimplifiedType(target.objectType, /*writing*/ false), indexType, /*writing*/ false);
51883                                 if (simplified_1 && simplified_1 !== target) {
51884                                     invokeOnce(source, simplified_1, inferFromTypes);
51885                                 }
51886                             }
51887                         }
51888                     }
51889                 }
51890                 if (ts.getObjectFlags(source) & 4 /* Reference */ && ts.getObjectFlags(target) & 4 /* Reference */ && (source.target === target.target || isArrayType(source) && isArrayType(target)) &&
51891                     !(source.node && target.node)) {
51892                     // If source and target are references to the same generic type, infer from type arguments
51893                     inferFromTypeArguments(getTypeArguments(source), getTypeArguments(target), getVariances(source.target));
51894                 }
51895                 else if (source.flags & 4194304 /* Index */ && target.flags & 4194304 /* Index */) {
51896                     contravariant = !contravariant;
51897                     inferFromTypes(source.type, target.type);
51898                     contravariant = !contravariant;
51899                 }
51900                 else if ((isLiteralType(source) || source.flags & 4 /* String */) && target.flags & 4194304 /* Index */) {
51901                     var empty = createEmptyObjectTypeFromStringLiteral(source);
51902                     contravariant = !contravariant;
51903                     inferWithPriority(empty, target.type, 64 /* LiteralKeyof */);
51904                     contravariant = !contravariant;
51905                 }
51906                 else if (source.flags & 8388608 /* IndexedAccess */ && target.flags & 8388608 /* IndexedAccess */) {
51907                     inferFromTypes(source.objectType, target.objectType);
51908                     inferFromTypes(source.indexType, target.indexType);
51909                 }
51910                 else if (source.flags & 16777216 /* Conditional */ && target.flags & 16777216 /* Conditional */) {
51911                     inferFromTypes(source.checkType, target.checkType);
51912                     inferFromTypes(source.extendsType, target.extendsType);
51913                     inferFromTypes(getTrueTypeFromConditionalType(source), getTrueTypeFromConditionalType(target));
51914                     inferFromTypes(getFalseTypeFromConditionalType(source), getFalseTypeFromConditionalType(target));
51915                 }
51916                 else if (target.flags & 16777216 /* Conditional */) {
51917                     var savePriority = priority;
51918                     priority |= contravariant ? 16 /* ContravariantConditional */ : 0;
51919                     var targetTypes = [getTrueTypeFromConditionalType(target), getFalseTypeFromConditionalType(target)];
51920                     inferToMultipleTypes(source, targetTypes, target.flags);
51921                     priority = savePriority;
51922                 }
51923                 else if (target.flags & 3145728 /* UnionOrIntersection */) {
51924                     inferToMultipleTypes(source, target.types, target.flags);
51925                 }
51926                 else if (source.flags & 1048576 /* Union */) {
51927                     // Source is a union or intersection type, infer from each constituent type
51928                     var sourceTypes = source.types;
51929                     for (var _e = 0, sourceTypes_2 = sourceTypes; _e < sourceTypes_2.length; _e++) {
51930                         var sourceType = sourceTypes_2[_e];
51931                         inferFromTypes(sourceType, target);
51932                     }
51933                 }
51934                 else {
51935                     source = getReducedType(source);
51936                     if (!(priority & 128 /* NoConstraints */ && source.flags & (2097152 /* Intersection */ | 63176704 /* Instantiable */))) {
51937                         var apparentSource = getApparentType(source);
51938                         // getApparentType can return _any_ type, since an indexed access or conditional may simplify to any other type.
51939                         // If that occurs and it doesn't simplify to an object or intersection, we'll need to restart `inferFromTypes`
51940                         // with the simplified source.
51941                         if (apparentSource !== source && allowComplexConstraintInference && !(apparentSource.flags & (524288 /* Object */ | 2097152 /* Intersection */))) {
51942                             // TODO: The `allowComplexConstraintInference` flag is a hack! This forbids inference from complex constraints within constraints!
51943                             // This isn't required algorithmically, but rather is used to lower the memory burden caused by performing inference
51944                             // that is _too good_ in projects with complicated constraints (eg, fp-ts). In such cases, if we did not limit ourselves
51945                             // here, we might produce more valid inferences for types, causing us to do more checks and perform more instantiations
51946                             // (in addition to the extra stack depth here) which, in turn, can push the already close process over its limit.
51947                             // TL;DR: If we ever become generally more memory efficient (or our resource budget ever increases), we should just
51948                             // remove this `allowComplexConstraintInference` flag.
51949                             allowComplexConstraintInference = false;
51950                             return inferFromTypes(apparentSource, target);
51951                         }
51952                         source = apparentSource;
51953                     }
51954                     if (source.flags & (524288 /* Object */ | 2097152 /* Intersection */)) {
51955                         invokeOnce(source, target, inferFromObjectTypes);
51956                     }
51957                 }
51958                 if (source.flags & 25165824 /* Simplifiable */) {
51959                     var simplified = getSimplifiedType(source, contravariant);
51960                     if (simplified !== source) {
51961                         inferFromTypes(simplified, target);
51962                     }
51963                 }
51964             }
51965             function inferWithPriority(source, target, newPriority) {
51966                 var savePriority = priority;
51967                 priority |= newPriority;
51968                 inferFromTypes(source, target);
51969                 priority = savePriority;
51970             }
51971             function invokeOnce(source, target, action) {
51972                 var key = source.id + "," + target.id;
51973                 var status = visited && visited.get(key);
51974                 if (status !== undefined) {
51975                     inferencePriority = Math.min(inferencePriority, status);
51976                     return;
51977                 }
51978                 (visited || (visited = ts.createMap())).set(key, -1 /* Circularity */);
51979                 var saveInferencePriority = inferencePriority;
51980                 inferencePriority = 512 /* MaxValue */;
51981                 action(source, target);
51982                 visited.set(key, inferencePriority);
51983                 inferencePriority = Math.min(inferencePriority, saveInferencePriority);
51984             }
51985             function inferFromMatchingTypes(sources, targets, matches) {
51986                 var matchedSources;
51987                 var matchedTargets;
51988                 for (var _i = 0, targets_1 = targets; _i < targets_1.length; _i++) {
51989                     var t = targets_1[_i];
51990                     for (var _a = 0, sources_1 = sources; _a < sources_1.length; _a++) {
51991                         var s = sources_1[_a];
51992                         if (matches(s, t)) {
51993                             inferFromTypes(s, t);
51994                             matchedSources = ts.appendIfUnique(matchedSources, s);
51995                             matchedTargets = ts.appendIfUnique(matchedTargets, t);
51996                         }
51997                     }
51998                 }
51999                 return [
52000                     matchedSources ? ts.filter(sources, function (t) { return !ts.contains(matchedSources, t); }) : sources,
52001                     matchedTargets ? ts.filter(targets, function (t) { return !ts.contains(matchedTargets, t); }) : targets,
52002                 ];
52003             }
52004             function inferFromTypeArguments(sourceTypes, targetTypes, variances) {
52005                 var count = sourceTypes.length < targetTypes.length ? sourceTypes.length : targetTypes.length;
52006                 for (var i = 0; i < count; i++) {
52007                     if (i < variances.length && (variances[i] & 7 /* VarianceMask */) === 2 /* Contravariant */) {
52008                         inferFromContravariantTypes(sourceTypes[i], targetTypes[i]);
52009                     }
52010                     else {
52011                         inferFromTypes(sourceTypes[i], targetTypes[i]);
52012                     }
52013                 }
52014             }
52015             function inferFromContravariantTypes(source, target) {
52016                 if (strictFunctionTypes || priority & 256 /* AlwaysStrict */) {
52017                     contravariant = !contravariant;
52018                     inferFromTypes(source, target);
52019                     contravariant = !contravariant;
52020                 }
52021                 else {
52022                     inferFromTypes(source, target);
52023                 }
52024             }
52025             function getInferenceInfoForType(type) {
52026                 if (type.flags & 8650752 /* TypeVariable */) {
52027                     for (var _i = 0, inferences_2 = inferences; _i < inferences_2.length; _i++) {
52028                         var inference = inferences_2[_i];
52029                         if (type === inference.typeParameter) {
52030                             return inference;
52031                         }
52032                     }
52033                 }
52034                 return undefined;
52035             }
52036             function getSingleTypeVariableFromIntersectionTypes(types) {
52037                 var typeVariable;
52038                 for (var _i = 0, types_14 = types; _i < types_14.length; _i++) {
52039                     var type = types_14[_i];
52040                     var t = type.flags & 2097152 /* Intersection */ && ts.find(type.types, function (t) { return !!getInferenceInfoForType(t); });
52041                     if (!t || typeVariable && t !== typeVariable) {
52042                         return undefined;
52043                     }
52044                     typeVariable = t;
52045                 }
52046                 return typeVariable;
52047             }
52048             function inferToMultipleTypes(source, targets, targetFlags) {
52049                 var typeVariableCount = 0;
52050                 if (targetFlags & 1048576 /* Union */) {
52051                     var nakedTypeVariable = void 0;
52052                     var sources = source.flags & 1048576 /* Union */ ? source.types : [source];
52053                     var matched_1 = new Array(sources.length);
52054                     var inferenceCircularity = false;
52055                     // First infer to types that are not naked type variables. For each source type we
52056                     // track whether inferences were made from that particular type to some target with
52057                     // equal priority (i.e. of equal quality) to what we would infer for a naked type
52058                     // parameter.
52059                     for (var _i = 0, targets_2 = targets; _i < targets_2.length; _i++) {
52060                         var t = targets_2[_i];
52061                         if (getInferenceInfoForType(t)) {
52062                             nakedTypeVariable = t;
52063                             typeVariableCount++;
52064                         }
52065                         else {
52066                             for (var i = 0; i < sources.length; i++) {
52067                                 var saveInferencePriority = inferencePriority;
52068                                 inferencePriority = 512 /* MaxValue */;
52069                                 inferFromTypes(sources[i], t);
52070                                 if (inferencePriority === priority)
52071                                     matched_1[i] = true;
52072                                 inferenceCircularity = inferenceCircularity || inferencePriority === -1 /* Circularity */;
52073                                 inferencePriority = Math.min(inferencePriority, saveInferencePriority);
52074                             }
52075                         }
52076                     }
52077                     if (typeVariableCount === 0) {
52078                         // If every target is an intersection of types containing a single naked type variable,
52079                         // make a lower priority inference to that type variable. This handles inferring from
52080                         // 'A | B' to 'T & (X | Y)' where we want to infer 'A | B' for T.
52081                         var intersectionTypeVariable = getSingleTypeVariableFromIntersectionTypes(targets);
52082                         if (intersectionTypeVariable) {
52083                             inferWithPriority(source, intersectionTypeVariable, 1 /* NakedTypeVariable */);
52084                         }
52085                         return;
52086                     }
52087                     // If the target has a single naked type variable and no inference circularities were
52088                     // encountered above (meaning we explored the types fully), create a union of the source
52089                     // types from which no inferences have been made so far and infer from that union to the
52090                     // naked type variable.
52091                     if (typeVariableCount === 1 && !inferenceCircularity) {
52092                         var unmatched = ts.flatMap(sources, function (s, i) { return matched_1[i] ? undefined : s; });
52093                         if (unmatched.length) {
52094                             inferFromTypes(getUnionType(unmatched), nakedTypeVariable);
52095                             return;
52096                         }
52097                     }
52098                 }
52099                 else {
52100                     // We infer from types that are not naked type variables first so that inferences we
52101                     // make from nested naked type variables and given slightly higher priority by virtue
52102                     // of being first in the candidates array.
52103                     for (var _a = 0, targets_3 = targets; _a < targets_3.length; _a++) {
52104                         var t = targets_3[_a];
52105                         if (getInferenceInfoForType(t)) {
52106                             typeVariableCount++;
52107                         }
52108                         else {
52109                             inferFromTypes(source, t);
52110                         }
52111                     }
52112                 }
52113                 // Inferences directly to naked type variables are given lower priority as they are
52114                 // less specific. For example, when inferring from Promise<string> to T | Promise<T>,
52115                 // we want to infer string for T, not Promise<string> | string. For intersection types
52116                 // we only infer to single naked type variables.
52117                 if (targetFlags & 2097152 /* Intersection */ ? typeVariableCount === 1 : typeVariableCount > 0) {
52118                     for (var _b = 0, targets_4 = targets; _b < targets_4.length; _b++) {
52119                         var t = targets_4[_b];
52120                         if (getInferenceInfoForType(t)) {
52121                             inferWithPriority(source, t, 1 /* NakedTypeVariable */);
52122                         }
52123                     }
52124                 }
52125             }
52126             function inferToMappedType(source, target, constraintType) {
52127                 if (constraintType.flags & 1048576 /* Union */) {
52128                     var result = false;
52129                     for (var _i = 0, _a = constraintType.types; _i < _a.length; _i++) {
52130                         var type = _a[_i];
52131                         result = inferToMappedType(source, target, type) || result;
52132                     }
52133                     return result;
52134                 }
52135                 if (constraintType.flags & 4194304 /* Index */) {
52136                     // We're inferring from some source type S to a homomorphic mapped type { [P in keyof T]: X },
52137                     // where T is a type variable. Use inferTypeForHomomorphicMappedType to infer a suitable source
52138                     // type and then make a secondary inference from that type to T. We make a secondary inference
52139                     // such that direct inferences to T get priority over inferences to Partial<T>, for example.
52140                     var inference = getInferenceInfoForType(constraintType.type);
52141                     if (inference && !inference.isFixed && !isFromInferenceBlockedSource(source)) {
52142                         var inferredType = inferTypeForHomomorphicMappedType(source, target, constraintType);
52143                         if (inferredType) {
52144                             // We assign a lower priority to inferences made from types containing non-inferrable
52145                             // types because we may only have a partial result (i.e. we may have failed to make
52146                             // reverse inferences for some properties).
52147                             inferWithPriority(inferredType, inference.typeParameter, ts.getObjectFlags(source) & 2097152 /* NonInferrableType */ ?
52148                                 4 /* PartialHomomorphicMappedType */ :
52149                                 2 /* HomomorphicMappedType */);
52150                         }
52151                     }
52152                     return true;
52153                 }
52154                 if (constraintType.flags & 262144 /* TypeParameter */) {
52155                     // We're inferring from some source type S to a mapped type { [P in K]: X }, where K is a type
52156                     // parameter. First infer from 'keyof S' to K.
52157                     inferWithPriority(getIndexType(source), constraintType, 8 /* MappedTypeConstraint */);
52158                     // If K is constrained to a type C, also infer to C. Thus, for a mapped type { [P in K]: X },
52159                     // where K extends keyof T, we make the same inferences as for a homomorphic mapped type
52160                     // { [P in keyof T]: X }. This enables us to make meaningful inferences when the target is a
52161                     // Pick<T, K>.
52162                     var extendedConstraint = getConstraintOfType(constraintType);
52163                     if (extendedConstraint && inferToMappedType(source, target, extendedConstraint)) {
52164                         return true;
52165                     }
52166                     // If no inferences can be made to K's constraint, infer from a union of the property types
52167                     // in the source to the template type X.
52168                     var propTypes = ts.map(getPropertiesOfType(source), getTypeOfSymbol);
52169                     var stringIndexType = getIndexTypeOfType(source, 0 /* String */);
52170                     var numberIndexInfo = getNonEnumNumberIndexInfo(source);
52171                     var numberIndexType = numberIndexInfo && numberIndexInfo.type;
52172                     inferFromTypes(getUnionType(ts.append(ts.append(propTypes, stringIndexType), numberIndexType)), getTemplateTypeFromMappedType(target));
52173                     return true;
52174                 }
52175                 return false;
52176             }
52177             function inferFromObjectTypes(source, target) {
52178                 // If we are already processing another target type with the same associated symbol (such as
52179                 // an instantiation of the same generic type), we do not explore this target as it would yield
52180                 // no further inferences. We exclude the static side of classes from this check since it shares
52181                 // its symbol with the instance side which would lead to false positives.
52182                 var isNonConstructorObject = target.flags & 524288 /* Object */ &&
52183                     !(ts.getObjectFlags(target) & 16 /* Anonymous */ && target.symbol && target.symbol.flags & 32 /* Class */);
52184                 var symbolOrType = isNonConstructorObject ? isTupleType(target) ? target.target : target.symbol : undefined;
52185                 if (symbolOrType) {
52186                     if (ts.contains(symbolOrTypeStack, symbolOrType)) {
52187                         inferencePriority = -1 /* Circularity */;
52188                         return;
52189                     }
52190                     (symbolOrTypeStack || (symbolOrTypeStack = [])).push(symbolOrType);
52191                     inferFromObjectTypesWorker(source, target);
52192                     symbolOrTypeStack.pop();
52193                 }
52194                 else {
52195                     inferFromObjectTypesWorker(source, target);
52196                 }
52197             }
52198             function inferFromObjectTypesWorker(source, target) {
52199                 if (ts.getObjectFlags(source) & 4 /* Reference */ && ts.getObjectFlags(target) & 4 /* Reference */ && (source.target === target.target || isArrayType(source) && isArrayType(target))) {
52200                     // If source and target are references to the same generic type, infer from type arguments
52201                     inferFromTypeArguments(getTypeArguments(source), getTypeArguments(target), getVariances(source.target));
52202                     return;
52203                 }
52204                 if (isGenericMappedType(source) && isGenericMappedType(target)) {
52205                     // The source and target types are generic types { [P in S]: X } and { [P in T]: Y }, so we infer
52206                     // from S to T and from X to Y.
52207                     inferFromTypes(getConstraintTypeFromMappedType(source), getConstraintTypeFromMappedType(target));
52208                     inferFromTypes(getTemplateTypeFromMappedType(source), getTemplateTypeFromMappedType(target));
52209                 }
52210                 if (ts.getObjectFlags(target) & 32 /* Mapped */) {
52211                     var constraintType = getConstraintTypeFromMappedType(target);
52212                     if (inferToMappedType(source, target, constraintType)) {
52213                         return;
52214                     }
52215                 }
52216                 // Infer from the members of source and target only if the two types are possibly related
52217                 if (!typesDefinitelyUnrelated(source, target)) {
52218                     if (isArrayType(source) || isTupleType(source)) {
52219                         if (isTupleType(target)) {
52220                             var sourceLength = isTupleType(source) ? getLengthOfTupleType(source) : 0;
52221                             var targetLength = getLengthOfTupleType(target);
52222                             var sourceRestType = isTupleType(source) ? getRestTypeOfTupleType(source) : getElementTypeOfArrayType(source);
52223                             var targetRestType = getRestTypeOfTupleType(target);
52224                             var fixedLength = targetLength < sourceLength || sourceRestType ? targetLength : sourceLength;
52225                             for (var i = 0; i < fixedLength; i++) {
52226                                 inferFromTypes(i < sourceLength ? getTypeArguments(source)[i] : sourceRestType, getTypeArguments(target)[i]);
52227                             }
52228                             if (targetRestType) {
52229                                 var types = fixedLength < sourceLength ? getTypeArguments(source).slice(fixedLength, sourceLength) : [];
52230                                 if (sourceRestType) {
52231                                     types.push(sourceRestType);
52232                                 }
52233                                 if (types.length) {
52234                                     inferFromTypes(getUnionType(types), targetRestType);
52235                                 }
52236                             }
52237                             return;
52238                         }
52239                         if (isArrayType(target)) {
52240                             inferFromIndexTypes(source, target);
52241                             return;
52242                         }
52243                     }
52244                     inferFromProperties(source, target);
52245                     inferFromSignatures(source, target, 0 /* Call */);
52246                     inferFromSignatures(source, target, 1 /* Construct */);
52247                     inferFromIndexTypes(source, target);
52248                 }
52249             }
52250             function inferFromProperties(source, target) {
52251                 var properties = getPropertiesOfObjectType(target);
52252                 for (var _i = 0, properties_3 = properties; _i < properties_3.length; _i++) {
52253                     var targetProp = properties_3[_i];
52254                     var sourceProp = getPropertyOfType(source, targetProp.escapedName);
52255                     if (sourceProp) {
52256                         inferFromTypes(getTypeOfSymbol(sourceProp), getTypeOfSymbol(targetProp));
52257                     }
52258                 }
52259             }
52260             function inferFromSignatures(source, target, kind) {
52261                 var sourceSignatures = getSignaturesOfType(source, kind);
52262                 var targetSignatures = getSignaturesOfType(target, kind);
52263                 var sourceLen = sourceSignatures.length;
52264                 var targetLen = targetSignatures.length;
52265                 var len = sourceLen < targetLen ? sourceLen : targetLen;
52266                 var skipParameters = !!(ts.getObjectFlags(source) & 2097152 /* NonInferrableType */);
52267                 for (var i = 0; i < len; i++) {
52268                     inferFromSignature(getBaseSignature(sourceSignatures[sourceLen - len + i]), getErasedSignature(targetSignatures[targetLen - len + i]), skipParameters);
52269                 }
52270             }
52271             function inferFromSignature(source, target, skipParameters) {
52272                 if (!skipParameters) {
52273                     var saveBivariant = bivariant;
52274                     var kind = target.declaration ? target.declaration.kind : 0 /* Unknown */;
52275                     // Once we descend into a bivariant signature we remain bivariant for all nested inferences
52276                     bivariant = bivariant || kind === 161 /* MethodDeclaration */ || kind === 160 /* MethodSignature */ || kind === 162 /* Constructor */;
52277                     applyToParameterTypes(source, target, inferFromContravariantTypes);
52278                     bivariant = saveBivariant;
52279                 }
52280                 applyToReturnTypes(source, target, inferFromTypes);
52281             }
52282             function inferFromIndexTypes(source, target) {
52283                 var targetStringIndexType = getIndexTypeOfType(target, 0 /* String */);
52284                 if (targetStringIndexType) {
52285                     var sourceIndexType = getIndexTypeOfType(source, 0 /* String */) ||
52286                         getImplicitIndexTypeOfType(source, 0 /* String */);
52287                     if (sourceIndexType) {
52288                         inferFromTypes(sourceIndexType, targetStringIndexType);
52289                     }
52290                 }
52291                 var targetNumberIndexType = getIndexTypeOfType(target, 1 /* Number */);
52292                 if (targetNumberIndexType) {
52293                     var sourceIndexType = getIndexTypeOfType(source, 1 /* Number */) ||
52294                         getIndexTypeOfType(source, 0 /* String */) ||
52295                         getImplicitIndexTypeOfType(source, 1 /* Number */);
52296                     if (sourceIndexType) {
52297                         inferFromTypes(sourceIndexType, targetNumberIndexType);
52298                     }
52299                 }
52300             }
52301         }
52302         function isTypeOrBaseIdenticalTo(s, t) {
52303             return isTypeIdenticalTo(s, t) || !!(t.flags & 4 /* String */ && s.flags & 128 /* StringLiteral */ || t.flags & 8 /* Number */ && s.flags & 256 /* NumberLiteral */);
52304         }
52305         function isTypeCloselyMatchedBy(s, t) {
52306             return !!(s.flags & 524288 /* Object */ && t.flags & 524288 /* Object */ && s.symbol && s.symbol === t.symbol ||
52307                 s.aliasSymbol && s.aliasTypeArguments && s.aliasSymbol === t.aliasSymbol);
52308         }
52309         function hasPrimitiveConstraint(type) {
52310             var constraint = getConstraintOfTypeParameter(type);
52311             return !!constraint && maybeTypeOfKind(constraint.flags & 16777216 /* Conditional */ ? getDefaultConstraintOfConditionalType(constraint) : constraint, 131068 /* Primitive */ | 4194304 /* Index */);
52312         }
52313         function isObjectLiteralType(type) {
52314             return !!(ts.getObjectFlags(type) & 128 /* ObjectLiteral */);
52315         }
52316         function isObjectOrArrayLiteralType(type) {
52317             return !!(ts.getObjectFlags(type) & (128 /* ObjectLiteral */ | 65536 /* ArrayLiteral */));
52318         }
52319         function unionObjectAndArrayLiteralCandidates(candidates) {
52320             if (candidates.length > 1) {
52321                 var objectLiterals = ts.filter(candidates, isObjectOrArrayLiteralType);
52322                 if (objectLiterals.length) {
52323                     var literalsType = getUnionType(objectLiterals, 2 /* Subtype */);
52324                     return ts.concatenate(ts.filter(candidates, function (t) { return !isObjectOrArrayLiteralType(t); }), [literalsType]);
52325                 }
52326             }
52327             return candidates;
52328         }
52329         function getContravariantInference(inference) {
52330             return inference.priority & 104 /* PriorityImpliesCombination */ ? getIntersectionType(inference.contraCandidates) : getCommonSubtype(inference.contraCandidates);
52331         }
52332         function getCovariantInference(inference, signature) {
52333             // Extract all object and array literal types and replace them with a single widened and normalized type.
52334             var candidates = unionObjectAndArrayLiteralCandidates(inference.candidates);
52335             // We widen inferred literal types if
52336             // all inferences were made to top-level occurrences of the type parameter, and
52337             // the type parameter has no constraint or its constraint includes no primitive or literal types, and
52338             // the type parameter was fixed during inference or does not occur at top-level in the return type.
52339             var primitiveConstraint = hasPrimitiveConstraint(inference.typeParameter);
52340             var widenLiteralTypes = !primitiveConstraint && inference.topLevel &&
52341                 (inference.isFixed || !isTypeParameterAtTopLevel(getReturnTypeOfSignature(signature), inference.typeParameter));
52342             var baseCandidates = primitiveConstraint ? ts.sameMap(candidates, getRegularTypeOfLiteralType) :
52343                 widenLiteralTypes ? ts.sameMap(candidates, getWidenedLiteralType) :
52344                     candidates;
52345             // If all inferences were made from a position that implies a combined result, infer a union type.
52346             // Otherwise, infer a common supertype.
52347             var unwidenedType = inference.priority & 104 /* PriorityImpliesCombination */ ?
52348                 getUnionType(baseCandidates, 2 /* Subtype */) :
52349                 getCommonSupertype(baseCandidates);
52350             return getWidenedType(unwidenedType);
52351         }
52352         function getInferredType(context, index) {
52353             var inference = context.inferences[index];
52354             if (!inference.inferredType) {
52355                 var inferredType = void 0;
52356                 var signature = context.signature;
52357                 if (signature) {
52358                     var inferredCovariantType = inference.candidates ? getCovariantInference(inference, signature) : undefined;
52359                     if (inference.contraCandidates) {
52360                         var inferredContravariantType = getContravariantInference(inference);
52361                         // If we have both co- and contra-variant inferences, we prefer the contra-variant inference
52362                         // unless the co-variant inference is a subtype and not 'never'.
52363                         inferredType = inferredCovariantType && !(inferredCovariantType.flags & 131072 /* Never */) &&
52364                             isTypeSubtypeOf(inferredCovariantType, inferredContravariantType) ?
52365                             inferredCovariantType : inferredContravariantType;
52366                     }
52367                     else if (inferredCovariantType) {
52368                         inferredType = inferredCovariantType;
52369                     }
52370                     else if (context.flags & 1 /* NoDefault */) {
52371                         // We use silentNeverType as the wildcard that signals no inferences.
52372                         inferredType = silentNeverType;
52373                     }
52374                     else {
52375                         // Infer either the default or the empty object type when no inferences were
52376                         // made. It is important to remember that in this case, inference still
52377                         // succeeds, meaning there is no error for not having inference candidates. An
52378                         // inference error only occurs when there are *conflicting* candidates, i.e.
52379                         // candidates with no common supertype.
52380                         var defaultType = getDefaultFromTypeParameter(inference.typeParameter);
52381                         if (defaultType) {
52382                             // Instantiate the default type. Any forward reference to a type
52383                             // parameter should be instantiated to the empty object type.
52384                             inferredType = instantiateType(defaultType, mergeTypeMappers(createBackreferenceMapper(context, index), context.nonFixingMapper));
52385                         }
52386                     }
52387                 }
52388                 else {
52389                     inferredType = getTypeFromInference(inference);
52390                 }
52391                 inference.inferredType = inferredType || getDefaultTypeArgumentType(!!(context.flags & 2 /* AnyDefault */));
52392                 var constraint = getConstraintOfTypeParameter(inference.typeParameter);
52393                 if (constraint) {
52394                     var instantiatedConstraint = instantiateType(constraint, context.nonFixingMapper);
52395                     if (!inferredType || !context.compareTypes(inferredType, getTypeWithThisArgument(instantiatedConstraint, inferredType))) {
52396                         inference.inferredType = inferredType = instantiatedConstraint;
52397                     }
52398                 }
52399             }
52400             return inference.inferredType;
52401         }
52402         function getDefaultTypeArgumentType(isInJavaScriptFile) {
52403             return isInJavaScriptFile ? anyType : unknownType;
52404         }
52405         function getInferredTypes(context) {
52406             var result = [];
52407             for (var i = 0; i < context.inferences.length; i++) {
52408                 result.push(getInferredType(context, i));
52409             }
52410             return result;
52411         }
52412         // EXPRESSION TYPE CHECKING
52413         function getCannotFindNameDiagnosticForName(node) {
52414             switch (node.escapedText) {
52415                 case "document":
52416                 case "console":
52417                     return ts.Diagnostics.Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_include_dom;
52418                 case "$":
52419                     return compilerOptions.types
52420                         ? 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
52421                         : ts.Diagnostics.Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_jQuery_Try_npm_i_types_Slashjquery;
52422                 case "describe":
52423                 case "suite":
52424                 case "it":
52425                 case "test":
52426                     return compilerOptions.types
52427                         ? 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
52428                         : 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;
52429                 case "process":
52430                 case "require":
52431                 case "Buffer":
52432                 case "module":
52433                     return compilerOptions.types
52434                         ? 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
52435                         : ts.Diagnostics.Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_types_Slashnode;
52436                 case "Map":
52437                 case "Set":
52438                 case "Promise":
52439                 case "Symbol":
52440                 case "WeakMap":
52441                 case "WeakSet":
52442                 case "Iterator":
52443                 case "AsyncIterator":
52444                     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;
52445                 default:
52446                     if (node.parent.kind === 282 /* ShorthandPropertyAssignment */) {
52447                         return ts.Diagnostics.No_value_exists_in_scope_for_the_shorthand_property_0_Either_declare_one_or_provide_an_initializer;
52448                     }
52449                     else {
52450                         return ts.Diagnostics.Cannot_find_name_0;
52451                     }
52452             }
52453         }
52454         function getResolvedSymbol(node) {
52455             var links = getNodeLinks(node);
52456             if (!links.resolvedSymbol) {
52457                 links.resolvedSymbol = !ts.nodeIsMissing(node) &&
52458                     resolveName(node, node.escapedText, 111551 /* Value */ | 1048576 /* ExportValue */, getCannotFindNameDiagnosticForName(node), node, !ts.isWriteOnlyAccess(node), 
52459                     /*excludeGlobals*/ false, ts.Diagnostics.Cannot_find_name_0_Did_you_mean_1) || unknownSymbol;
52460             }
52461             return links.resolvedSymbol;
52462         }
52463         function isInTypeQuery(node) {
52464             // TypeScript 1.0 spec (April 2014): 3.6.3
52465             // A type query consists of the keyword typeof followed by an expression.
52466             // The expression is restricted to a single identifier or a sequence of identifiers separated by periods
52467             return !!ts.findAncestor(node, function (n) { return n.kind === 172 /* TypeQuery */ ? true : n.kind === 75 /* Identifier */ || n.kind === 153 /* QualifiedName */ ? false : "quit"; });
52468         }
52469         // Return the flow cache key for a "dotted name" (i.e. a sequence of identifiers
52470         // separated by dots). The key consists of the id of the symbol referenced by the
52471         // leftmost identifier followed by zero or more property names separated by dots.
52472         // The result is undefined if the reference isn't a dotted name. We prefix nodes
52473         // occurring in an apparent type position with '@' because the control flow type
52474         // of such nodes may be based on the apparent type instead of the declared type.
52475         function getFlowCacheKey(node, declaredType, initialType, flowContainer) {
52476             switch (node.kind) {
52477                 case 75 /* Identifier */:
52478                     var symbol = getResolvedSymbol(node);
52479                     return symbol !== unknownSymbol ? (flowContainer ? getNodeId(flowContainer) : "-1") + "|" + getTypeId(declaredType) + "|" + getTypeId(initialType) + "|" + (isConstraintPosition(node) ? "@" : "") + getSymbolId(symbol) : undefined;
52480                 case 104 /* ThisKeyword */:
52481                     return "0";
52482                 case 218 /* NonNullExpression */:
52483                 case 200 /* ParenthesizedExpression */:
52484                     return getFlowCacheKey(node.expression, declaredType, initialType, flowContainer);
52485                 case 194 /* PropertyAccessExpression */:
52486                 case 195 /* ElementAccessExpression */:
52487                     var propName = getAccessedPropertyName(node);
52488                     if (propName !== undefined) {
52489                         var key = getFlowCacheKey(node.expression, declaredType, initialType, flowContainer);
52490                         return key && key + "." + propName;
52491                     }
52492             }
52493             return undefined;
52494         }
52495         function isMatchingReference(source, target) {
52496             switch (target.kind) {
52497                 case 200 /* ParenthesizedExpression */:
52498                 case 218 /* NonNullExpression */:
52499                     return isMatchingReference(source, target.expression);
52500             }
52501             switch (source.kind) {
52502                 case 75 /* Identifier */:
52503                     return target.kind === 75 /* Identifier */ && getResolvedSymbol(source) === getResolvedSymbol(target) ||
52504                         (target.kind === 242 /* VariableDeclaration */ || target.kind === 191 /* BindingElement */) &&
52505                             getExportSymbolOfValueSymbolIfExported(getResolvedSymbol(source)) === getSymbolOfNode(target);
52506                 case 104 /* ThisKeyword */:
52507                     return target.kind === 104 /* ThisKeyword */;
52508                 case 102 /* SuperKeyword */:
52509                     return target.kind === 102 /* SuperKeyword */;
52510                 case 218 /* NonNullExpression */:
52511                 case 200 /* ParenthesizedExpression */:
52512                     return isMatchingReference(source.expression, target);
52513                 case 194 /* PropertyAccessExpression */:
52514                 case 195 /* ElementAccessExpression */:
52515                     return ts.isAccessExpression(target) &&
52516                         getAccessedPropertyName(source) === getAccessedPropertyName(target) &&
52517                         isMatchingReference(source.expression, target.expression);
52518             }
52519             return false;
52520         }
52521         // Given a source x, check if target matches x or is an && operation with an operand that matches x.
52522         function containsTruthyCheck(source, target) {
52523             return isMatchingReference(source, target) ||
52524                 (target.kind === 209 /* BinaryExpression */ && target.operatorToken.kind === 55 /* AmpersandAmpersandToken */ &&
52525                     (containsTruthyCheck(source, target.left) || containsTruthyCheck(source, target.right)));
52526         }
52527         function getAccessedPropertyName(access) {
52528             return access.kind === 194 /* PropertyAccessExpression */ ? access.name.escapedText :
52529                 ts.isStringOrNumericLiteralLike(access.argumentExpression) ? ts.escapeLeadingUnderscores(access.argumentExpression.text) :
52530                     undefined;
52531         }
52532         function containsMatchingReference(source, target) {
52533             while (ts.isAccessExpression(source)) {
52534                 source = source.expression;
52535                 if (isMatchingReference(source, target)) {
52536                     return true;
52537                 }
52538             }
52539             return false;
52540         }
52541         function optionalChainContainsReference(source, target) {
52542             while (ts.isOptionalChain(source)) {
52543                 source = source.expression;
52544                 if (isMatchingReference(source, target)) {
52545                     return true;
52546                 }
52547             }
52548             return false;
52549         }
52550         function isDiscriminantProperty(type, name) {
52551             if (type && type.flags & 1048576 /* Union */) {
52552                 var prop = getUnionOrIntersectionProperty(type, name);
52553                 if (prop && ts.getCheckFlags(prop) & 2 /* SyntheticProperty */) {
52554                     if (prop.isDiscriminantProperty === undefined) {
52555                         prop.isDiscriminantProperty =
52556                             (prop.checkFlags & 192 /* Discriminant */) === 192 /* Discriminant */ &&
52557                                 !maybeTypeOfKind(getTypeOfSymbol(prop), 63176704 /* Instantiable */);
52558                     }
52559                     return !!prop.isDiscriminantProperty;
52560                 }
52561             }
52562             return false;
52563         }
52564         function findDiscriminantProperties(sourceProperties, target) {
52565             var result;
52566             for (var _i = 0, sourceProperties_2 = sourceProperties; _i < sourceProperties_2.length; _i++) {
52567                 var sourceProperty = sourceProperties_2[_i];
52568                 if (isDiscriminantProperty(target, sourceProperty.escapedName)) {
52569                     if (result) {
52570                         result.push(sourceProperty);
52571                         continue;
52572                     }
52573                     result = [sourceProperty];
52574                 }
52575             }
52576             return result;
52577         }
52578         function isOrContainsMatchingReference(source, target) {
52579             return isMatchingReference(source, target) || containsMatchingReference(source, target);
52580         }
52581         function hasMatchingArgument(callExpression, reference) {
52582             if (callExpression.arguments) {
52583                 for (var _i = 0, _a = callExpression.arguments; _i < _a.length; _i++) {
52584                     var argument = _a[_i];
52585                     if (isOrContainsMatchingReference(reference, argument)) {
52586                         return true;
52587                     }
52588                 }
52589             }
52590             if (callExpression.expression.kind === 194 /* PropertyAccessExpression */ &&
52591                 isOrContainsMatchingReference(reference, callExpression.expression.expression)) {
52592                 return true;
52593             }
52594             return false;
52595         }
52596         function getFlowNodeId(flow) {
52597             if (!flow.id || flow.id < 0) {
52598                 flow.id = nextFlowId;
52599                 nextFlowId++;
52600             }
52601             return flow.id;
52602         }
52603         function typeMaybeAssignableTo(source, target) {
52604             if (!(source.flags & 1048576 /* Union */)) {
52605                 return isTypeAssignableTo(source, target);
52606             }
52607             for (var _i = 0, _a = source.types; _i < _a.length; _i++) {
52608                 var t = _a[_i];
52609                 if (isTypeAssignableTo(t, target)) {
52610                     return true;
52611                 }
52612             }
52613             return false;
52614         }
52615         // Remove those constituent types of declaredType to which no constituent type of assignedType is assignable.
52616         // For example, when a variable of type number | string | boolean is assigned a value of type number | boolean,
52617         // we remove type string.
52618         function getAssignmentReducedType(declaredType, assignedType) {
52619             if (declaredType !== assignedType) {
52620                 if (assignedType.flags & 131072 /* Never */) {
52621                     return assignedType;
52622                 }
52623                 var reducedType = filterType(declaredType, function (t) { return typeMaybeAssignableTo(assignedType, t); });
52624                 if (assignedType.flags & 512 /* BooleanLiteral */ && isFreshLiteralType(assignedType)) {
52625                     reducedType = mapType(reducedType, getFreshTypeOfLiteralType); // Ensure that if the assignment is a fresh type, that we narrow to fresh types
52626                 }
52627                 // Our crude heuristic produces an invalid result in some cases: see GH#26130.
52628                 // For now, when that happens, we give up and don't narrow at all.  (This also
52629                 // means we'll never narrow for erroneous assignments where the assigned type
52630                 // is not assignable to the declared type.)
52631                 if (isTypeAssignableTo(assignedType, reducedType)) {
52632                     return reducedType;
52633                 }
52634             }
52635             return declaredType;
52636         }
52637         function getTypeFactsOfTypes(types) {
52638             var result = 0 /* None */;
52639             for (var _i = 0, types_15 = types; _i < types_15.length; _i++) {
52640                 var t = types_15[_i];
52641                 result |= getTypeFacts(t);
52642             }
52643             return result;
52644         }
52645         function isFunctionObjectType(type) {
52646             // We do a quick check for a "bind" property before performing the more expensive subtype
52647             // check. This gives us a quicker out in the common case where an object type is not a function.
52648             var resolved = resolveStructuredTypeMembers(type);
52649             return !!(resolved.callSignatures.length || resolved.constructSignatures.length ||
52650                 resolved.members.get("bind") && isTypeSubtypeOf(type, globalFunctionType));
52651         }
52652         function getTypeFacts(type) {
52653             var flags = type.flags;
52654             if (flags & 4 /* String */) {
52655                 return strictNullChecks ? 16317953 /* StringStrictFacts */ : 16776705 /* StringFacts */;
52656             }
52657             if (flags & 128 /* StringLiteral */) {
52658                 var isEmpty = type.value === "";
52659                 return strictNullChecks ?
52660                     isEmpty ? 12123649 /* EmptyStringStrictFacts */ : 7929345 /* NonEmptyStringStrictFacts */ :
52661                     isEmpty ? 12582401 /* EmptyStringFacts */ : 16776705 /* NonEmptyStringFacts */;
52662             }
52663             if (flags & (8 /* Number */ | 32 /* Enum */)) {
52664                 return strictNullChecks ? 16317698 /* NumberStrictFacts */ : 16776450 /* NumberFacts */;
52665             }
52666             if (flags & 256 /* NumberLiteral */) {
52667                 var isZero = type.value === 0;
52668                 return strictNullChecks ?
52669                     isZero ? 12123394 /* ZeroNumberStrictFacts */ : 7929090 /* NonZeroNumberStrictFacts */ :
52670                     isZero ? 12582146 /* ZeroNumberFacts */ : 16776450 /* NonZeroNumberFacts */;
52671             }
52672             if (flags & 64 /* BigInt */) {
52673                 return strictNullChecks ? 16317188 /* BigIntStrictFacts */ : 16775940 /* BigIntFacts */;
52674             }
52675             if (flags & 2048 /* BigIntLiteral */) {
52676                 var isZero = isZeroBigInt(type);
52677                 return strictNullChecks ?
52678                     isZero ? 12122884 /* ZeroBigIntStrictFacts */ : 7928580 /* NonZeroBigIntStrictFacts */ :
52679                     isZero ? 12581636 /* ZeroBigIntFacts */ : 16775940 /* NonZeroBigIntFacts */;
52680             }
52681             if (flags & 16 /* Boolean */) {
52682                 return strictNullChecks ? 16316168 /* BooleanStrictFacts */ : 16774920 /* BooleanFacts */;
52683             }
52684             if (flags & 528 /* BooleanLike */) {
52685                 return strictNullChecks ?
52686                     (type === falseType || type === regularFalseType) ? 12121864 /* FalseStrictFacts */ : 7927560 /* TrueStrictFacts */ :
52687                     (type === falseType || type === regularFalseType) ? 12580616 /* FalseFacts */ : 16774920 /* TrueFacts */;
52688             }
52689             if (flags & 524288 /* Object */) {
52690                 return ts.getObjectFlags(type) & 16 /* Anonymous */ && isEmptyObjectType(type) ?
52691                     strictNullChecks ? 16318463 /* EmptyObjectStrictFacts */ : 16777215 /* EmptyObjectFacts */ :
52692                     isFunctionObjectType(type) ?
52693                         strictNullChecks ? 7880640 /* FunctionStrictFacts */ : 16728000 /* FunctionFacts */ :
52694                         strictNullChecks ? 7888800 /* ObjectStrictFacts */ : 16736160 /* ObjectFacts */;
52695             }
52696             if (flags & (16384 /* Void */ | 32768 /* Undefined */)) {
52697                 return 9830144 /* UndefinedFacts */;
52698             }
52699             if (flags & 65536 /* Null */) {
52700                 return 9363232 /* NullFacts */;
52701             }
52702             if (flags & 12288 /* ESSymbolLike */) {
52703                 return strictNullChecks ? 7925520 /* SymbolStrictFacts */ : 16772880 /* SymbolFacts */;
52704             }
52705             if (flags & 67108864 /* NonPrimitive */) {
52706                 return strictNullChecks ? 7888800 /* ObjectStrictFacts */ : 16736160 /* ObjectFacts */;
52707             }
52708             if (flags & 131072 /* Never */) {
52709                 return 0 /* None */;
52710             }
52711             if (flags & 63176704 /* Instantiable */) {
52712                 return getTypeFacts(getBaseConstraintOfType(type) || unknownType);
52713             }
52714             if (flags & 3145728 /* UnionOrIntersection */) {
52715                 return getTypeFactsOfTypes(type.types);
52716             }
52717             return 16777215 /* All */;
52718         }
52719         function getTypeWithFacts(type, include) {
52720             return filterType(type, function (t) { return (getTypeFacts(t) & include) !== 0; });
52721         }
52722         function getTypeWithDefault(type, defaultExpression) {
52723             if (defaultExpression) {
52724                 var defaultType = getTypeOfExpression(defaultExpression);
52725                 return getUnionType([getTypeWithFacts(type, 524288 /* NEUndefined */), defaultType]);
52726             }
52727             return type;
52728         }
52729         function getTypeOfDestructuredProperty(type, name) {
52730             var nameType = getLiteralTypeFromPropertyName(name);
52731             if (!isTypeUsableAsPropertyName(nameType))
52732                 return errorType;
52733             var text = getPropertyNameFromType(nameType);
52734             return getConstraintForLocation(getTypeOfPropertyOfType(type, text), name) ||
52735                 isNumericLiteralName(text) && getIndexTypeOfType(type, 1 /* Number */) ||
52736                 getIndexTypeOfType(type, 0 /* String */) ||
52737                 errorType;
52738         }
52739         function getTypeOfDestructuredArrayElement(type, index) {
52740             return everyType(type, isTupleLikeType) && getTupleElementType(type, index) ||
52741                 checkIteratedTypeOrElementType(65 /* Destructuring */, type, undefinedType, /*errorNode*/ undefined) ||
52742                 errorType;
52743         }
52744         function getTypeOfDestructuredSpreadExpression(type) {
52745             return createArrayType(checkIteratedTypeOrElementType(65 /* Destructuring */, type, undefinedType, /*errorNode*/ undefined) || errorType);
52746         }
52747         function getAssignedTypeOfBinaryExpression(node) {
52748             var isDestructuringDefaultAssignment = node.parent.kind === 192 /* ArrayLiteralExpression */ && isDestructuringAssignmentTarget(node.parent) ||
52749                 node.parent.kind === 281 /* PropertyAssignment */ && isDestructuringAssignmentTarget(node.parent.parent);
52750             return isDestructuringDefaultAssignment ?
52751                 getTypeWithDefault(getAssignedType(node), node.right) :
52752                 getTypeOfExpression(node.right);
52753         }
52754         function isDestructuringAssignmentTarget(parent) {
52755             return parent.parent.kind === 209 /* BinaryExpression */ && parent.parent.left === parent ||
52756                 parent.parent.kind === 232 /* ForOfStatement */ && parent.parent.initializer === parent;
52757         }
52758         function getAssignedTypeOfArrayLiteralElement(node, element) {
52759             return getTypeOfDestructuredArrayElement(getAssignedType(node), node.elements.indexOf(element));
52760         }
52761         function getAssignedTypeOfSpreadExpression(node) {
52762             return getTypeOfDestructuredSpreadExpression(getAssignedType(node.parent));
52763         }
52764         function getAssignedTypeOfPropertyAssignment(node) {
52765             return getTypeOfDestructuredProperty(getAssignedType(node.parent), node.name);
52766         }
52767         function getAssignedTypeOfShorthandPropertyAssignment(node) {
52768             return getTypeWithDefault(getAssignedTypeOfPropertyAssignment(node), node.objectAssignmentInitializer);
52769         }
52770         function getAssignedType(node) {
52771             var parent = node.parent;
52772             switch (parent.kind) {
52773                 case 231 /* ForInStatement */:
52774                     return stringType;
52775                 case 232 /* ForOfStatement */:
52776                     return checkRightHandSideOfForOf(parent) || errorType;
52777                 case 209 /* BinaryExpression */:
52778                     return getAssignedTypeOfBinaryExpression(parent);
52779                 case 203 /* DeleteExpression */:
52780                     return undefinedType;
52781                 case 192 /* ArrayLiteralExpression */:
52782                     return getAssignedTypeOfArrayLiteralElement(parent, node);
52783                 case 213 /* SpreadElement */:
52784                     return getAssignedTypeOfSpreadExpression(parent);
52785                 case 281 /* PropertyAssignment */:
52786                     return getAssignedTypeOfPropertyAssignment(parent);
52787                 case 282 /* ShorthandPropertyAssignment */:
52788                     return getAssignedTypeOfShorthandPropertyAssignment(parent);
52789             }
52790             return errorType;
52791         }
52792         function getInitialTypeOfBindingElement(node) {
52793             var pattern = node.parent;
52794             var parentType = getInitialType(pattern.parent);
52795             var type = pattern.kind === 189 /* ObjectBindingPattern */ ?
52796                 getTypeOfDestructuredProperty(parentType, node.propertyName || node.name) :
52797                 !node.dotDotDotToken ?
52798                     getTypeOfDestructuredArrayElement(parentType, pattern.elements.indexOf(node)) :
52799                     getTypeOfDestructuredSpreadExpression(parentType);
52800             return getTypeWithDefault(type, node.initializer);
52801         }
52802         function getTypeOfInitializer(node) {
52803             // Return the cached type if one is available. If the type of the variable was inferred
52804             // from its initializer, we'll already have cached the type. Otherwise we compute it now
52805             // without caching such that transient types are reflected.
52806             var links = getNodeLinks(node);
52807             return links.resolvedType || getTypeOfExpression(node);
52808         }
52809         function getInitialTypeOfVariableDeclaration(node) {
52810             if (node.initializer) {
52811                 return getTypeOfInitializer(node.initializer);
52812             }
52813             if (node.parent.parent.kind === 231 /* ForInStatement */) {
52814                 return stringType;
52815             }
52816             if (node.parent.parent.kind === 232 /* ForOfStatement */) {
52817                 return checkRightHandSideOfForOf(node.parent.parent) || errorType;
52818             }
52819             return errorType;
52820         }
52821         function getInitialType(node) {
52822             return node.kind === 242 /* VariableDeclaration */ ?
52823                 getInitialTypeOfVariableDeclaration(node) :
52824                 getInitialTypeOfBindingElement(node);
52825         }
52826         function isEmptyArrayAssignment(node) {
52827             return node.kind === 242 /* VariableDeclaration */ && node.initializer &&
52828                 isEmptyArrayLiteral(node.initializer) ||
52829                 node.kind !== 191 /* BindingElement */ && node.parent.kind === 209 /* BinaryExpression */ &&
52830                     isEmptyArrayLiteral(node.parent.right);
52831         }
52832         function getReferenceCandidate(node) {
52833             switch (node.kind) {
52834                 case 200 /* ParenthesizedExpression */:
52835                     return getReferenceCandidate(node.expression);
52836                 case 209 /* BinaryExpression */:
52837                     switch (node.operatorToken.kind) {
52838                         case 62 /* EqualsToken */:
52839                             return getReferenceCandidate(node.left);
52840                         case 27 /* CommaToken */:
52841                             return getReferenceCandidate(node.right);
52842                     }
52843             }
52844             return node;
52845         }
52846         function getReferenceRoot(node) {
52847             var parent = node.parent;
52848             return parent.kind === 200 /* ParenthesizedExpression */ ||
52849                 parent.kind === 209 /* BinaryExpression */ && parent.operatorToken.kind === 62 /* EqualsToken */ && parent.left === node ||
52850                 parent.kind === 209 /* BinaryExpression */ && parent.operatorToken.kind === 27 /* CommaToken */ && parent.right === node ?
52851                 getReferenceRoot(parent) : node;
52852         }
52853         function getTypeOfSwitchClause(clause) {
52854             if (clause.kind === 277 /* CaseClause */) {
52855                 return getRegularTypeOfLiteralType(getTypeOfExpression(clause.expression));
52856             }
52857             return neverType;
52858         }
52859         function getSwitchClauseTypes(switchStatement) {
52860             var links = getNodeLinks(switchStatement);
52861             if (!links.switchTypes) {
52862                 links.switchTypes = [];
52863                 for (var _i = 0, _a = switchStatement.caseBlock.clauses; _i < _a.length; _i++) {
52864                     var clause = _a[_i];
52865                     links.switchTypes.push(getTypeOfSwitchClause(clause));
52866                 }
52867             }
52868             return links.switchTypes;
52869         }
52870         function getSwitchClauseTypeOfWitnesses(switchStatement, retainDefault) {
52871             var witnesses = [];
52872             for (var _i = 0, _a = switchStatement.caseBlock.clauses; _i < _a.length; _i++) {
52873                 var clause = _a[_i];
52874                 if (clause.kind === 277 /* CaseClause */) {
52875                     if (ts.isStringLiteralLike(clause.expression)) {
52876                         witnesses.push(clause.expression.text);
52877                         continue;
52878                     }
52879                     return ts.emptyArray;
52880                 }
52881                 if (retainDefault)
52882                     witnesses.push(/*explicitDefaultStatement*/ undefined);
52883             }
52884             return witnesses;
52885         }
52886         function eachTypeContainedIn(source, types) {
52887             return source.flags & 1048576 /* Union */ ? !ts.forEach(source.types, function (t) { return !ts.contains(types, t); }) : ts.contains(types, source);
52888         }
52889         function isTypeSubsetOf(source, target) {
52890             return source === target || target.flags & 1048576 /* Union */ && isTypeSubsetOfUnion(source, target);
52891         }
52892         function isTypeSubsetOfUnion(source, target) {
52893             if (source.flags & 1048576 /* Union */) {
52894                 for (var _i = 0, _a = source.types; _i < _a.length; _i++) {
52895                     var t = _a[_i];
52896                     if (!containsType(target.types, t)) {
52897                         return false;
52898                     }
52899                 }
52900                 return true;
52901             }
52902             if (source.flags & 1024 /* EnumLiteral */ && getBaseTypeOfEnumLiteralType(source) === target) {
52903                 return true;
52904             }
52905             return containsType(target.types, source);
52906         }
52907         function forEachType(type, f) {
52908             return type.flags & 1048576 /* Union */ ? ts.forEach(type.types, f) : f(type);
52909         }
52910         function everyType(type, f) {
52911             return type.flags & 1048576 /* Union */ ? ts.every(type.types, f) : f(type);
52912         }
52913         function filterType(type, f) {
52914             if (type.flags & 1048576 /* Union */) {
52915                 var types = type.types;
52916                 var filtered = ts.filter(types, f);
52917                 return filtered === types ? type : getUnionTypeFromSortedList(filtered, type.objectFlags);
52918             }
52919             return type.flags & 131072 /* Never */ || f(type) ? type : neverType;
52920         }
52921         function countTypes(type) {
52922             return type.flags & 1048576 /* Union */ ? type.types.length : 1;
52923         }
52924         function mapType(type, mapper, noReductions) {
52925             if (type.flags & 131072 /* Never */) {
52926                 return type;
52927             }
52928             if (!(type.flags & 1048576 /* Union */)) {
52929                 return mapper(type);
52930             }
52931             var mappedTypes;
52932             for (var _i = 0, _a = type.types; _i < _a.length; _i++) {
52933                 var t = _a[_i];
52934                 var mapped = mapper(t);
52935                 if (mapped) {
52936                     if (!mappedTypes) {
52937                         mappedTypes = [mapped];
52938                     }
52939                     else {
52940                         mappedTypes.push(mapped);
52941                     }
52942                 }
52943             }
52944             return mappedTypes && getUnionType(mappedTypes, noReductions ? 0 /* None */ : 1 /* Literal */);
52945         }
52946         function extractTypesOfKind(type, kind) {
52947             return filterType(type, function (t) { return (t.flags & kind) !== 0; });
52948         }
52949         // Return a new type in which occurrences of the string and number primitive types in
52950         // typeWithPrimitives have been replaced with occurrences of string literals and numeric
52951         // literals in typeWithLiterals, respectively.
52952         function replacePrimitivesWithLiterals(typeWithPrimitives, typeWithLiterals) {
52953             if (isTypeSubsetOf(stringType, typeWithPrimitives) && maybeTypeOfKind(typeWithLiterals, 128 /* StringLiteral */) ||
52954                 isTypeSubsetOf(numberType, typeWithPrimitives) && maybeTypeOfKind(typeWithLiterals, 256 /* NumberLiteral */) ||
52955                 isTypeSubsetOf(bigintType, typeWithPrimitives) && maybeTypeOfKind(typeWithLiterals, 2048 /* BigIntLiteral */)) {
52956                 return mapType(typeWithPrimitives, function (t) {
52957                     return t.flags & 4 /* String */ ? extractTypesOfKind(typeWithLiterals, 4 /* String */ | 128 /* StringLiteral */) :
52958                         t.flags & 8 /* Number */ ? extractTypesOfKind(typeWithLiterals, 8 /* Number */ | 256 /* NumberLiteral */) :
52959                             t.flags & 64 /* BigInt */ ? extractTypesOfKind(typeWithLiterals, 64 /* BigInt */ | 2048 /* BigIntLiteral */) : t;
52960                 });
52961             }
52962             return typeWithPrimitives;
52963         }
52964         function isIncomplete(flowType) {
52965             return flowType.flags === 0;
52966         }
52967         function getTypeFromFlowType(flowType) {
52968             return flowType.flags === 0 ? flowType.type : flowType;
52969         }
52970         function createFlowType(type, incomplete) {
52971             return incomplete ? { flags: 0, type: type } : type;
52972         }
52973         // An evolving array type tracks the element types that have so far been seen in an
52974         // 'x.push(value)' or 'x[n] = value' operation along the control flow graph. Evolving
52975         // array types are ultimately converted into manifest array types (using getFinalArrayType)
52976         // and never escape the getFlowTypeOfReference function.
52977         function createEvolvingArrayType(elementType) {
52978             var result = createObjectType(256 /* EvolvingArray */);
52979             result.elementType = elementType;
52980             return result;
52981         }
52982         function getEvolvingArrayType(elementType) {
52983             return evolvingArrayTypes[elementType.id] || (evolvingArrayTypes[elementType.id] = createEvolvingArrayType(elementType));
52984         }
52985         // When adding evolving array element types we do not perform subtype reduction. Instead,
52986         // we defer subtype reduction until the evolving array type is finalized into a manifest
52987         // array type.
52988         function addEvolvingArrayElementType(evolvingArrayType, node) {
52989             var elementType = getBaseTypeOfLiteralType(getContextFreeTypeOfExpression(node));
52990             return isTypeSubsetOf(elementType, evolvingArrayType.elementType) ? evolvingArrayType : getEvolvingArrayType(getUnionType([evolvingArrayType.elementType, elementType]));
52991         }
52992         function createFinalArrayType(elementType) {
52993             return elementType.flags & 131072 /* Never */ ?
52994                 autoArrayType :
52995                 createArrayType(elementType.flags & 1048576 /* Union */ ?
52996                     getUnionType(elementType.types, 2 /* Subtype */) :
52997                     elementType);
52998         }
52999         // We perform subtype reduction upon obtaining the final array type from an evolving array type.
53000         function getFinalArrayType(evolvingArrayType) {
53001             return evolvingArrayType.finalArrayType || (evolvingArrayType.finalArrayType = createFinalArrayType(evolvingArrayType.elementType));
53002         }
53003         function finalizeEvolvingArrayType(type) {
53004             return ts.getObjectFlags(type) & 256 /* EvolvingArray */ ? getFinalArrayType(type) : type;
53005         }
53006         function getElementTypeOfEvolvingArrayType(type) {
53007             return ts.getObjectFlags(type) & 256 /* EvolvingArray */ ? type.elementType : neverType;
53008         }
53009         function isEvolvingArrayTypeList(types) {
53010             var hasEvolvingArrayType = false;
53011             for (var _i = 0, types_16 = types; _i < types_16.length; _i++) {
53012                 var t = types_16[_i];
53013                 if (!(t.flags & 131072 /* Never */)) {
53014                     if (!(ts.getObjectFlags(t) & 256 /* EvolvingArray */)) {
53015                         return false;
53016                     }
53017                     hasEvolvingArrayType = true;
53018                 }
53019             }
53020             return hasEvolvingArrayType;
53021         }
53022         // At flow control branch or loop junctions, if the type along every antecedent code path
53023         // is an evolving array type, we construct a combined evolving array type. Otherwise we
53024         // finalize all evolving array types.
53025         function getUnionOrEvolvingArrayType(types, subtypeReduction) {
53026             return isEvolvingArrayTypeList(types) ?
53027                 getEvolvingArrayType(getUnionType(ts.map(types, getElementTypeOfEvolvingArrayType))) :
53028                 getUnionType(ts.sameMap(types, finalizeEvolvingArrayType), subtypeReduction);
53029         }
53030         // Return true if the given node is 'x' in an 'x.length', x.push(value)', 'x.unshift(value)' or
53031         // 'x[n] = value' operation, where 'n' is an expression of type any, undefined, or a number-like type.
53032         function isEvolvingArrayOperationTarget(node) {
53033             var root = getReferenceRoot(node);
53034             var parent = root.parent;
53035             var isLengthPushOrUnshift = ts.isPropertyAccessExpression(parent) && (parent.name.escapedText === "length" ||
53036                 parent.parent.kind === 196 /* CallExpression */
53037                     && ts.isIdentifier(parent.name)
53038                     && ts.isPushOrUnshiftIdentifier(parent.name));
53039             var isElementAssignment = parent.kind === 195 /* ElementAccessExpression */ &&
53040                 parent.expression === root &&
53041                 parent.parent.kind === 209 /* BinaryExpression */ &&
53042                 parent.parent.operatorToken.kind === 62 /* EqualsToken */ &&
53043                 parent.parent.left === parent &&
53044                 !ts.isAssignmentTarget(parent.parent) &&
53045                 isTypeAssignableToKind(getTypeOfExpression(parent.argumentExpression), 296 /* NumberLike */);
53046             return isLengthPushOrUnshift || isElementAssignment;
53047         }
53048         function isDeclarationWithExplicitTypeAnnotation(declaration) {
53049             return (declaration.kind === 242 /* VariableDeclaration */ || declaration.kind === 156 /* Parameter */ ||
53050                 declaration.kind === 159 /* PropertyDeclaration */ || declaration.kind === 158 /* PropertySignature */) &&
53051                 !!ts.getEffectiveTypeAnnotationNode(declaration);
53052         }
53053         function getExplicitTypeOfSymbol(symbol, diagnostic) {
53054             if (symbol.flags & (16 /* Function */ | 8192 /* Method */ | 32 /* Class */ | 512 /* ValueModule */)) {
53055                 return getTypeOfSymbol(symbol);
53056             }
53057             if (symbol.flags & (3 /* Variable */ | 4 /* Property */)) {
53058                 var declaration = symbol.valueDeclaration;
53059                 if (declaration) {
53060                     if (isDeclarationWithExplicitTypeAnnotation(declaration)) {
53061                         return getTypeOfSymbol(symbol);
53062                     }
53063                     if (ts.isVariableDeclaration(declaration) && declaration.parent.parent.kind === 232 /* ForOfStatement */) {
53064                         var statement = declaration.parent.parent;
53065                         var expressionType = getTypeOfDottedName(statement.expression, /*diagnostic*/ undefined);
53066                         if (expressionType) {
53067                             var use = statement.awaitModifier ? 15 /* ForAwaitOf */ : 13 /* ForOf */;
53068                             return checkIteratedTypeOrElementType(use, expressionType, undefinedType, /*errorNode*/ undefined);
53069                         }
53070                     }
53071                     if (diagnostic) {
53072                         ts.addRelatedInfo(diagnostic, ts.createDiagnosticForNode(declaration, ts.Diagnostics._0_needs_an_explicit_type_annotation, symbolToString(symbol)));
53073                     }
53074                 }
53075             }
53076         }
53077         // We require the dotted function name in an assertion expression to be comprised of identifiers
53078         // that reference function, method, class or value module symbols; or variable, property or
53079         // parameter symbols with declarations that have explicit type annotations. Such references are
53080         // resolvable with no possibility of triggering circularities in control flow analysis.
53081         function getTypeOfDottedName(node, diagnostic) {
53082             if (!(node.flags & 16777216 /* InWithStatement */)) {
53083                 switch (node.kind) {
53084                     case 75 /* Identifier */:
53085                         var symbol = getExportSymbolOfValueSymbolIfExported(getResolvedSymbol(node));
53086                         return getExplicitTypeOfSymbol(symbol.flags & 2097152 /* Alias */ ? resolveAlias(symbol) : symbol, diagnostic);
53087                     case 104 /* ThisKeyword */:
53088                         return getExplicitThisType(node);
53089                     case 102 /* SuperKeyword */:
53090                         return checkSuperExpression(node);
53091                     case 194 /* PropertyAccessExpression */:
53092                         var type = getTypeOfDottedName(node.expression, diagnostic);
53093                         var prop = type && getPropertyOfType(type, node.name.escapedText);
53094                         return prop && getExplicitTypeOfSymbol(prop, diagnostic);
53095                     case 200 /* ParenthesizedExpression */:
53096                         return getTypeOfDottedName(node.expression, diagnostic);
53097                 }
53098             }
53099         }
53100         function getEffectsSignature(node) {
53101             var links = getNodeLinks(node);
53102             var signature = links.effectsSignature;
53103             if (signature === undefined) {
53104                 // A call expression parented by an expression statement is a potential assertion. Other call
53105                 // expressions are potential type predicate function calls. In order to avoid triggering
53106                 // circularities in control flow analysis, we use getTypeOfDottedName when resolving the call
53107                 // target expression of an assertion.
53108                 var funcType = void 0;
53109                 if (node.parent.kind === 226 /* ExpressionStatement */) {
53110                     funcType = getTypeOfDottedName(node.expression, /*diagnostic*/ undefined);
53111                 }
53112                 else if (node.expression.kind !== 102 /* SuperKeyword */) {
53113                     if (ts.isOptionalChain(node)) {
53114                         funcType = checkNonNullType(getOptionalExpressionType(checkExpression(node.expression), node.expression), node.expression);
53115                     }
53116                     else {
53117                         funcType = checkNonNullExpression(node.expression);
53118                     }
53119                 }
53120                 var signatures = getSignaturesOfType(funcType && getApparentType(funcType) || unknownType, 0 /* Call */);
53121                 var candidate = signatures.length === 1 && !signatures[0].typeParameters ? signatures[0] :
53122                     ts.some(signatures, hasTypePredicateOrNeverReturnType) ? getResolvedSignature(node) :
53123                         undefined;
53124                 signature = links.effectsSignature = candidate && hasTypePredicateOrNeverReturnType(candidate) ? candidate : unknownSignature;
53125             }
53126             return signature === unknownSignature ? undefined : signature;
53127         }
53128         function hasTypePredicateOrNeverReturnType(signature) {
53129             return !!(getTypePredicateOfSignature(signature) ||
53130                 signature.declaration && (getReturnTypeFromAnnotation(signature.declaration) || unknownType).flags & 131072 /* Never */);
53131         }
53132         function getTypePredicateArgument(predicate, callExpression) {
53133             if (predicate.kind === 1 /* Identifier */ || predicate.kind === 3 /* AssertsIdentifier */) {
53134                 return callExpression.arguments[predicate.parameterIndex];
53135             }
53136             var invokedExpression = ts.skipParentheses(callExpression.expression);
53137             return ts.isAccessExpression(invokedExpression) ? ts.skipParentheses(invokedExpression.expression) : undefined;
53138         }
53139         function reportFlowControlError(node) {
53140             var block = ts.findAncestor(node, ts.isFunctionOrModuleBlock);
53141             var sourceFile = ts.getSourceFileOfNode(node);
53142             var span = ts.getSpanOfTokenAtPosition(sourceFile, block.statements.pos);
53143             diagnostics.add(ts.createFileDiagnostic(sourceFile, span.start, span.length, ts.Diagnostics.The_containing_function_or_module_body_is_too_large_for_control_flow_analysis));
53144         }
53145         function isReachableFlowNode(flow) {
53146             var result = isReachableFlowNodeWorker(flow, /*noCacheCheck*/ false);
53147             lastFlowNode = flow;
53148             lastFlowNodeReachable = result;
53149             return result;
53150         }
53151         function isFalseExpression(expr) {
53152             var node = ts.skipParentheses(expr);
53153             return node.kind === 91 /* FalseKeyword */ || node.kind === 209 /* BinaryExpression */ && (node.operatorToken.kind === 55 /* AmpersandAmpersandToken */ && (isFalseExpression(node.left) || isFalseExpression(node.right)) ||
53154                 node.operatorToken.kind === 56 /* BarBarToken */ && isFalseExpression(node.left) && isFalseExpression(node.right));
53155         }
53156         function isReachableFlowNodeWorker(flow, noCacheCheck) {
53157             while (true) {
53158                 if (flow === lastFlowNode) {
53159                     return lastFlowNodeReachable;
53160                 }
53161                 var flags = flow.flags;
53162                 if (flags & 4096 /* Shared */) {
53163                     if (!noCacheCheck) {
53164                         var id = getFlowNodeId(flow);
53165                         var reachable = flowNodeReachable[id];
53166                         return reachable !== undefined ? reachable : (flowNodeReachable[id] = isReachableFlowNodeWorker(flow, /*noCacheCheck*/ true));
53167                     }
53168                     noCacheCheck = false;
53169                 }
53170                 if (flags & (16 /* Assignment */ | 96 /* Condition */ | 256 /* ArrayMutation */)) {
53171                     flow = flow.antecedent;
53172                 }
53173                 else if (flags & 512 /* Call */) {
53174                     var signature = getEffectsSignature(flow.node);
53175                     if (signature) {
53176                         var predicate = getTypePredicateOfSignature(signature);
53177                         if (predicate && predicate.kind === 3 /* AssertsIdentifier */) {
53178                             var predicateArgument = flow.node.arguments[predicate.parameterIndex];
53179                             if (predicateArgument && isFalseExpression(predicateArgument)) {
53180                                 return false;
53181                             }
53182                         }
53183                         if (getReturnTypeOfSignature(signature).flags & 131072 /* Never */) {
53184                             return false;
53185                         }
53186                     }
53187                     flow = flow.antecedent;
53188                 }
53189                 else if (flags & 4 /* BranchLabel */) {
53190                     // A branching point is reachable if any branch is reachable.
53191                     return ts.some(flow.antecedents, function (f) { return isReachableFlowNodeWorker(f, /*noCacheCheck*/ false); });
53192                 }
53193                 else if (flags & 8 /* LoopLabel */) {
53194                     // A loop is reachable if the control flow path that leads to the top is reachable.
53195                     flow = flow.antecedents[0];
53196                 }
53197                 else if (flags & 128 /* SwitchClause */) {
53198                     // The control flow path representing an unmatched value in a switch statement with
53199                     // no default clause is unreachable if the switch statement is exhaustive.
53200                     if (flow.clauseStart === flow.clauseEnd && isExhaustiveSwitchStatement(flow.switchStatement)) {
53201                         return false;
53202                     }
53203                     flow = flow.antecedent;
53204                 }
53205                 else if (flags & 1024 /* ReduceLabel */) {
53206                     // Cache is unreliable once we start adjusting labels
53207                     lastFlowNode = undefined;
53208                     var target = flow.target;
53209                     var saveAntecedents = target.antecedents;
53210                     target.antecedents = flow.antecedents;
53211                     var result = isReachableFlowNodeWorker(flow.antecedent, /*noCacheCheck*/ false);
53212                     target.antecedents = saveAntecedents;
53213                     return result;
53214                 }
53215                 else {
53216                     return !(flags & 1 /* Unreachable */);
53217                 }
53218             }
53219         }
53220         function getFlowTypeOfReference(reference, declaredType, initialType, flowContainer, couldBeUninitialized) {
53221             if (initialType === void 0) { initialType = declaredType; }
53222             var key;
53223             var keySet = false;
53224             var flowDepth = 0;
53225             if (flowAnalysisDisabled) {
53226                 return errorType;
53227             }
53228             if (!reference.flowNode || !couldBeUninitialized && !(declaredType.flags & 133970943 /* Narrowable */)) {
53229                 return declaredType;
53230             }
53231             flowInvocationCount++;
53232             var sharedFlowStart = sharedFlowCount;
53233             var evolvedType = getTypeFromFlowType(getTypeAtFlowNode(reference.flowNode));
53234             sharedFlowCount = sharedFlowStart;
53235             // When the reference is 'x' in an 'x.length', 'x.push(value)', 'x.unshift(value)' or x[n] = value' operation,
53236             // we give type 'any[]' to 'x' instead of using the type determined by control flow analysis such that operations
53237             // on empty arrays are possible without implicit any errors and new element types can be inferred without
53238             // type mismatch errors.
53239             var resultType = ts.getObjectFlags(evolvedType) & 256 /* EvolvingArray */ && isEvolvingArrayOperationTarget(reference) ? autoArrayType : finalizeEvolvingArrayType(evolvedType);
53240             if (resultType === unreachableNeverType || reference.parent && reference.parent.kind === 218 /* NonNullExpression */ && getTypeWithFacts(resultType, 2097152 /* NEUndefinedOrNull */).flags & 131072 /* Never */) {
53241                 return declaredType;
53242             }
53243             return resultType;
53244             function getOrSetCacheKey() {
53245                 if (keySet) {
53246                     return key;
53247                 }
53248                 keySet = true;
53249                 return key = getFlowCacheKey(reference, declaredType, initialType, flowContainer);
53250             }
53251             function getTypeAtFlowNode(flow) {
53252                 if (flowDepth === 2000) {
53253                     // We have made 2000 recursive invocations. To avoid overflowing the call stack we report an error
53254                     // and disable further control flow analysis in the containing function or module body.
53255                     flowAnalysisDisabled = true;
53256                     reportFlowControlError(reference);
53257                     return errorType;
53258                 }
53259                 flowDepth++;
53260                 while (true) {
53261                     var flags = flow.flags;
53262                     if (flags & 4096 /* Shared */) {
53263                         // We cache results of flow type resolution for shared nodes that were previously visited in
53264                         // the same getFlowTypeOfReference invocation. A node is considered shared when it is the
53265                         // antecedent of more than one node.
53266                         for (var i = sharedFlowStart; i < sharedFlowCount; i++) {
53267                             if (sharedFlowNodes[i] === flow) {
53268                                 flowDepth--;
53269                                 return sharedFlowTypes[i];
53270                             }
53271                         }
53272                     }
53273                     var type = void 0;
53274                     if (flags & 16 /* Assignment */) {
53275                         type = getTypeAtFlowAssignment(flow);
53276                         if (!type) {
53277                             flow = flow.antecedent;
53278                             continue;
53279                         }
53280                     }
53281                     else if (flags & 512 /* Call */) {
53282                         type = getTypeAtFlowCall(flow);
53283                         if (!type) {
53284                             flow = flow.antecedent;
53285                             continue;
53286                         }
53287                     }
53288                     else if (flags & 96 /* Condition */) {
53289                         type = getTypeAtFlowCondition(flow);
53290                     }
53291                     else if (flags & 128 /* SwitchClause */) {
53292                         type = getTypeAtSwitchClause(flow);
53293                     }
53294                     else if (flags & 12 /* Label */) {
53295                         if (flow.antecedents.length === 1) {
53296                             flow = flow.antecedents[0];
53297                             continue;
53298                         }
53299                         type = flags & 4 /* BranchLabel */ ?
53300                             getTypeAtFlowBranchLabel(flow) :
53301                             getTypeAtFlowLoopLabel(flow);
53302                     }
53303                     else if (flags & 256 /* ArrayMutation */) {
53304                         type = getTypeAtFlowArrayMutation(flow);
53305                         if (!type) {
53306                             flow = flow.antecedent;
53307                             continue;
53308                         }
53309                     }
53310                     else if (flags & 1024 /* ReduceLabel */) {
53311                         var target = flow.target;
53312                         var saveAntecedents = target.antecedents;
53313                         target.antecedents = flow.antecedents;
53314                         type = getTypeAtFlowNode(flow.antecedent);
53315                         target.antecedents = saveAntecedents;
53316                     }
53317                     else if (flags & 2 /* Start */) {
53318                         // Check if we should continue with the control flow of the containing function.
53319                         var container = flow.node;
53320                         if (container && container !== flowContainer &&
53321                             reference.kind !== 194 /* PropertyAccessExpression */ &&
53322                             reference.kind !== 195 /* ElementAccessExpression */ &&
53323                             reference.kind !== 104 /* ThisKeyword */) {
53324                             flow = container.flowNode;
53325                             continue;
53326                         }
53327                         // At the top of the flow we have the initial type.
53328                         type = initialType;
53329                     }
53330                     else {
53331                         // Unreachable code errors are reported in the binding phase. Here we
53332                         // simply return the non-auto declared type to reduce follow-on errors.
53333                         type = convertAutoToAny(declaredType);
53334                     }
53335                     if (flags & 4096 /* Shared */) {
53336                         // Record visited node and the associated type in the cache.
53337                         sharedFlowNodes[sharedFlowCount] = flow;
53338                         sharedFlowTypes[sharedFlowCount] = type;
53339                         sharedFlowCount++;
53340                     }
53341                     flowDepth--;
53342                     return type;
53343                 }
53344             }
53345             function getInitialOrAssignedType(flow) {
53346                 var node = flow.node;
53347                 return getConstraintForLocation(node.kind === 242 /* VariableDeclaration */ || node.kind === 191 /* BindingElement */ ?
53348                     getInitialType(node) :
53349                     getAssignedType(node), reference);
53350             }
53351             function getTypeAtFlowAssignment(flow) {
53352                 var node = flow.node;
53353                 // Assignments only narrow the computed type if the declared type is a union type. Thus, we
53354                 // only need to evaluate the assigned type if the declared type is a union type.
53355                 if (isMatchingReference(reference, node)) {
53356                     if (!isReachableFlowNode(flow)) {
53357                         return unreachableNeverType;
53358                     }
53359                     if (ts.getAssignmentTargetKind(node) === 2 /* Compound */) {
53360                         var flowType = getTypeAtFlowNode(flow.antecedent);
53361                         return createFlowType(getBaseTypeOfLiteralType(getTypeFromFlowType(flowType)), isIncomplete(flowType));
53362                     }
53363                     if (declaredType === autoType || declaredType === autoArrayType) {
53364                         if (isEmptyArrayAssignment(node)) {
53365                             return getEvolvingArrayType(neverType);
53366                         }
53367                         var assignedType = getBaseTypeOfLiteralType(getInitialOrAssignedType(flow));
53368                         return isTypeAssignableTo(assignedType, declaredType) ? assignedType : anyArrayType;
53369                     }
53370                     if (declaredType.flags & 1048576 /* Union */) {
53371                         return getAssignmentReducedType(declaredType, getInitialOrAssignedType(flow));
53372                     }
53373                     return declaredType;
53374                 }
53375                 // We didn't have a direct match. However, if the reference is a dotted name, this
53376                 // may be an assignment to a left hand part of the reference. For example, for a
53377                 // reference 'x.y.z', we may be at an assignment to 'x.y' or 'x'. In that case,
53378                 // return the declared type.
53379                 if (containsMatchingReference(reference, node)) {
53380                     if (!isReachableFlowNode(flow)) {
53381                         return unreachableNeverType;
53382                     }
53383                     // A matching dotted name might also be an expando property on a function *expression*,
53384                     // in which case we continue control flow analysis back to the function's declaration
53385                     if (ts.isVariableDeclaration(node) && (ts.isInJSFile(node) || ts.isVarConst(node))) {
53386                         var init = ts.getDeclaredExpandoInitializer(node);
53387                         if (init && (init.kind === 201 /* FunctionExpression */ || init.kind === 202 /* ArrowFunction */)) {
53388                             return getTypeAtFlowNode(flow.antecedent);
53389                         }
53390                     }
53391                     return declaredType;
53392                 }
53393                 // for (const _ in ref) acts as a nonnull on ref
53394                 if (ts.isVariableDeclaration(node) && node.parent.parent.kind === 231 /* ForInStatement */ && isMatchingReference(reference, node.parent.parent.expression)) {
53395                     return getNonNullableTypeIfNeeded(getTypeFromFlowType(getTypeAtFlowNode(flow.antecedent)));
53396                 }
53397                 // Assignment doesn't affect reference
53398                 return undefined;
53399             }
53400             function narrowTypeByAssertion(type, expr) {
53401                 var node = ts.skipParentheses(expr);
53402                 if (node.kind === 91 /* FalseKeyword */) {
53403                     return unreachableNeverType;
53404                 }
53405                 if (node.kind === 209 /* BinaryExpression */) {
53406                     if (node.operatorToken.kind === 55 /* AmpersandAmpersandToken */) {
53407                         return narrowTypeByAssertion(narrowTypeByAssertion(type, node.left), node.right);
53408                     }
53409                     if (node.operatorToken.kind === 56 /* BarBarToken */) {
53410                         return getUnionType([narrowTypeByAssertion(type, node.left), narrowTypeByAssertion(type, node.right)]);
53411                     }
53412                 }
53413                 return narrowType(type, node, /*assumeTrue*/ true);
53414             }
53415             function getTypeAtFlowCall(flow) {
53416                 var signature = getEffectsSignature(flow.node);
53417                 if (signature) {
53418                     var predicate = getTypePredicateOfSignature(signature);
53419                     if (predicate && (predicate.kind === 2 /* AssertsThis */ || predicate.kind === 3 /* AssertsIdentifier */)) {
53420                         var flowType = getTypeAtFlowNode(flow.antecedent);
53421                         var type = finalizeEvolvingArrayType(getTypeFromFlowType(flowType));
53422                         var narrowedType = predicate.type ? narrowTypeByTypePredicate(type, predicate, flow.node, /*assumeTrue*/ true) :
53423                             predicate.kind === 3 /* AssertsIdentifier */ && predicate.parameterIndex >= 0 && predicate.parameterIndex < flow.node.arguments.length ? narrowTypeByAssertion(type, flow.node.arguments[predicate.parameterIndex]) :
53424                                 type;
53425                         return narrowedType === type ? flowType : createFlowType(narrowedType, isIncomplete(flowType));
53426                     }
53427                     if (getReturnTypeOfSignature(signature).flags & 131072 /* Never */) {
53428                         return unreachableNeverType;
53429                     }
53430                 }
53431                 return undefined;
53432             }
53433             function getTypeAtFlowArrayMutation(flow) {
53434                 if (declaredType === autoType || declaredType === autoArrayType) {
53435                     var node = flow.node;
53436                     var expr = node.kind === 196 /* CallExpression */ ?
53437                         node.expression.expression :
53438                         node.left.expression;
53439                     if (isMatchingReference(reference, getReferenceCandidate(expr))) {
53440                         var flowType = getTypeAtFlowNode(flow.antecedent);
53441                         var type = getTypeFromFlowType(flowType);
53442                         if (ts.getObjectFlags(type) & 256 /* EvolvingArray */) {
53443                             var evolvedType_1 = type;
53444                             if (node.kind === 196 /* CallExpression */) {
53445                                 for (var _i = 0, _a = node.arguments; _i < _a.length; _i++) {
53446                                     var arg = _a[_i];
53447                                     evolvedType_1 = addEvolvingArrayElementType(evolvedType_1, arg);
53448                                 }
53449                             }
53450                             else {
53451                                 // 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)
53452                                 var indexType = getContextFreeTypeOfExpression(node.left.argumentExpression);
53453                                 if (isTypeAssignableToKind(indexType, 296 /* NumberLike */)) {
53454                                     evolvedType_1 = addEvolvingArrayElementType(evolvedType_1, node.right);
53455                                 }
53456                             }
53457                             return evolvedType_1 === type ? flowType : createFlowType(evolvedType_1, isIncomplete(flowType));
53458                         }
53459                         return flowType;
53460                     }
53461                 }
53462                 return undefined;
53463             }
53464             function getTypeAtFlowCondition(flow) {
53465                 var flowType = getTypeAtFlowNode(flow.antecedent);
53466                 var type = getTypeFromFlowType(flowType);
53467                 if (type.flags & 131072 /* Never */) {
53468                     return flowType;
53469                 }
53470                 // If we have an antecedent type (meaning we're reachable in some way), we first
53471                 // attempt to narrow the antecedent type. If that produces the never type, and if
53472                 // the antecedent type is incomplete (i.e. a transient type in a loop), then we
53473                 // take the type guard as an indication that control *could* reach here once we
53474                 // have the complete type. We proceed by switching to the silent never type which
53475                 // doesn't report errors when operators are applied to it. Note that this is the
53476                 // *only* place a silent never type is ever generated.
53477                 var assumeTrue = (flow.flags & 32 /* TrueCondition */) !== 0;
53478                 var nonEvolvingType = finalizeEvolvingArrayType(type);
53479                 var narrowedType = narrowType(nonEvolvingType, flow.node, assumeTrue);
53480                 if (narrowedType === nonEvolvingType) {
53481                     return flowType;
53482                 }
53483                 var incomplete = isIncomplete(flowType);
53484                 var resultType = incomplete && narrowedType.flags & 131072 /* Never */ ? silentNeverType : narrowedType;
53485                 return createFlowType(resultType, incomplete);
53486             }
53487             function getTypeAtSwitchClause(flow) {
53488                 var expr = flow.switchStatement.expression;
53489                 var flowType = getTypeAtFlowNode(flow.antecedent);
53490                 var type = getTypeFromFlowType(flowType);
53491                 if (isMatchingReference(reference, expr)) {
53492                     type = narrowTypeBySwitchOnDiscriminant(type, flow.switchStatement, flow.clauseStart, flow.clauseEnd);
53493                 }
53494                 else if (expr.kind === 204 /* TypeOfExpression */ && isMatchingReference(reference, expr.expression)) {
53495                     type = narrowBySwitchOnTypeOf(type, flow.switchStatement, flow.clauseStart, flow.clauseEnd);
53496                 }
53497                 else {
53498                     if (strictNullChecks) {
53499                         if (optionalChainContainsReference(expr, reference)) {
53500                             type = narrowTypeBySwitchOptionalChainContainment(type, flow.switchStatement, flow.clauseStart, flow.clauseEnd, function (t) { return !(t.flags & (32768 /* Undefined */ | 131072 /* Never */)); });
53501                         }
53502                         else if (expr.kind === 204 /* TypeOfExpression */ && optionalChainContainsReference(expr.expression, reference)) {
53503                             type = narrowTypeBySwitchOptionalChainContainment(type, flow.switchStatement, flow.clauseStart, flow.clauseEnd, function (t) { return !(t.flags & 131072 /* Never */ || t.flags & 128 /* StringLiteral */ && t.value === "undefined"); });
53504                         }
53505                     }
53506                     if (isMatchingReferenceDiscriminant(expr, type)) {
53507                         type = narrowTypeByDiscriminant(type, expr, function (t) { return narrowTypeBySwitchOnDiscriminant(t, flow.switchStatement, flow.clauseStart, flow.clauseEnd); });
53508                     }
53509                 }
53510                 return createFlowType(type, isIncomplete(flowType));
53511             }
53512             function getTypeAtFlowBranchLabel(flow) {
53513                 var antecedentTypes = [];
53514                 var subtypeReduction = false;
53515                 var seenIncomplete = false;
53516                 var bypassFlow;
53517                 for (var _i = 0, _a = flow.antecedents; _i < _a.length; _i++) {
53518                     var antecedent = _a[_i];
53519                     if (!bypassFlow && antecedent.flags & 128 /* SwitchClause */ && antecedent.clauseStart === antecedent.clauseEnd) {
53520                         // The antecedent is the bypass branch of a potentially exhaustive switch statement.
53521                         bypassFlow = antecedent;
53522                         continue;
53523                     }
53524                     var flowType = getTypeAtFlowNode(antecedent);
53525                     var type = getTypeFromFlowType(flowType);
53526                     // If the type at a particular antecedent path is the declared type and the
53527                     // reference is known to always be assigned (i.e. when declared and initial types
53528                     // are the same), there is no reason to process more antecedents since the only
53529                     // possible outcome is subtypes that will be removed in the final union type anyway.
53530                     if (type === declaredType && declaredType === initialType) {
53531                         return type;
53532                     }
53533                     ts.pushIfUnique(antecedentTypes, type);
53534                     // If an antecedent type is not a subset of the declared type, we need to perform
53535                     // subtype reduction. This happens when a "foreign" type is injected into the control
53536                     // flow using the instanceof operator or a user defined type predicate.
53537                     if (!isTypeSubsetOf(type, declaredType)) {
53538                         subtypeReduction = true;
53539                     }
53540                     if (isIncomplete(flowType)) {
53541                         seenIncomplete = true;
53542                     }
53543                 }
53544                 if (bypassFlow) {
53545                     var flowType = getTypeAtFlowNode(bypassFlow);
53546                     var type = getTypeFromFlowType(flowType);
53547                     // If the bypass flow contributes a type we haven't seen yet and the switch statement
53548                     // isn't exhaustive, process the bypass flow type. Since exhaustiveness checks increase
53549                     // the risk of circularities, we only want to perform them when they make a difference.
53550                     if (!ts.contains(antecedentTypes, type) && !isExhaustiveSwitchStatement(bypassFlow.switchStatement)) {
53551                         if (type === declaredType && declaredType === initialType) {
53552                             return type;
53553                         }
53554                         antecedentTypes.push(type);
53555                         if (!isTypeSubsetOf(type, declaredType)) {
53556                             subtypeReduction = true;
53557                         }
53558                         if (isIncomplete(flowType)) {
53559                             seenIncomplete = true;
53560                         }
53561                     }
53562                 }
53563                 return createFlowType(getUnionOrEvolvingArrayType(antecedentTypes, subtypeReduction ? 2 /* Subtype */ : 1 /* Literal */), seenIncomplete);
53564             }
53565             function getTypeAtFlowLoopLabel(flow) {
53566                 // If we have previously computed the control flow type for the reference at
53567                 // this flow loop junction, return the cached type.
53568                 var id = getFlowNodeId(flow);
53569                 var cache = flowLoopCaches[id] || (flowLoopCaches[id] = ts.createMap());
53570                 var key = getOrSetCacheKey();
53571                 if (!key) {
53572                     // No cache key is generated when binding patterns are in unnarrowable situations
53573                     return declaredType;
53574                 }
53575                 var cached = cache.get(key);
53576                 if (cached) {
53577                     return cached;
53578                 }
53579                 // If this flow loop junction and reference are already being processed, return
53580                 // the union of the types computed for each branch so far, marked as incomplete.
53581                 // It is possible to see an empty array in cases where loops are nested and the
53582                 // back edge of the outer loop reaches an inner loop that is already being analyzed.
53583                 // In such cases we restart the analysis of the inner loop, which will then see
53584                 // a non-empty in-process array for the outer loop and eventually terminate because
53585                 // the first antecedent of a loop junction is always the non-looping control flow
53586                 // path that leads to the top.
53587                 for (var i = flowLoopStart; i < flowLoopCount; i++) {
53588                     if (flowLoopNodes[i] === flow && flowLoopKeys[i] === key && flowLoopTypes[i].length) {
53589                         return createFlowType(getUnionOrEvolvingArrayType(flowLoopTypes[i], 1 /* Literal */), /*incomplete*/ true);
53590                     }
53591                 }
53592                 // Add the flow loop junction and reference to the in-process stack and analyze
53593                 // each antecedent code path.
53594                 var antecedentTypes = [];
53595                 var subtypeReduction = false;
53596                 var firstAntecedentType;
53597                 for (var _i = 0, _a = flow.antecedents; _i < _a.length; _i++) {
53598                     var antecedent = _a[_i];
53599                     var flowType = void 0;
53600                     if (!firstAntecedentType) {
53601                         // The first antecedent of a loop junction is always the non-looping control
53602                         // flow path that leads to the top.
53603                         flowType = firstAntecedentType = getTypeAtFlowNode(antecedent);
53604                     }
53605                     else {
53606                         // All but the first antecedent are the looping control flow paths that lead
53607                         // back to the loop junction. We track these on the flow loop stack.
53608                         flowLoopNodes[flowLoopCount] = flow;
53609                         flowLoopKeys[flowLoopCount] = key;
53610                         flowLoopTypes[flowLoopCount] = antecedentTypes;
53611                         flowLoopCount++;
53612                         var saveFlowTypeCache = flowTypeCache;
53613                         flowTypeCache = undefined;
53614                         flowType = getTypeAtFlowNode(antecedent);
53615                         flowTypeCache = saveFlowTypeCache;
53616                         flowLoopCount--;
53617                         // If we see a value appear in the cache it is a sign that control flow analysis
53618                         // was restarted and completed by checkExpressionCached. We can simply pick up
53619                         // the resulting type and bail out.
53620                         var cached_1 = cache.get(key);
53621                         if (cached_1) {
53622                             return cached_1;
53623                         }
53624                     }
53625                     var type = getTypeFromFlowType(flowType);
53626                     ts.pushIfUnique(antecedentTypes, type);
53627                     // If an antecedent type is not a subset of the declared type, we need to perform
53628                     // subtype reduction. This happens when a "foreign" type is injected into the control
53629                     // flow using the instanceof operator or a user defined type predicate.
53630                     if (!isTypeSubsetOf(type, declaredType)) {
53631                         subtypeReduction = true;
53632                     }
53633                     // If the type at a particular antecedent path is the declared type there is no
53634                     // reason to process more antecedents since the only possible outcome is subtypes
53635                     // that will be removed in the final union type anyway.
53636                     if (type === declaredType) {
53637                         break;
53638                     }
53639                 }
53640                 // The result is incomplete if the first antecedent (the non-looping control flow path)
53641                 // is incomplete.
53642                 var result = getUnionOrEvolvingArrayType(antecedentTypes, subtypeReduction ? 2 /* Subtype */ : 1 /* Literal */);
53643                 if (isIncomplete(firstAntecedentType)) {
53644                     return createFlowType(result, /*incomplete*/ true);
53645                 }
53646                 cache.set(key, result);
53647                 return result;
53648             }
53649             function isMatchingReferenceDiscriminant(expr, computedType) {
53650                 if (!(computedType.flags & 1048576 /* Union */) || !ts.isAccessExpression(expr)) {
53651                     return false;
53652                 }
53653                 var name = getAccessedPropertyName(expr);
53654                 if (name === undefined) {
53655                     return false;
53656                 }
53657                 return isMatchingReference(reference, expr.expression) && isDiscriminantProperty(computedType, name);
53658             }
53659             function narrowTypeByDiscriminant(type, access, narrowType) {
53660                 var propName = getAccessedPropertyName(access);
53661                 if (propName === undefined) {
53662                     return type;
53663                 }
53664                 var propType = getTypeOfPropertyOfType(type, propName);
53665                 if (!propType) {
53666                     return type;
53667                 }
53668                 var narrowedPropType = narrowType(propType);
53669                 return filterType(type, function (t) {
53670                     var discriminantType = getTypeOfPropertyOrIndexSignature(t, propName);
53671                     return !(discriminantType.flags & 131072 /* Never */) && isTypeComparableTo(discriminantType, narrowedPropType);
53672                 });
53673             }
53674             function narrowTypeByTruthiness(type, expr, assumeTrue) {
53675                 if (isMatchingReference(reference, expr)) {
53676                     return getTypeWithFacts(type, assumeTrue ? 4194304 /* Truthy */ : 8388608 /* Falsy */);
53677                 }
53678                 if (strictNullChecks && assumeTrue && optionalChainContainsReference(expr, reference)) {
53679                     type = getTypeWithFacts(type, 2097152 /* NEUndefinedOrNull */);
53680                 }
53681                 if (isMatchingReferenceDiscriminant(expr, declaredType)) {
53682                     return narrowTypeByDiscriminant(type, expr, function (t) { return getTypeWithFacts(t, assumeTrue ? 4194304 /* Truthy */ : 8388608 /* Falsy */); });
53683                 }
53684                 return type;
53685             }
53686             function isTypePresencePossible(type, propName, assumeTrue) {
53687                 if (getIndexInfoOfType(type, 0 /* String */)) {
53688                     return true;
53689                 }
53690                 var prop = getPropertyOfType(type, propName);
53691                 if (prop) {
53692                     return prop.flags & 16777216 /* Optional */ ? true : assumeTrue;
53693                 }
53694                 return !assumeTrue;
53695             }
53696             function narrowByInKeyword(type, literal, assumeTrue) {
53697                 if (type.flags & (1048576 /* Union */ | 524288 /* Object */) || isThisTypeParameter(type)) {
53698                     var propName_1 = ts.escapeLeadingUnderscores(literal.text);
53699                     return filterType(type, function (t) { return isTypePresencePossible(t, propName_1, assumeTrue); });
53700                 }
53701                 return type;
53702             }
53703             function narrowTypeByBinaryExpression(type, expr, assumeTrue) {
53704                 switch (expr.operatorToken.kind) {
53705                     case 62 /* EqualsToken */:
53706                         return narrowTypeByTruthiness(narrowType(type, expr.right, assumeTrue), expr.left, assumeTrue);
53707                     case 34 /* EqualsEqualsToken */:
53708                     case 35 /* ExclamationEqualsToken */:
53709                     case 36 /* EqualsEqualsEqualsToken */:
53710                     case 37 /* ExclamationEqualsEqualsToken */:
53711                         var operator_1 = expr.operatorToken.kind;
53712                         var left_1 = getReferenceCandidate(expr.left);
53713                         var right_1 = getReferenceCandidate(expr.right);
53714                         if (left_1.kind === 204 /* TypeOfExpression */ && ts.isStringLiteralLike(right_1)) {
53715                             return narrowTypeByTypeof(type, left_1, operator_1, right_1, assumeTrue);
53716                         }
53717                         if (right_1.kind === 204 /* TypeOfExpression */ && ts.isStringLiteralLike(left_1)) {
53718                             return narrowTypeByTypeof(type, right_1, operator_1, left_1, assumeTrue);
53719                         }
53720                         if (isMatchingReference(reference, left_1)) {
53721                             return narrowTypeByEquality(type, operator_1, right_1, assumeTrue);
53722                         }
53723                         if (isMatchingReference(reference, right_1)) {
53724                             return narrowTypeByEquality(type, operator_1, left_1, assumeTrue);
53725                         }
53726                         if (strictNullChecks) {
53727                             if (optionalChainContainsReference(left_1, reference)) {
53728                                 type = narrowTypeByOptionalChainContainment(type, operator_1, right_1, assumeTrue);
53729                             }
53730                             else if (optionalChainContainsReference(right_1, reference)) {
53731                                 type = narrowTypeByOptionalChainContainment(type, operator_1, left_1, assumeTrue);
53732                             }
53733                         }
53734                         if (isMatchingReferenceDiscriminant(left_1, declaredType)) {
53735                             return narrowTypeByDiscriminant(type, left_1, function (t) { return narrowTypeByEquality(t, operator_1, right_1, assumeTrue); });
53736                         }
53737                         if (isMatchingReferenceDiscriminant(right_1, declaredType)) {
53738                             return narrowTypeByDiscriminant(type, right_1, function (t) { return narrowTypeByEquality(t, operator_1, left_1, assumeTrue); });
53739                         }
53740                         if (isMatchingConstructorReference(left_1)) {
53741                             return narrowTypeByConstructor(type, operator_1, right_1, assumeTrue);
53742                         }
53743                         if (isMatchingConstructorReference(right_1)) {
53744                             return narrowTypeByConstructor(type, operator_1, left_1, assumeTrue);
53745                         }
53746                         break;
53747                     case 98 /* InstanceOfKeyword */:
53748                         return narrowTypeByInstanceof(type, expr, assumeTrue);
53749                     case 97 /* InKeyword */:
53750                         var target = getReferenceCandidate(expr.right);
53751                         if (ts.isStringLiteralLike(expr.left) && isMatchingReference(reference, target)) {
53752                             return narrowByInKeyword(type, expr.left, assumeTrue);
53753                         }
53754                         break;
53755                     case 27 /* CommaToken */:
53756                         return narrowType(type, expr.right, assumeTrue);
53757                 }
53758                 return type;
53759             }
53760             function narrowTypeByOptionalChainContainment(type, operator, value, assumeTrue) {
53761                 // We are in a branch of obj?.foo === value (or any one of the other equality operators). We narrow obj as follows:
53762                 // When operator is === and type of value excludes undefined, null and undefined is removed from type of obj in true branch.
53763                 // When operator is !== and type of value excludes undefined, null and undefined is removed from type of obj in false branch.
53764                 // When operator is == and type of value excludes null and undefined, null and undefined is removed from type of obj in true branch.
53765                 // When operator is != and type of value excludes null and undefined, null and undefined is removed from type of obj in false branch.
53766                 // When operator is === and type of value is undefined, null and undefined is removed from type of obj in false branch.
53767                 // When operator is !== and type of value is undefined, null and undefined is removed from type of obj in true branch.
53768                 // When operator is == and type of value is null or undefined, null and undefined is removed from type of obj in false branch.
53769                 // When operator is != and type of value is null or undefined, null and undefined is removed from type of obj in true branch.
53770                 var equalsOperator = operator === 34 /* EqualsEqualsToken */ || operator === 36 /* EqualsEqualsEqualsToken */;
53771                 var nullableFlags = operator === 34 /* EqualsEqualsToken */ || operator === 35 /* ExclamationEqualsToken */ ? 98304 /* Nullable */ : 32768 /* Undefined */;
53772                 var valueType = getTypeOfExpression(value);
53773                 // Note that we include any and unknown in the exclusion test because their domain includes null and undefined.
53774                 var removeNullable = equalsOperator !== assumeTrue && everyType(valueType, function (t) { return !!(t.flags & nullableFlags); }) ||
53775                     equalsOperator === assumeTrue && everyType(valueType, function (t) { return !(t.flags & (3 /* AnyOrUnknown */ | nullableFlags)); });
53776                 return removeNullable ? getTypeWithFacts(type, 2097152 /* NEUndefinedOrNull */) : type;
53777             }
53778             function narrowTypeByEquality(type, operator, value, assumeTrue) {
53779                 if (type.flags & 1 /* Any */) {
53780                     return type;
53781                 }
53782                 if (operator === 35 /* ExclamationEqualsToken */ || operator === 37 /* ExclamationEqualsEqualsToken */) {
53783                     assumeTrue = !assumeTrue;
53784                 }
53785                 var valueType = getTypeOfExpression(value);
53786                 if ((type.flags & 2 /* Unknown */) && assumeTrue && (operator === 36 /* EqualsEqualsEqualsToken */ || operator === 37 /* ExclamationEqualsEqualsToken */)) {
53787                     if (valueType.flags & (131068 /* Primitive */ | 67108864 /* NonPrimitive */)) {
53788                         return valueType;
53789                     }
53790                     if (valueType.flags & 524288 /* Object */) {
53791                         return nonPrimitiveType;
53792                     }
53793                     return type;
53794                 }
53795                 if (valueType.flags & 98304 /* Nullable */) {
53796                     if (!strictNullChecks) {
53797                         return type;
53798                     }
53799                     var doubleEquals = operator === 34 /* EqualsEqualsToken */ || operator === 35 /* ExclamationEqualsToken */;
53800                     var facts = doubleEquals ?
53801                         assumeTrue ? 262144 /* EQUndefinedOrNull */ : 2097152 /* NEUndefinedOrNull */ :
53802                         valueType.flags & 65536 /* Null */ ?
53803                             assumeTrue ? 131072 /* EQNull */ : 1048576 /* NENull */ :
53804                             assumeTrue ? 65536 /* EQUndefined */ : 524288 /* NEUndefined */;
53805                     return getTypeWithFacts(type, facts);
53806                 }
53807                 if (type.flags & 67637251 /* NotUnionOrUnit */) {
53808                     return type;
53809                 }
53810                 if (assumeTrue) {
53811                     var filterFn = operator === 34 /* EqualsEqualsToken */ ?
53812                         (function (t) { return areTypesComparable(t, valueType) || isCoercibleUnderDoubleEquals(t, valueType); }) :
53813                         function (t) { return areTypesComparable(t, valueType); };
53814                     var narrowedType = filterType(type, filterFn);
53815                     return narrowedType.flags & 131072 /* Never */ ? type : replacePrimitivesWithLiterals(narrowedType, valueType);
53816                 }
53817                 if (isUnitType(valueType)) {
53818                     var regularType_1 = getRegularTypeOfLiteralType(valueType);
53819                     return filterType(type, function (t) { return isUnitType(t) ? !areTypesComparable(t, valueType) : getRegularTypeOfLiteralType(t) !== regularType_1; });
53820                 }
53821                 return type;
53822             }
53823             function narrowTypeByTypeof(type, typeOfExpr, operator, literal, assumeTrue) {
53824                 // We have '==', '!=', '===', or !==' operator with 'typeof xxx' and string literal operands
53825                 if (operator === 35 /* ExclamationEqualsToken */ || operator === 37 /* ExclamationEqualsEqualsToken */) {
53826                     assumeTrue = !assumeTrue;
53827                 }
53828                 var target = getReferenceCandidate(typeOfExpr.expression);
53829                 if (!isMatchingReference(reference, target)) {
53830                     if (strictNullChecks && optionalChainContainsReference(target, reference) && assumeTrue === (literal.text !== "undefined")) {
53831                         return getTypeWithFacts(type, 2097152 /* NEUndefinedOrNull */);
53832                     }
53833                     return type;
53834                 }
53835                 if (type.flags & 1 /* Any */ && literal.text === "function") {
53836                     return type;
53837                 }
53838                 if (assumeTrue && type.flags & 2 /* Unknown */ && literal.text === "object") {
53839                     // The pattern x && typeof x === 'object', where x is of type unknown, narrows x to type object. We don't
53840                     // need to check for the reverse typeof x === 'object' && x since that already narrows correctly.
53841                     if (typeOfExpr.parent.parent.kind === 209 /* BinaryExpression */) {
53842                         var expr = typeOfExpr.parent.parent;
53843                         if (expr.operatorToken.kind === 55 /* AmpersandAmpersandToken */ && expr.right === typeOfExpr.parent && containsTruthyCheck(reference, expr.left)) {
53844                             return nonPrimitiveType;
53845                         }
53846                     }
53847                     return getUnionType([nonPrimitiveType, nullType]);
53848                 }
53849                 var facts = assumeTrue ?
53850                     typeofEQFacts.get(literal.text) || 128 /* TypeofEQHostObject */ :
53851                     typeofNEFacts.get(literal.text) || 32768 /* TypeofNEHostObject */;
53852                 return getTypeWithFacts(assumeTrue ? mapType(type, narrowTypeForTypeof) : type, facts);
53853                 function narrowTypeForTypeof(type) {
53854                     // We narrow a non-union type to an exact primitive type if the non-union type
53855                     // is a supertype of that primitive type. For example, type 'any' can be narrowed
53856                     // to one of the primitive types.
53857                     var targetType = literal.text === "function" ? globalFunctionType : typeofTypesByName.get(literal.text);
53858                     if (targetType) {
53859                         if (isTypeSubtypeOf(type, targetType)) {
53860                             return type;
53861                         }
53862                         if (isTypeSubtypeOf(targetType, type)) {
53863                             return targetType;
53864                         }
53865                         if (type.flags & 63176704 /* Instantiable */) {
53866                             var constraint = getBaseConstraintOfType(type) || anyType;
53867                             if (isTypeSubtypeOf(targetType, constraint)) {
53868                                 return getIntersectionType([type, targetType]);
53869                             }
53870                         }
53871                     }
53872                     return type;
53873                 }
53874             }
53875             function narrowTypeBySwitchOptionalChainContainment(type, switchStatement, clauseStart, clauseEnd, clauseCheck) {
53876                 var everyClauseChecks = clauseStart !== clauseEnd && ts.every(getSwitchClauseTypes(switchStatement).slice(clauseStart, clauseEnd), clauseCheck);
53877                 return everyClauseChecks ? getTypeWithFacts(type, 2097152 /* NEUndefinedOrNull */) : type;
53878             }
53879             function narrowTypeBySwitchOnDiscriminant(type, switchStatement, clauseStart, clauseEnd) {
53880                 // We only narrow if all case expressions specify
53881                 // values with unit types, except for the case where
53882                 // `type` is unknown. In this instance we map object
53883                 // types to the nonPrimitive type and narrow with that.
53884                 var switchTypes = getSwitchClauseTypes(switchStatement);
53885                 if (!switchTypes.length) {
53886                     return type;
53887                 }
53888                 var clauseTypes = switchTypes.slice(clauseStart, clauseEnd);
53889                 var hasDefaultClause = clauseStart === clauseEnd || ts.contains(clauseTypes, neverType);
53890                 if ((type.flags & 2 /* Unknown */) && !hasDefaultClause) {
53891                     var groundClauseTypes = void 0;
53892                     for (var i = 0; i < clauseTypes.length; i += 1) {
53893                         var t = clauseTypes[i];
53894                         if (t.flags & (131068 /* Primitive */ | 67108864 /* NonPrimitive */)) {
53895                             if (groundClauseTypes !== undefined) {
53896                                 groundClauseTypes.push(t);
53897                             }
53898                         }
53899                         else if (t.flags & 524288 /* Object */) {
53900                             if (groundClauseTypes === undefined) {
53901                                 groundClauseTypes = clauseTypes.slice(0, i);
53902                             }
53903                             groundClauseTypes.push(nonPrimitiveType);
53904                         }
53905                         else {
53906                             return type;
53907                         }
53908                     }
53909                     return getUnionType(groundClauseTypes === undefined ? clauseTypes : groundClauseTypes);
53910                 }
53911                 var discriminantType = getUnionType(clauseTypes);
53912                 var caseType = discriminantType.flags & 131072 /* Never */ ? neverType :
53913                     replacePrimitivesWithLiterals(filterType(type, function (t) { return areTypesComparable(discriminantType, t); }), discriminantType);
53914                 if (!hasDefaultClause) {
53915                     return caseType;
53916                 }
53917                 var defaultType = filterType(type, function (t) { return !(isUnitType(t) && ts.contains(switchTypes, getRegularTypeOfLiteralType(t))); });
53918                 return caseType.flags & 131072 /* Never */ ? defaultType : getUnionType([caseType, defaultType]);
53919             }
53920             function getImpliedTypeFromTypeofCase(type, text) {
53921                 switch (text) {
53922                     case "function":
53923                         return type.flags & 1 /* Any */ ? type : globalFunctionType;
53924                     case "object":
53925                         return type.flags & 2 /* Unknown */ ? getUnionType([nonPrimitiveType, nullType]) : type;
53926                     default:
53927                         return typeofTypesByName.get(text) || type;
53928                 }
53929             }
53930             function narrowTypeForTypeofSwitch(candidate) {
53931                 return function (type) {
53932                     if (isTypeSubtypeOf(candidate, type)) {
53933                         return candidate;
53934                     }
53935                     if (type.flags & 63176704 /* Instantiable */) {
53936                         var constraint = getBaseConstraintOfType(type) || anyType;
53937                         if (isTypeSubtypeOf(candidate, constraint)) {
53938                             return getIntersectionType([type, candidate]);
53939                         }
53940                     }
53941                     return type;
53942                 };
53943             }
53944             function narrowBySwitchOnTypeOf(type, switchStatement, clauseStart, clauseEnd) {
53945                 var switchWitnesses = getSwitchClauseTypeOfWitnesses(switchStatement, /*retainDefault*/ true);
53946                 if (!switchWitnesses.length) {
53947                     return type;
53948                 }
53949                 //  Equal start and end denotes implicit fallthrough; undefined marks explicit default clause
53950                 var defaultCaseLocation = ts.findIndex(switchWitnesses, function (elem) { return elem === undefined; });
53951                 var hasDefaultClause = clauseStart === clauseEnd || (defaultCaseLocation >= clauseStart && defaultCaseLocation < clauseEnd);
53952                 var clauseWitnesses;
53953                 var switchFacts;
53954                 if (defaultCaseLocation > -1) {
53955                     // We no longer need the undefined denoting an
53956                     // explicit default case. Remove the undefined and
53957                     // fix-up clauseStart and clauseEnd.  This means
53958                     // that we don't have to worry about undefined
53959                     // in the witness array.
53960                     var witnesses = switchWitnesses.filter(function (witness) { return witness !== undefined; });
53961                     // The adjusted clause start and end after removing the `default` statement.
53962                     var fixedClauseStart = defaultCaseLocation < clauseStart ? clauseStart - 1 : clauseStart;
53963                     var fixedClauseEnd = defaultCaseLocation < clauseEnd ? clauseEnd - 1 : clauseEnd;
53964                     clauseWitnesses = witnesses.slice(fixedClauseStart, fixedClauseEnd);
53965                     switchFacts = getFactsFromTypeofSwitch(fixedClauseStart, fixedClauseEnd, witnesses, hasDefaultClause);
53966                 }
53967                 else {
53968                     clauseWitnesses = switchWitnesses.slice(clauseStart, clauseEnd);
53969                     switchFacts = getFactsFromTypeofSwitch(clauseStart, clauseEnd, switchWitnesses, hasDefaultClause);
53970                 }
53971                 if (hasDefaultClause) {
53972                     return filterType(type, function (t) { return (getTypeFacts(t) & switchFacts) === switchFacts; });
53973                 }
53974                 /*
53975                   The implied type is the raw type suggested by a
53976                   value being caught in this clause.
53977
53978                   When the clause contains a default case we ignore
53979                   the implied type and try to narrow using any facts
53980                   we can learn: see `switchFacts`.
53981
53982                   Example:
53983                   switch (typeof x) {
53984                       case 'number':
53985                       case 'string': break;
53986                       default: break;
53987                       case 'number':
53988                       case 'boolean': break
53989                   }
53990
53991                   In the first clause (case `number` and `string`) the
53992                   implied type is number | string.
53993
53994                   In the default clause we de not compute an implied type.
53995
53996                   In the third clause (case `number` and `boolean`)
53997                   the naive implied type is number | boolean, however
53998                   we use the type facts to narrow the implied type to
53999                   boolean. We know that number cannot be selected
54000                   because it is caught in the first clause.
54001                 */
54002                 var impliedType = getTypeWithFacts(getUnionType(clauseWitnesses.map(function (text) { return getImpliedTypeFromTypeofCase(type, text); })), switchFacts);
54003                 if (impliedType.flags & 1048576 /* Union */) {
54004                     impliedType = getAssignmentReducedType(impliedType, getBaseConstraintOrType(type));
54005                 }
54006                 return getTypeWithFacts(mapType(type, narrowTypeForTypeofSwitch(impliedType)), switchFacts);
54007             }
54008             function isMatchingConstructorReference(expr) {
54009                 return (ts.isPropertyAccessExpression(expr) && ts.idText(expr.name) === "constructor" ||
54010                     ts.isElementAccessExpression(expr) && ts.isStringLiteralLike(expr.argumentExpression) && expr.argumentExpression.text === "constructor") &&
54011                     isMatchingReference(reference, expr.expression);
54012             }
54013             function narrowTypeByConstructor(type, operator, identifier, assumeTrue) {
54014                 // Do not narrow when checking inequality.
54015                 if (assumeTrue ? (operator !== 34 /* EqualsEqualsToken */ && operator !== 36 /* EqualsEqualsEqualsToken */) : (operator !== 35 /* ExclamationEqualsToken */ && operator !== 37 /* ExclamationEqualsEqualsToken */)) {
54016                     return type;
54017                 }
54018                 // Get the type of the constructor identifier expression, if it is not a function then do not narrow.
54019                 var identifierType = getTypeOfExpression(identifier);
54020                 if (!isFunctionType(identifierType) && !isConstructorType(identifierType)) {
54021                     return type;
54022                 }
54023                 // Get the prototype property of the type identifier so we can find out its type.
54024                 var prototypeProperty = getPropertyOfType(identifierType, "prototype");
54025                 if (!prototypeProperty) {
54026                     return type;
54027                 }
54028                 // Get the type of the prototype, if it is undefined, or the global `Object` or `Function` types then do not narrow.
54029                 var prototypeType = getTypeOfSymbol(prototypeProperty);
54030                 var candidate = !isTypeAny(prototypeType) ? prototypeType : undefined;
54031                 if (!candidate || candidate === globalObjectType || candidate === globalFunctionType) {
54032                     return type;
54033                 }
54034                 // If the type that is being narrowed is `any` then just return the `candidate` type since every type is a subtype of `any`.
54035                 if (isTypeAny(type)) {
54036                     return candidate;
54037                 }
54038                 // Filter out types that are not considered to be "constructed by" the `candidate` type.
54039                 return filterType(type, function (t) { return isConstructedBy(t, candidate); });
54040                 function isConstructedBy(source, target) {
54041                     // If either the source or target type are a class type then we need to check that they are the same exact type.
54042                     // This is because you may have a class `A` that defines some set of properties, and another class `B`
54043                     // that defines the same set of properties as class `A`, in that case they are structurally the same
54044                     // type, but when you do something like `instanceOfA.constructor === B` it will return false.
54045                     if (source.flags & 524288 /* Object */ && ts.getObjectFlags(source) & 1 /* Class */ ||
54046                         target.flags & 524288 /* Object */ && ts.getObjectFlags(target) & 1 /* Class */) {
54047                         return source.symbol === target.symbol;
54048                     }
54049                     // For all other types just check that the `source` type is a subtype of the `target` type.
54050                     return isTypeSubtypeOf(source, target);
54051                 }
54052             }
54053             function narrowTypeByInstanceof(type, expr, assumeTrue) {
54054                 var left = getReferenceCandidate(expr.left);
54055                 if (!isMatchingReference(reference, left)) {
54056                     if (assumeTrue && strictNullChecks && optionalChainContainsReference(left, reference)) {
54057                         return getTypeWithFacts(type, 2097152 /* NEUndefinedOrNull */);
54058                     }
54059                     return type;
54060                 }
54061                 // Check that right operand is a function type with a prototype property
54062                 var rightType = getTypeOfExpression(expr.right);
54063                 if (!isTypeDerivedFrom(rightType, globalFunctionType)) {
54064                     return type;
54065                 }
54066                 var targetType;
54067                 var prototypeProperty = getPropertyOfType(rightType, "prototype");
54068                 if (prototypeProperty) {
54069                     // Target type is type of the prototype property
54070                     var prototypePropertyType = getTypeOfSymbol(prototypeProperty);
54071                     if (!isTypeAny(prototypePropertyType)) {
54072                         targetType = prototypePropertyType;
54073                     }
54074                 }
54075                 // Don't narrow from 'any' if the target type is exactly 'Object' or 'Function'
54076                 if (isTypeAny(type) && (targetType === globalObjectType || targetType === globalFunctionType)) {
54077                     return type;
54078                 }
54079                 if (!targetType) {
54080                     var constructSignatures = getSignaturesOfType(rightType, 1 /* Construct */);
54081                     targetType = constructSignatures.length ?
54082                         getUnionType(ts.map(constructSignatures, function (signature) { return getReturnTypeOfSignature(getErasedSignature(signature)); })) :
54083                         emptyObjectType;
54084                 }
54085                 return getNarrowedType(type, targetType, assumeTrue, isTypeDerivedFrom);
54086             }
54087             function getNarrowedType(type, candidate, assumeTrue, isRelated) {
54088                 if (!assumeTrue) {
54089                     return filterType(type, function (t) { return !isRelated(t, candidate); });
54090                 }
54091                 // If the current type is a union type, remove all constituents that couldn't be instances of
54092                 // the candidate type. If one or more constituents remain, return a union of those.
54093                 if (type.flags & 1048576 /* Union */) {
54094                     var assignableType = filterType(type, function (t) { return isRelated(t, candidate); });
54095                     if (!(assignableType.flags & 131072 /* Never */)) {
54096                         return assignableType;
54097                     }
54098                 }
54099                 // If the candidate type is a subtype of the target type, narrow to the candidate type.
54100                 // Otherwise, if the target type is assignable to the candidate type, keep the target type.
54101                 // Otherwise, if the candidate type is assignable to the target type, narrow to the candidate
54102                 // type. Otherwise, the types are completely unrelated, so narrow to an intersection of the
54103                 // two types.
54104                 return isTypeSubtypeOf(candidate, type) ? candidate :
54105                     isTypeAssignableTo(type, candidate) ? type :
54106                         isTypeAssignableTo(candidate, type) ? candidate :
54107                             getIntersectionType([type, candidate]);
54108             }
54109             function narrowTypeByCallExpression(type, callExpression, assumeTrue) {
54110                 if (hasMatchingArgument(callExpression, reference)) {
54111                     var signature = assumeTrue || !ts.isCallChain(callExpression) ? getEffectsSignature(callExpression) : undefined;
54112                     var predicate = signature && getTypePredicateOfSignature(signature);
54113                     if (predicate && (predicate.kind === 0 /* This */ || predicate.kind === 1 /* Identifier */)) {
54114                         return narrowTypeByTypePredicate(type, predicate, callExpression, assumeTrue);
54115                     }
54116                 }
54117                 return type;
54118             }
54119             function narrowTypeByTypePredicate(type, predicate, callExpression, assumeTrue) {
54120                 // Don't narrow from 'any' if the predicate type is exactly 'Object' or 'Function'
54121                 if (predicate.type && !(isTypeAny(type) && (predicate.type === globalObjectType || predicate.type === globalFunctionType))) {
54122                     var predicateArgument = getTypePredicateArgument(predicate, callExpression);
54123                     if (predicateArgument) {
54124                         if (isMatchingReference(reference, predicateArgument)) {
54125                             return getNarrowedType(type, predicate.type, assumeTrue, isTypeSubtypeOf);
54126                         }
54127                         if (strictNullChecks && assumeTrue && optionalChainContainsReference(predicateArgument, reference) &&
54128                             !(getTypeFacts(predicate.type) & 65536 /* EQUndefined */)) {
54129                             type = getTypeWithFacts(type, 2097152 /* NEUndefinedOrNull */);
54130                         }
54131                         if (isMatchingReferenceDiscriminant(predicateArgument, declaredType)) {
54132                             return narrowTypeByDiscriminant(type, predicateArgument, function (t) { return getNarrowedType(t, predicate.type, assumeTrue, isTypeSubtypeOf); });
54133                         }
54134                     }
54135                 }
54136                 return type;
54137             }
54138             // Narrow the given type based on the given expression having the assumed boolean value. The returned type
54139             // will be a subtype or the same type as the argument.
54140             function narrowType(type, expr, assumeTrue) {
54141                 // for `a?.b`, we emulate a synthetic `a !== null && a !== undefined` condition for `a`
54142                 if (ts.isExpressionOfOptionalChainRoot(expr) ||
54143                     ts.isBinaryExpression(expr.parent) && expr.parent.operatorToken.kind === 60 /* QuestionQuestionToken */ && expr.parent.left === expr) {
54144                     return narrowTypeByOptionality(type, expr, assumeTrue);
54145                 }
54146                 switch (expr.kind) {
54147                     case 75 /* Identifier */:
54148                     case 104 /* ThisKeyword */:
54149                     case 102 /* SuperKeyword */:
54150                     case 194 /* PropertyAccessExpression */:
54151                     case 195 /* ElementAccessExpression */:
54152                         return narrowTypeByTruthiness(type, expr, assumeTrue);
54153                     case 196 /* CallExpression */:
54154                         return narrowTypeByCallExpression(type, expr, assumeTrue);
54155                     case 200 /* ParenthesizedExpression */:
54156                         return narrowType(type, expr.expression, assumeTrue);
54157                     case 209 /* BinaryExpression */:
54158                         return narrowTypeByBinaryExpression(type, expr, assumeTrue);
54159                     case 207 /* PrefixUnaryExpression */:
54160                         if (expr.operator === 53 /* ExclamationToken */) {
54161                             return narrowType(type, expr.operand, !assumeTrue);
54162                         }
54163                         break;
54164                 }
54165                 return type;
54166             }
54167             function narrowTypeByOptionality(type, expr, assumePresent) {
54168                 if (isMatchingReference(reference, expr)) {
54169                     return getTypeWithFacts(type, assumePresent ? 2097152 /* NEUndefinedOrNull */ : 262144 /* EQUndefinedOrNull */);
54170                 }
54171                 if (isMatchingReferenceDiscriminant(expr, declaredType)) {
54172                     return narrowTypeByDiscriminant(type, expr, function (t) { return getTypeWithFacts(t, assumePresent ? 2097152 /* NEUndefinedOrNull */ : 262144 /* EQUndefinedOrNull */); });
54173                 }
54174                 return type;
54175             }
54176         }
54177         function getTypeOfSymbolAtLocation(symbol, location) {
54178             symbol = symbol.exportSymbol || symbol;
54179             // If we have an identifier or a property access at the given location, if the location is
54180             // an dotted name expression, and if the location is not an assignment target, obtain the type
54181             // of the expression (which will reflect control flow analysis). If the expression indeed
54182             // resolved to the given symbol, return the narrowed type.
54183             if (location.kind === 75 /* Identifier */) {
54184                 if (ts.isRightSideOfQualifiedNameOrPropertyAccess(location)) {
54185                     location = location.parent;
54186                 }
54187                 if (ts.isExpressionNode(location) && !ts.isAssignmentTarget(location)) {
54188                     var type = getTypeOfExpression(location);
54189                     if (getExportSymbolOfValueSymbolIfExported(getNodeLinks(location).resolvedSymbol) === symbol) {
54190                         return type;
54191                     }
54192                 }
54193             }
54194             // The location isn't a reference to the given symbol, meaning we're being asked
54195             // a hypothetical question of what type the symbol would have if there was a reference
54196             // to it at the given location. Since we have no control flow information for the
54197             // hypothetical reference (control flow information is created and attached by the
54198             // binder), we simply return the declared type of the symbol.
54199             return getTypeOfSymbol(symbol);
54200         }
54201         function getControlFlowContainer(node) {
54202             return ts.findAncestor(node.parent, function (node) {
54203                 return ts.isFunctionLike(node) && !ts.getImmediatelyInvokedFunctionExpression(node) ||
54204                     node.kind === 250 /* ModuleBlock */ ||
54205                     node.kind === 290 /* SourceFile */ ||
54206                     node.kind === 159 /* PropertyDeclaration */;
54207             });
54208         }
54209         // Check if a parameter is assigned anywhere within its declaring function.
54210         function isParameterAssigned(symbol) {
54211             var func = ts.getRootDeclaration(symbol.valueDeclaration).parent;
54212             var links = getNodeLinks(func);
54213             if (!(links.flags & 8388608 /* AssignmentsMarked */)) {
54214                 links.flags |= 8388608 /* AssignmentsMarked */;
54215                 if (!hasParentWithAssignmentsMarked(func)) {
54216                     markParameterAssignments(func);
54217                 }
54218             }
54219             return symbol.isAssigned || false;
54220         }
54221         function hasParentWithAssignmentsMarked(node) {
54222             return !!ts.findAncestor(node.parent, function (node) { return ts.isFunctionLike(node) && !!(getNodeLinks(node).flags & 8388608 /* AssignmentsMarked */); });
54223         }
54224         function markParameterAssignments(node) {
54225             if (node.kind === 75 /* Identifier */) {
54226                 if (ts.isAssignmentTarget(node)) {
54227                     var symbol = getResolvedSymbol(node);
54228                     if (symbol.valueDeclaration && ts.getRootDeclaration(symbol.valueDeclaration).kind === 156 /* Parameter */) {
54229                         symbol.isAssigned = true;
54230                     }
54231                 }
54232             }
54233             else {
54234                 ts.forEachChild(node, markParameterAssignments);
54235             }
54236         }
54237         function isConstVariable(symbol) {
54238             return symbol.flags & 3 /* Variable */ && (getDeclarationNodeFlagsFromSymbol(symbol) & 2 /* Const */) !== 0 && getTypeOfSymbol(symbol) !== autoArrayType;
54239         }
54240         /** remove undefined from the annotated type of a parameter when there is an initializer (that doesn't include undefined) */
54241         function removeOptionalityFromDeclaredType(declaredType, declaration) {
54242             if (pushTypeResolution(declaration.symbol, 2 /* DeclaredType */)) {
54243                 var annotationIncludesUndefined = strictNullChecks &&
54244                     declaration.kind === 156 /* Parameter */ &&
54245                     declaration.initializer &&
54246                     getFalsyFlags(declaredType) & 32768 /* Undefined */ &&
54247                     !(getFalsyFlags(checkExpression(declaration.initializer)) & 32768 /* Undefined */);
54248                 popTypeResolution();
54249                 return annotationIncludesUndefined ? getTypeWithFacts(declaredType, 524288 /* NEUndefined */) : declaredType;
54250             }
54251             else {
54252                 reportCircularityError(declaration.symbol);
54253                 return declaredType;
54254             }
54255         }
54256         function isConstraintPosition(node) {
54257             var parent = node.parent;
54258             return parent.kind === 194 /* PropertyAccessExpression */ ||
54259                 parent.kind === 196 /* CallExpression */ && parent.expression === node ||
54260                 parent.kind === 195 /* ElementAccessExpression */ && parent.expression === node ||
54261                 parent.kind === 191 /* BindingElement */ && parent.name === node && !!parent.initializer;
54262         }
54263         function typeHasNullableConstraint(type) {
54264             return type.flags & 58982400 /* InstantiableNonPrimitive */ && maybeTypeOfKind(getBaseConstraintOfType(type) || unknownType, 98304 /* Nullable */);
54265         }
54266         function getConstraintForLocation(type, node) {
54267             // When a node is the left hand expression of a property access, element access, or call expression,
54268             // and the type of the node includes type variables with constraints that are nullable, we fetch the
54269             // apparent type of the node *before* performing control flow analysis such that narrowings apply to
54270             // the constraint type.
54271             if (type && isConstraintPosition(node) && forEachType(type, typeHasNullableConstraint)) {
54272                 return mapType(getWidenedType(type), getBaseConstraintOrType);
54273             }
54274             return type;
54275         }
54276         function isExportOrExportExpression(location) {
54277             return !!ts.findAncestor(location, function (e) { return e.parent && ts.isExportAssignment(e.parent) && e.parent.expression === e && ts.isEntityNameExpression(e); });
54278         }
54279         function markAliasReferenced(symbol, location) {
54280             if (isNonLocalAlias(symbol, /*excludes*/ 111551 /* Value */) && !isInTypeQuery(location) && !getTypeOnlyAliasDeclaration(symbol)) {
54281                 if (compilerOptions.preserveConstEnums && isExportOrExportExpression(location) || !isConstEnumOrConstEnumOnlyModule(resolveAlias(symbol))) {
54282                     markAliasSymbolAsReferenced(symbol);
54283                 }
54284                 else {
54285                     markConstEnumAliasAsReferenced(symbol);
54286                 }
54287             }
54288         }
54289         function checkIdentifier(node) {
54290             var symbol = getResolvedSymbol(node);
54291             if (symbol === unknownSymbol) {
54292                 return errorType;
54293             }
54294             // As noted in ECMAScript 6 language spec, arrow functions never have an arguments objects.
54295             // Although in down-level emit of arrow function, we emit it using function expression which means that
54296             // arguments objects will be bound to the inner object; emitting arrow function natively in ES6, arguments objects
54297             // will be bound to non-arrow function that contain this arrow function. This results in inconsistent behavior.
54298             // To avoid that we will give an error to users if they use arguments objects in arrow function so that they
54299             // can explicitly bound arguments objects
54300             if (symbol === argumentsSymbol) {
54301                 var container = ts.getContainingFunction(node);
54302                 if (languageVersion < 2 /* ES2015 */) {
54303                     if (container.kind === 202 /* ArrowFunction */) {
54304                         error(node, ts.Diagnostics.The_arguments_object_cannot_be_referenced_in_an_arrow_function_in_ES3_and_ES5_Consider_using_a_standard_function_expression);
54305                     }
54306                     else if (ts.hasModifier(container, 256 /* Async */)) {
54307                         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);
54308                     }
54309                 }
54310                 getNodeLinks(container).flags |= 8192 /* CaptureArguments */;
54311                 return getTypeOfSymbol(symbol);
54312             }
54313             // We should only mark aliases as referenced if there isn't a local value declaration
54314             // for the symbol. Also, don't mark any property access expression LHS - checkPropertyAccessExpression will handle that
54315             if (!(node.parent && ts.isPropertyAccessExpression(node.parent) && node.parent.expression === node)) {
54316                 markAliasReferenced(symbol, node);
54317             }
54318             var localOrExportSymbol = getExportSymbolOfValueSymbolIfExported(symbol);
54319             var declaration = localOrExportSymbol.valueDeclaration;
54320             if (localOrExportSymbol.flags & 32 /* Class */) {
54321                 // Due to the emit for class decorators, any reference to the class from inside of the class body
54322                 // must instead be rewritten to point to a temporary variable to avoid issues with the double-bind
54323                 // behavior of class names in ES6.
54324                 if (declaration.kind === 245 /* ClassDeclaration */
54325                     && ts.nodeIsDecorated(declaration)) {
54326                     var container = ts.getContainingClass(node);
54327                     while (container !== undefined) {
54328                         if (container === declaration && container.name !== node) {
54329                             getNodeLinks(declaration).flags |= 16777216 /* ClassWithConstructorReference */;
54330                             getNodeLinks(node).flags |= 33554432 /* ConstructorReferenceInClass */;
54331                             break;
54332                         }
54333                         container = ts.getContainingClass(container);
54334                     }
54335                 }
54336                 else if (declaration.kind === 214 /* ClassExpression */) {
54337                     // When we emit a class expression with static members that contain a reference
54338                     // to the constructor in the initializer, we will need to substitute that
54339                     // binding with an alias as the class name is not in scope.
54340                     var container = ts.getThisContainer(node, /*includeArrowFunctions*/ false);
54341                     while (container.kind !== 290 /* SourceFile */) {
54342                         if (container.parent === declaration) {
54343                             if (container.kind === 159 /* PropertyDeclaration */ && ts.hasModifier(container, 32 /* Static */)) {
54344                                 getNodeLinks(declaration).flags |= 16777216 /* ClassWithConstructorReference */;
54345                                 getNodeLinks(node).flags |= 33554432 /* ConstructorReferenceInClass */;
54346                             }
54347                             break;
54348                         }
54349                         container = ts.getThisContainer(container, /*includeArrowFunctions*/ false);
54350                     }
54351                 }
54352             }
54353             checkNestedBlockScopedBinding(node, symbol);
54354             var type = getConstraintForLocation(getTypeOfSymbol(localOrExportSymbol), node);
54355             var assignmentKind = ts.getAssignmentTargetKind(node);
54356             if (assignmentKind) {
54357                 if (!(localOrExportSymbol.flags & 3 /* Variable */) &&
54358                     !(ts.isInJSFile(node) && localOrExportSymbol.flags & 512 /* ValueModule */)) {
54359                     error(node, ts.Diagnostics.Cannot_assign_to_0_because_it_is_not_a_variable, symbolToString(symbol));
54360                     return errorType;
54361                 }
54362                 if (isReadonlySymbol(localOrExportSymbol)) {
54363                     if (localOrExportSymbol.flags & 3 /* Variable */) {
54364                         error(node, ts.Diagnostics.Cannot_assign_to_0_because_it_is_a_constant, symbolToString(symbol));
54365                     }
54366                     else {
54367                         error(node, ts.Diagnostics.Cannot_assign_to_0_because_it_is_a_read_only_property, symbolToString(symbol));
54368                     }
54369                     return errorType;
54370                 }
54371             }
54372             var isAlias = localOrExportSymbol.flags & 2097152 /* Alias */;
54373             // We only narrow variables and parameters occurring in a non-assignment position. For all other
54374             // entities we simply return the declared type.
54375             if (localOrExportSymbol.flags & 3 /* Variable */) {
54376                 if (assignmentKind === 1 /* Definite */) {
54377                     return type;
54378                 }
54379             }
54380             else if (isAlias) {
54381                 declaration = ts.find(symbol.declarations, isSomeImportDeclaration);
54382             }
54383             else {
54384                 return type;
54385             }
54386             if (!declaration) {
54387                 return type;
54388             }
54389             // The declaration container is the innermost function that encloses the declaration of the variable
54390             // or parameter. The flow container is the innermost function starting with which we analyze the control
54391             // flow graph to determine the control flow based type.
54392             var isParameter = ts.getRootDeclaration(declaration).kind === 156 /* Parameter */;
54393             var declarationContainer = getControlFlowContainer(declaration);
54394             var flowContainer = getControlFlowContainer(node);
54395             var isOuterVariable = flowContainer !== declarationContainer;
54396             var isSpreadDestructuringAssignmentTarget = node.parent && node.parent.parent && ts.isSpreadAssignment(node.parent) && isDestructuringAssignmentTarget(node.parent.parent);
54397             var isModuleExports = symbol.flags & 134217728 /* ModuleExports */;
54398             // When the control flow originates in a function expression or arrow function and we are referencing
54399             // a const variable or parameter from an outer function, we extend the origin of the control flow
54400             // analysis to include the immediately enclosing function.
54401             while (flowContainer !== declarationContainer && (flowContainer.kind === 201 /* FunctionExpression */ ||
54402                 flowContainer.kind === 202 /* ArrowFunction */ || ts.isObjectLiteralOrClassExpressionMethod(flowContainer)) &&
54403                 (isConstVariable(localOrExportSymbol) || isParameter && !isParameterAssigned(localOrExportSymbol))) {
54404                 flowContainer = getControlFlowContainer(flowContainer);
54405             }
54406             // We only look for uninitialized variables in strict null checking mode, and only when we can analyze
54407             // the entire control flow graph from the variable's declaration (i.e. when the flow container and
54408             // declaration container are the same).
54409             var assumeInitialized = isParameter || isAlias || isOuterVariable || isSpreadDestructuringAssignmentTarget || isModuleExports || ts.isBindingElement(declaration) ||
54410                 type !== autoType && type !== autoArrayType && (!strictNullChecks || (type.flags & (3 /* AnyOrUnknown */ | 16384 /* Void */)) !== 0 ||
54411                     isInTypeQuery(node) || node.parent.kind === 263 /* ExportSpecifier */) ||
54412                 node.parent.kind === 218 /* NonNullExpression */ ||
54413                 declaration.kind === 242 /* VariableDeclaration */ && declaration.exclamationToken ||
54414                 declaration.flags & 8388608 /* Ambient */;
54415             var initialType = assumeInitialized ? (isParameter ? removeOptionalityFromDeclaredType(type, declaration) : type) :
54416                 type === autoType || type === autoArrayType ? undefinedType :
54417                     getOptionalType(type);
54418             var flowType = getFlowTypeOfReference(node, type, initialType, flowContainer, !assumeInitialized);
54419             // A variable is considered uninitialized when it is possible to analyze the entire control flow graph
54420             // from declaration to use, and when the variable's declared type doesn't include undefined but the
54421             // control flow based type does include undefined.
54422             if (!isEvolvingArrayOperationTarget(node) && (type === autoType || type === autoArrayType)) {
54423                 if (flowType === autoType || flowType === autoArrayType) {
54424                     if (noImplicitAny) {
54425                         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));
54426                         error(node, ts.Diagnostics.Variable_0_implicitly_has_an_1_type, symbolToString(symbol), typeToString(flowType));
54427                     }
54428                     return convertAutoToAny(flowType);
54429                 }
54430             }
54431             else if (!assumeInitialized && !(getFalsyFlags(type) & 32768 /* Undefined */) && getFalsyFlags(flowType) & 32768 /* Undefined */) {
54432                 error(node, ts.Diagnostics.Variable_0_is_used_before_being_assigned, symbolToString(symbol));
54433                 // Return the declared type to reduce follow-on errors
54434                 return type;
54435             }
54436             return assignmentKind ? getBaseTypeOfLiteralType(flowType) : flowType;
54437         }
54438         function isInsideFunction(node, threshold) {
54439             return !!ts.findAncestor(node, function (n) { return n === threshold ? "quit" : ts.isFunctionLike(n); });
54440         }
54441         function getPartOfForStatementContainingNode(node, container) {
54442             return ts.findAncestor(node, function (n) { return n === container ? "quit" : n === container.initializer || n === container.condition || n === container.incrementor || n === container.statement; });
54443         }
54444         function checkNestedBlockScopedBinding(node, symbol) {
54445             if (languageVersion >= 2 /* ES2015 */ ||
54446                 (symbol.flags & (2 /* BlockScopedVariable */ | 32 /* Class */)) === 0 ||
54447                 ts.isSourceFile(symbol.valueDeclaration) ||
54448                 symbol.valueDeclaration.parent.kind === 280 /* CatchClause */) {
54449                 return;
54450             }
54451             // 1. walk from the use site up to the declaration and check
54452             // if there is anything function like between declaration and use-site (is binding/class is captured in function).
54453             // 2. walk from the declaration up to the boundary of lexical environment and check
54454             // if there is an iteration statement in between declaration and boundary (is binding/class declared inside iteration statement)
54455             var container = ts.getEnclosingBlockScopeContainer(symbol.valueDeclaration);
54456             var usedInFunction = isInsideFunction(node.parent, container);
54457             var current = container;
54458             var containedInIterationStatement = false;
54459             while (current && !ts.nodeStartsNewLexicalEnvironment(current)) {
54460                 if (ts.isIterationStatement(current, /*lookInLabeledStatements*/ false)) {
54461                     containedInIterationStatement = true;
54462                     break;
54463                 }
54464                 current = current.parent;
54465             }
54466             if (containedInIterationStatement) {
54467                 if (usedInFunction) {
54468                     // mark iteration statement as containing block-scoped binding captured in some function
54469                     var capturesBlockScopeBindingInLoopBody = true;
54470                     if (ts.isForStatement(container)) {
54471                         var varDeclList = ts.getAncestor(symbol.valueDeclaration, 243 /* VariableDeclarationList */);
54472                         if (varDeclList && varDeclList.parent === container) {
54473                             var part = getPartOfForStatementContainingNode(node.parent, container);
54474                             if (part) {
54475                                 var links = getNodeLinks(part);
54476                                 links.flags |= 131072 /* ContainsCapturedBlockScopeBinding */;
54477                                 var capturedBindings = links.capturedBlockScopeBindings || (links.capturedBlockScopeBindings = []);
54478                                 ts.pushIfUnique(capturedBindings, symbol);
54479                                 if (part === container.initializer) {
54480                                     capturesBlockScopeBindingInLoopBody = false; // Initializer is outside of loop body
54481                                 }
54482                             }
54483                         }
54484                     }
54485                     if (capturesBlockScopeBindingInLoopBody) {
54486                         getNodeLinks(current).flags |= 65536 /* LoopWithCapturedBlockScopedBinding */;
54487                     }
54488                 }
54489                 // mark variables that are declared in loop initializer and reassigned inside the body of ForStatement.
54490                 // if body of ForStatement will be converted to function then we'll need a extra machinery to propagate reassigned values back.
54491                 if (ts.isForStatement(container)) {
54492                     var varDeclList = ts.getAncestor(symbol.valueDeclaration, 243 /* VariableDeclarationList */);
54493                     if (varDeclList && varDeclList.parent === container && isAssignedInBodyOfForStatement(node, container)) {
54494                         getNodeLinks(symbol.valueDeclaration).flags |= 4194304 /* NeedsLoopOutParameter */;
54495                     }
54496                 }
54497                 // set 'declared inside loop' bit on the block-scoped binding
54498                 getNodeLinks(symbol.valueDeclaration).flags |= 524288 /* BlockScopedBindingInLoop */;
54499             }
54500             if (usedInFunction) {
54501                 getNodeLinks(symbol.valueDeclaration).flags |= 262144 /* CapturedBlockScopedBinding */;
54502             }
54503         }
54504         function isBindingCapturedByNode(node, decl) {
54505             var links = getNodeLinks(node);
54506             return !!links && ts.contains(links.capturedBlockScopeBindings, getSymbolOfNode(decl));
54507         }
54508         function isAssignedInBodyOfForStatement(node, container) {
54509             // skip parenthesized nodes
54510             var current = node;
54511             while (current.parent.kind === 200 /* ParenthesizedExpression */) {
54512                 current = current.parent;
54513             }
54514             // check if node is used as LHS in some assignment expression
54515             var isAssigned = false;
54516             if (ts.isAssignmentTarget(current)) {
54517                 isAssigned = true;
54518             }
54519             else if ((current.parent.kind === 207 /* PrefixUnaryExpression */ || current.parent.kind === 208 /* PostfixUnaryExpression */)) {
54520                 var expr = current.parent;
54521                 isAssigned = expr.operator === 45 /* PlusPlusToken */ || expr.operator === 46 /* MinusMinusToken */;
54522             }
54523             if (!isAssigned) {
54524                 return false;
54525             }
54526             // at this point we know that node is the target of assignment
54527             // now check that modification happens inside the statement part of the ForStatement
54528             return !!ts.findAncestor(current, function (n) { return n === container ? "quit" : n === container.statement; });
54529         }
54530         function captureLexicalThis(node, container) {
54531             getNodeLinks(node).flags |= 2 /* LexicalThis */;
54532             if (container.kind === 159 /* PropertyDeclaration */ || container.kind === 162 /* Constructor */) {
54533                 var classNode = container.parent;
54534                 getNodeLinks(classNode).flags |= 4 /* CaptureThis */;
54535             }
54536             else {
54537                 getNodeLinks(container).flags |= 4 /* CaptureThis */;
54538             }
54539         }
54540         function findFirstSuperCall(n) {
54541             if (ts.isSuperCall(n)) {
54542                 return n;
54543             }
54544             else if (ts.isFunctionLike(n)) {
54545                 return undefined;
54546             }
54547             return ts.forEachChild(n, findFirstSuperCall);
54548         }
54549         /**
54550          * Return a cached result if super-statement is already found.
54551          * Otherwise, find a super statement in a given constructor function and cache the result in the node-links of the constructor
54552          *
54553          * @param constructor constructor-function to look for super statement
54554          */
54555         function getSuperCallInConstructor(constructor) {
54556             var links = getNodeLinks(constructor);
54557             // Only trying to find super-call if we haven't yet tried to find one.  Once we try, we will record the result
54558             if (links.hasSuperCall === undefined) {
54559                 links.superCall = findFirstSuperCall(constructor.body);
54560                 links.hasSuperCall = links.superCall ? true : false;
54561             }
54562             return links.superCall;
54563         }
54564         /**
54565          * Check if the given class-declaration extends null then return true.
54566          * Otherwise, return false
54567          * @param classDecl a class declaration to check if it extends null
54568          */
54569         function classDeclarationExtendsNull(classDecl) {
54570             var classSymbol = getSymbolOfNode(classDecl);
54571             var classInstanceType = getDeclaredTypeOfSymbol(classSymbol);
54572             var baseConstructorType = getBaseConstructorTypeOfClass(classInstanceType);
54573             return baseConstructorType === nullWideningType;
54574         }
54575         function checkThisBeforeSuper(node, container, diagnosticMessage) {
54576             var containingClassDecl = container.parent;
54577             var baseTypeNode = ts.getClassExtendsHeritageElement(containingClassDecl);
54578             // If a containing class does not have extends clause or the class extends null
54579             // skip checking whether super statement is called before "this" accessing.
54580             if (baseTypeNode && !classDeclarationExtendsNull(containingClassDecl)) {
54581                 var superCall = getSuperCallInConstructor(container);
54582                 // We should give an error in the following cases:
54583                 //      - No super-call
54584                 //      - "this" is accessing before super-call.
54585                 //          i.e super(this)
54586                 //              this.x; super();
54587                 // We want to make sure that super-call is done before accessing "this" so that
54588                 // "this" is not accessed as a parameter of the super-call.
54589                 if (!superCall || superCall.end > node.pos) {
54590                     // In ES6, super inside constructor of class-declaration has to precede "this" accessing
54591                     error(node, diagnosticMessage);
54592                 }
54593             }
54594         }
54595         function checkThisExpression(node) {
54596             // Stop at the first arrow function so that we can
54597             // tell whether 'this' needs to be captured.
54598             var container = ts.getThisContainer(node, /* includeArrowFunctions */ true);
54599             var capturedByArrowFunction = false;
54600             if (container.kind === 162 /* Constructor */) {
54601                 checkThisBeforeSuper(node, container, ts.Diagnostics.super_must_be_called_before_accessing_this_in_the_constructor_of_a_derived_class);
54602             }
54603             // Now skip arrow functions to get the "real" owner of 'this'.
54604             if (container.kind === 202 /* ArrowFunction */) {
54605                 container = ts.getThisContainer(container, /* includeArrowFunctions */ false);
54606                 capturedByArrowFunction = true;
54607             }
54608             switch (container.kind) {
54609                 case 249 /* ModuleDeclaration */:
54610                     error(node, ts.Diagnostics.this_cannot_be_referenced_in_a_module_or_namespace_body);
54611                     // do not return here so in case if lexical this is captured - it will be reflected in flags on NodeLinks
54612                     break;
54613                 case 248 /* EnumDeclaration */:
54614                     error(node, ts.Diagnostics.this_cannot_be_referenced_in_current_location);
54615                     // do not return here so in case if lexical this is captured - it will be reflected in flags on NodeLinks
54616                     break;
54617                 case 162 /* Constructor */:
54618                     if (isInConstructorArgumentInitializer(node, container)) {
54619                         error(node, ts.Diagnostics.this_cannot_be_referenced_in_constructor_arguments);
54620                         // do not return here so in case if lexical this is captured - it will be reflected in flags on NodeLinks
54621                     }
54622                     break;
54623                 case 159 /* PropertyDeclaration */:
54624                 case 158 /* PropertySignature */:
54625                     if (ts.hasModifier(container, 32 /* Static */) && !(compilerOptions.target === 99 /* ESNext */ && compilerOptions.useDefineForClassFields)) {
54626                         error(node, ts.Diagnostics.this_cannot_be_referenced_in_a_static_property_initializer);
54627                         // do not return here so in case if lexical this is captured - it will be reflected in flags on NodeLinks
54628                     }
54629                     break;
54630                 case 154 /* ComputedPropertyName */:
54631                     error(node, ts.Diagnostics.this_cannot_be_referenced_in_a_computed_property_name);
54632                     break;
54633             }
54634             // When targeting es6, mark that we'll need to capture `this` in its lexically bound scope.
54635             if (capturedByArrowFunction && languageVersion < 2 /* ES2015 */) {
54636                 captureLexicalThis(node, container);
54637             }
54638             var type = tryGetThisTypeAt(node, /*includeGlobalThis*/ true, container);
54639             if (noImplicitThis) {
54640                 var globalThisType_1 = getTypeOfSymbol(globalThisSymbol);
54641                 if (type === globalThisType_1 && capturedByArrowFunction) {
54642                     error(node, ts.Diagnostics.The_containing_arrow_function_captures_the_global_value_of_this);
54643                 }
54644                 else if (!type) {
54645                     // With noImplicitThis, functions may not reference 'this' if it has type 'any'
54646                     var diag = error(node, ts.Diagnostics.this_implicitly_has_type_any_because_it_does_not_have_a_type_annotation);
54647                     if (!ts.isSourceFile(container)) {
54648                         var outsideThis = tryGetThisTypeAt(container);
54649                         if (outsideThis && outsideThis !== globalThisType_1) {
54650                             ts.addRelatedInfo(diag, ts.createDiagnosticForNode(container, ts.Diagnostics.An_outer_value_of_this_is_shadowed_by_this_container));
54651                         }
54652                     }
54653                 }
54654             }
54655             return type || anyType;
54656         }
54657         function tryGetThisTypeAt(node, includeGlobalThis, container) {
54658             if (includeGlobalThis === void 0) { includeGlobalThis = true; }
54659             if (container === void 0) { container = ts.getThisContainer(node, /*includeArrowFunctions*/ false); }
54660             var isInJS = ts.isInJSFile(node);
54661             if (ts.isFunctionLike(container) &&
54662                 (!isInParameterInitializerBeforeContainingFunction(node) || ts.getThisParameter(container))) {
54663                 // Note: a parameter initializer should refer to class-this unless function-this is explicitly annotated.
54664                 // If this is a function in a JS file, it might be a class method.
54665                 var className = getClassNameFromPrototypeMethod(container);
54666                 if (isInJS && className) {
54667                     var classSymbol = checkExpression(className).symbol;
54668                     if (classSymbol && classSymbol.members && (classSymbol.flags & 16 /* Function */)) {
54669                         var classType = getDeclaredTypeOfSymbol(classSymbol).thisType;
54670                         if (classType) {
54671                             return getFlowTypeOfReference(node, classType);
54672                         }
54673                     }
54674                 }
54675                 // Check if it's a constructor definition, can be either a variable decl or function decl
54676                 // i.e.
54677                 //   * /** @constructor */ function [name]() { ... }
54678                 //   * /** @constructor */ var x = function() { ... }
54679                 else if (isInJS &&
54680                     (container.kind === 201 /* FunctionExpression */ || container.kind === 244 /* FunctionDeclaration */) &&
54681                     ts.getJSDocClassTag(container)) {
54682                     var classType = getDeclaredTypeOfSymbol(getMergedSymbol(container.symbol)).thisType;
54683                     return getFlowTypeOfReference(node, classType);
54684                 }
54685                 var thisType = getThisTypeOfDeclaration(container) || getContextualThisParameterType(container);
54686                 if (thisType) {
54687                     return getFlowTypeOfReference(node, thisType);
54688                 }
54689             }
54690             if (ts.isClassLike(container.parent)) {
54691                 var symbol = getSymbolOfNode(container.parent);
54692                 var type = ts.hasModifier(container, 32 /* Static */) ? getTypeOfSymbol(symbol) : getDeclaredTypeOfSymbol(symbol).thisType;
54693                 return getFlowTypeOfReference(node, type);
54694             }
54695             if (isInJS) {
54696                 var type = getTypeForThisExpressionFromJSDoc(container);
54697                 if (type && type !== errorType) {
54698                     return getFlowTypeOfReference(node, type);
54699                 }
54700             }
54701             if (ts.isSourceFile(container)) {
54702                 // look up in the source file's locals or exports
54703                 if (container.commonJsModuleIndicator) {
54704                     var fileSymbol = getSymbolOfNode(container);
54705                     return fileSymbol && getTypeOfSymbol(fileSymbol);
54706                 }
54707                 else if (includeGlobalThis) {
54708                     return getTypeOfSymbol(globalThisSymbol);
54709                 }
54710             }
54711         }
54712         function getExplicitThisType(node) {
54713             var container = ts.getThisContainer(node, /*includeArrowFunctions*/ false);
54714             if (ts.isFunctionLike(container)) {
54715                 var signature = getSignatureFromDeclaration(container);
54716                 if (signature.thisParameter) {
54717                     return getExplicitTypeOfSymbol(signature.thisParameter);
54718                 }
54719             }
54720             if (ts.isClassLike(container.parent)) {
54721                 var symbol = getSymbolOfNode(container.parent);
54722                 return ts.hasModifier(container, 32 /* Static */) ? getTypeOfSymbol(symbol) : getDeclaredTypeOfSymbol(symbol).thisType;
54723             }
54724         }
54725         function getClassNameFromPrototypeMethod(container) {
54726             // Check if it's the RHS of a x.prototype.y = function [name]() { .... }
54727             if (container.kind === 201 /* FunctionExpression */ &&
54728                 ts.isBinaryExpression(container.parent) &&
54729                 ts.getAssignmentDeclarationKind(container.parent) === 3 /* PrototypeProperty */) {
54730                 // Get the 'x' of 'x.prototype.y = container'
54731                 return container.parent // x.prototype.y = container
54732                     .left // x.prototype.y
54733                     .expression // x.prototype
54734                     .expression; // x
54735             }
54736             // x.prototype = { method() { } }
54737             else if (container.kind === 161 /* MethodDeclaration */ &&
54738                 container.parent.kind === 193 /* ObjectLiteralExpression */ &&
54739                 ts.isBinaryExpression(container.parent.parent) &&
54740                 ts.getAssignmentDeclarationKind(container.parent.parent) === 6 /* Prototype */) {
54741                 return container.parent.parent.left.expression;
54742             }
54743             // x.prototype = { method: function() { } }
54744             else if (container.kind === 201 /* FunctionExpression */ &&
54745                 container.parent.kind === 281 /* PropertyAssignment */ &&
54746                 container.parent.parent.kind === 193 /* ObjectLiteralExpression */ &&
54747                 ts.isBinaryExpression(container.parent.parent.parent) &&
54748                 ts.getAssignmentDeclarationKind(container.parent.parent.parent) === 6 /* Prototype */) {
54749                 return container.parent.parent.parent.left.expression;
54750             }
54751             // Object.defineProperty(x, "method", { value: function() { } });
54752             // Object.defineProperty(x, "method", { set: (x: () => void) => void });
54753             // Object.defineProperty(x, "method", { get: () => function() { }) });
54754             else if (container.kind === 201 /* FunctionExpression */ &&
54755                 ts.isPropertyAssignment(container.parent) &&
54756                 ts.isIdentifier(container.parent.name) &&
54757                 (container.parent.name.escapedText === "value" || container.parent.name.escapedText === "get" || container.parent.name.escapedText === "set") &&
54758                 ts.isObjectLiteralExpression(container.parent.parent) &&
54759                 ts.isCallExpression(container.parent.parent.parent) &&
54760                 container.parent.parent.parent.arguments[2] === container.parent.parent &&
54761                 ts.getAssignmentDeclarationKind(container.parent.parent.parent) === 9 /* ObjectDefinePrototypeProperty */) {
54762                 return container.parent.parent.parent.arguments[0].expression;
54763             }
54764             // Object.defineProperty(x, "method", { value() { } });
54765             // Object.defineProperty(x, "method", { set(x: () => void) {} });
54766             // Object.defineProperty(x, "method", { get() { return () => {} } });
54767             else if (ts.isMethodDeclaration(container) &&
54768                 ts.isIdentifier(container.name) &&
54769                 (container.name.escapedText === "value" || container.name.escapedText === "get" || container.name.escapedText === "set") &&
54770                 ts.isObjectLiteralExpression(container.parent) &&
54771                 ts.isCallExpression(container.parent.parent) &&
54772                 container.parent.parent.arguments[2] === container.parent &&
54773                 ts.getAssignmentDeclarationKind(container.parent.parent) === 9 /* ObjectDefinePrototypeProperty */) {
54774                 return container.parent.parent.arguments[0].expression;
54775             }
54776         }
54777         function getTypeForThisExpressionFromJSDoc(node) {
54778             var jsdocType = ts.getJSDocType(node);
54779             if (jsdocType && jsdocType.kind === 300 /* JSDocFunctionType */) {
54780                 var jsDocFunctionType = jsdocType;
54781                 if (jsDocFunctionType.parameters.length > 0 &&
54782                     jsDocFunctionType.parameters[0].name &&
54783                     jsDocFunctionType.parameters[0].name.escapedText === "this" /* This */) {
54784                     return getTypeFromTypeNode(jsDocFunctionType.parameters[0].type);
54785                 }
54786             }
54787             var thisTag = ts.getJSDocThisTag(node);
54788             if (thisTag && thisTag.typeExpression) {
54789                 return getTypeFromTypeNode(thisTag.typeExpression);
54790             }
54791         }
54792         function isInConstructorArgumentInitializer(node, constructorDecl) {
54793             return !!ts.findAncestor(node, function (n) { return ts.isFunctionLikeDeclaration(n) ? "quit" : n.kind === 156 /* Parameter */ && n.parent === constructorDecl; });
54794         }
54795         function checkSuperExpression(node) {
54796             var isCallExpression = node.parent.kind === 196 /* CallExpression */ && node.parent.expression === node;
54797             var container = ts.getSuperContainer(node, /*stopOnFunctions*/ true);
54798             var needToCaptureLexicalThis = false;
54799             // adjust the container reference in case if super is used inside arrow functions with arbitrarily deep nesting
54800             if (!isCallExpression) {
54801                 while (container && container.kind === 202 /* ArrowFunction */) {
54802                     container = ts.getSuperContainer(container, /*stopOnFunctions*/ true);
54803                     needToCaptureLexicalThis = languageVersion < 2 /* ES2015 */;
54804                 }
54805             }
54806             var canUseSuperExpression = isLegalUsageOfSuperExpression(container);
54807             var nodeCheckFlag = 0;
54808             if (!canUseSuperExpression) {
54809                 // issue more specific error if super is used in computed property name
54810                 // class A { foo() { return "1" }}
54811                 // class B {
54812                 //     [super.foo()]() {}
54813                 // }
54814                 var current = ts.findAncestor(node, function (n) { return n === container ? "quit" : n.kind === 154 /* ComputedPropertyName */; });
54815                 if (current && current.kind === 154 /* ComputedPropertyName */) {
54816                     error(node, ts.Diagnostics.super_cannot_be_referenced_in_a_computed_property_name);
54817                 }
54818                 else if (isCallExpression) {
54819                     error(node, ts.Diagnostics.Super_calls_are_not_permitted_outside_constructors_or_in_nested_functions_inside_constructors);
54820                 }
54821                 else if (!container || !container.parent || !(ts.isClassLike(container.parent) || container.parent.kind === 193 /* ObjectLiteralExpression */)) {
54822                     error(node, ts.Diagnostics.super_can_only_be_referenced_in_members_of_derived_classes_or_object_literal_expressions);
54823                 }
54824                 else {
54825                     error(node, ts.Diagnostics.super_property_access_is_permitted_only_in_a_constructor_member_function_or_member_accessor_of_a_derived_class);
54826                 }
54827                 return errorType;
54828             }
54829             if (!isCallExpression && container.kind === 162 /* Constructor */) {
54830                 checkThisBeforeSuper(node, container, ts.Diagnostics.super_must_be_called_before_accessing_a_property_of_super_in_the_constructor_of_a_derived_class);
54831             }
54832             if (ts.hasModifier(container, 32 /* Static */) || isCallExpression) {
54833                 nodeCheckFlag = 512 /* SuperStatic */;
54834             }
54835             else {
54836                 nodeCheckFlag = 256 /* SuperInstance */;
54837             }
54838             getNodeLinks(node).flags |= nodeCheckFlag;
54839             // Due to how we emit async functions, we need to specialize the emit for an async method that contains a `super` reference.
54840             // This is due to the fact that we emit the body of an async function inside of a generator function. As generator
54841             // functions cannot reference `super`, we emit a helper inside of the method body, but outside of the generator. This helper
54842             // uses an arrow function, which is permitted to reference `super`.
54843             //
54844             // There are two primary ways we can access `super` from within an async method. The first is getting the value of a property
54845             // or indexed access on super, either as part of a right-hand-side expression or call expression. The second is when setting the value
54846             // of a property or indexed access, either as part of an assignment expression or destructuring assignment.
54847             //
54848             // The simplest case is reading a value, in which case we will emit something like the following:
54849             //
54850             //  // ts
54851             //  ...
54852             //  async asyncMethod() {
54853             //    let x = await super.asyncMethod();
54854             //    return x;
54855             //  }
54856             //  ...
54857             //
54858             //  // js
54859             //  ...
54860             //  asyncMethod() {
54861             //      const _super = Object.create(null, {
54862             //        asyncMethod: { get: () => super.asyncMethod },
54863             //      });
54864             //      return __awaiter(this, arguments, Promise, function *() {
54865             //          let x = yield _super.asyncMethod.call(this);
54866             //          return x;
54867             //      });
54868             //  }
54869             //  ...
54870             //
54871             // The more complex case is when we wish to assign a value, especially as part of a destructuring assignment. As both cases
54872             // are legal in ES6, but also likely less frequent, we only emit setters if there is an assignment:
54873             //
54874             //  // ts
54875             //  ...
54876             //  async asyncMethod(ar: Promise<any[]>) {
54877             //      [super.a, super.b] = await ar;
54878             //  }
54879             //  ...
54880             //
54881             //  // js
54882             //  ...
54883             //  asyncMethod(ar) {
54884             //      const _super = Object.create(null, {
54885             //        a: { get: () => super.a, set: (v) => super.a = v },
54886             //        b: { get: () => super.b, set: (v) => super.b = v }
54887             //      };
54888             //      return __awaiter(this, arguments, Promise, function *() {
54889             //          [_super.a, _super.b] = yield ar;
54890             //      });
54891             //  }
54892             //  ...
54893             //
54894             // Creating an object that has getter and setters instead of just an accessor function is required for destructuring assignments
54895             // as a call expression cannot be used as the target of a destructuring assignment while a property access can.
54896             //
54897             // For element access expressions (`super[x]`), we emit a generic helper that forwards the element access in both situations.
54898             if (container.kind === 161 /* MethodDeclaration */ && ts.hasModifier(container, 256 /* Async */)) {
54899                 if (ts.isSuperProperty(node.parent) && ts.isAssignmentTarget(node.parent)) {
54900                     getNodeLinks(container).flags |= 4096 /* AsyncMethodWithSuperBinding */;
54901                 }
54902                 else {
54903                     getNodeLinks(container).flags |= 2048 /* AsyncMethodWithSuper */;
54904                 }
54905             }
54906             if (needToCaptureLexicalThis) {
54907                 // call expressions are allowed only in constructors so they should always capture correct 'this'
54908                 // super property access expressions can also appear in arrow functions -
54909                 // in this case they should also use correct lexical this
54910                 captureLexicalThis(node.parent, container);
54911             }
54912             if (container.parent.kind === 193 /* ObjectLiteralExpression */) {
54913                 if (languageVersion < 2 /* ES2015 */) {
54914                     error(node, ts.Diagnostics.super_is_only_allowed_in_members_of_object_literal_expressions_when_option_target_is_ES2015_or_higher);
54915                     return errorType;
54916                 }
54917                 else {
54918                     // for object literal assume that type of 'super' is 'any'
54919                     return anyType;
54920                 }
54921             }
54922             // at this point the only legal case for parent is ClassLikeDeclaration
54923             var classLikeDeclaration = container.parent;
54924             if (!ts.getClassExtendsHeritageElement(classLikeDeclaration)) {
54925                 error(node, ts.Diagnostics.super_can_only_be_referenced_in_a_derived_class);
54926                 return errorType;
54927             }
54928             var classType = getDeclaredTypeOfSymbol(getSymbolOfNode(classLikeDeclaration));
54929             var baseClassType = classType && getBaseTypes(classType)[0];
54930             if (!baseClassType) {
54931                 return errorType;
54932             }
54933             if (container.kind === 162 /* Constructor */ && isInConstructorArgumentInitializer(node, container)) {
54934                 // issue custom error message for super property access in constructor arguments (to be aligned with old compiler)
54935                 error(node, ts.Diagnostics.super_cannot_be_referenced_in_constructor_arguments);
54936                 return errorType;
54937             }
54938             return nodeCheckFlag === 512 /* SuperStatic */
54939                 ? getBaseConstructorTypeOfClass(classType)
54940                 : getTypeWithThisArgument(baseClassType, classType.thisType);
54941             function isLegalUsageOfSuperExpression(container) {
54942                 if (!container) {
54943                     return false;
54944                 }
54945                 if (isCallExpression) {
54946                     // TS 1.0 SPEC (April 2014): 4.8.1
54947                     // Super calls are only permitted in constructors of derived classes
54948                     return container.kind === 162 /* Constructor */;
54949                 }
54950                 else {
54951                     // TS 1.0 SPEC (April 2014)
54952                     // 'super' property access is allowed
54953                     // - In a constructor, instance member function, instance member accessor, or instance member variable initializer where this references a derived class instance
54954                     // - In a static member function or static member accessor
54955                     // topmost container must be something that is directly nested in the class declaration\object literal expression
54956                     if (ts.isClassLike(container.parent) || container.parent.kind === 193 /* ObjectLiteralExpression */) {
54957                         if (ts.hasModifier(container, 32 /* Static */)) {
54958                             return container.kind === 161 /* MethodDeclaration */ ||
54959                                 container.kind === 160 /* MethodSignature */ ||
54960                                 container.kind === 163 /* GetAccessor */ ||
54961                                 container.kind === 164 /* SetAccessor */;
54962                         }
54963                         else {
54964                             return container.kind === 161 /* MethodDeclaration */ ||
54965                                 container.kind === 160 /* MethodSignature */ ||
54966                                 container.kind === 163 /* GetAccessor */ ||
54967                                 container.kind === 164 /* SetAccessor */ ||
54968                                 container.kind === 159 /* PropertyDeclaration */ ||
54969                                 container.kind === 158 /* PropertySignature */ ||
54970                                 container.kind === 162 /* Constructor */;
54971                         }
54972                     }
54973                 }
54974                 return false;
54975             }
54976         }
54977         function getContainingObjectLiteral(func) {
54978             return (func.kind === 161 /* MethodDeclaration */ ||
54979                 func.kind === 163 /* GetAccessor */ ||
54980                 func.kind === 164 /* SetAccessor */) && func.parent.kind === 193 /* ObjectLiteralExpression */ ? func.parent :
54981                 func.kind === 201 /* FunctionExpression */ && func.parent.kind === 281 /* PropertyAssignment */ ? func.parent.parent :
54982                     undefined;
54983         }
54984         function getThisTypeArgument(type) {
54985             return ts.getObjectFlags(type) & 4 /* Reference */ && type.target === globalThisType ? getTypeArguments(type)[0] : undefined;
54986         }
54987         function getThisTypeFromContextualType(type) {
54988             return mapType(type, function (t) {
54989                 return t.flags & 2097152 /* Intersection */ ? ts.forEach(t.types, getThisTypeArgument) : getThisTypeArgument(t);
54990             });
54991         }
54992         function getContextualThisParameterType(func) {
54993             if (func.kind === 202 /* ArrowFunction */) {
54994                 return undefined;
54995             }
54996             if (isContextSensitiveFunctionOrObjectLiteralMethod(func)) {
54997                 var contextualSignature = getContextualSignature(func);
54998                 if (contextualSignature) {
54999                     var thisParameter = contextualSignature.thisParameter;
55000                     if (thisParameter) {
55001                         return getTypeOfSymbol(thisParameter);
55002                     }
55003                 }
55004             }
55005             var inJs = ts.isInJSFile(func);
55006             if (noImplicitThis || inJs) {
55007                 var containingLiteral = getContainingObjectLiteral(func);
55008                 if (containingLiteral) {
55009                     // We have an object literal method. Check if the containing object literal has a contextual type
55010                     // that includes a ThisType<T>. If so, T is the contextual type for 'this'. We continue looking in
55011                     // any directly enclosing object literals.
55012                     var contextualType = getApparentTypeOfContextualType(containingLiteral);
55013                     var literal = containingLiteral;
55014                     var type = contextualType;
55015                     while (type) {
55016                         var thisType = getThisTypeFromContextualType(type);
55017                         if (thisType) {
55018                             return instantiateType(thisType, getMapperFromContext(getInferenceContext(containingLiteral)));
55019                         }
55020                         if (literal.parent.kind !== 281 /* PropertyAssignment */) {
55021                             break;
55022                         }
55023                         literal = literal.parent.parent;
55024                         type = getApparentTypeOfContextualType(literal);
55025                     }
55026                     // There was no contextual ThisType<T> for the containing object literal, so the contextual type
55027                     // for 'this' is the non-null form of the contextual type for the containing object literal or
55028                     // the type of the object literal itself.
55029                     return getWidenedType(contextualType ? getNonNullableType(contextualType) : checkExpressionCached(containingLiteral));
55030                 }
55031                 // In an assignment of the form 'obj.xxx = function(...)' or 'obj[xxx] = function(...)', the
55032                 // contextual type for 'this' is 'obj'.
55033                 var parent = ts.walkUpParenthesizedExpressions(func.parent);
55034                 if (parent.kind === 209 /* BinaryExpression */ && parent.operatorToken.kind === 62 /* EqualsToken */) {
55035                     var target = parent.left;
55036                     if (ts.isAccessExpression(target)) {
55037                         var expression = target.expression;
55038                         // Don't contextually type `this` as `exports` in `exports.Point = function(x, y) { this.x = x; this.y = y; }`
55039                         if (inJs && ts.isIdentifier(expression)) {
55040                             var sourceFile = ts.getSourceFileOfNode(parent);
55041                             if (sourceFile.commonJsModuleIndicator && getResolvedSymbol(expression) === sourceFile.symbol) {
55042                                 return undefined;
55043                             }
55044                         }
55045                         return getWidenedType(checkExpressionCached(expression));
55046                     }
55047                 }
55048             }
55049             return undefined;
55050         }
55051         // Return contextual type of parameter or undefined if no contextual type is available
55052         function getContextuallyTypedParameterType(parameter) {
55053             var func = parameter.parent;
55054             if (!isContextSensitiveFunctionOrObjectLiteralMethod(func)) {
55055                 return undefined;
55056             }
55057             var iife = ts.getImmediatelyInvokedFunctionExpression(func);
55058             if (iife && iife.arguments) {
55059                 var args = getEffectiveCallArguments(iife);
55060                 var indexOfParameter = func.parameters.indexOf(parameter);
55061                 if (parameter.dotDotDotToken) {
55062                     return getSpreadArgumentType(args, indexOfParameter, args.length, anyType, /*context*/ undefined);
55063                 }
55064                 var links = getNodeLinks(iife);
55065                 var cached = links.resolvedSignature;
55066                 links.resolvedSignature = anySignature;
55067                 var type = indexOfParameter < args.length ?
55068                     getWidenedLiteralType(checkExpression(args[indexOfParameter])) :
55069                     parameter.initializer ? undefined : undefinedWideningType;
55070                 links.resolvedSignature = cached;
55071                 return type;
55072             }
55073             var contextualSignature = getContextualSignature(func);
55074             if (contextualSignature) {
55075                 var index = func.parameters.indexOf(parameter) - (ts.getThisParameter(func) ? 1 : 0);
55076                 return parameter.dotDotDotToken && ts.lastOrUndefined(func.parameters) === parameter ?
55077                     getRestTypeAtPosition(contextualSignature, index) :
55078                     tryGetTypeAtPosition(contextualSignature, index);
55079             }
55080         }
55081         function getContextualTypeForVariableLikeDeclaration(declaration) {
55082             var typeNode = ts.getEffectiveTypeAnnotationNode(declaration);
55083             if (typeNode) {
55084                 return getTypeFromTypeNode(typeNode);
55085             }
55086             switch (declaration.kind) {
55087                 case 156 /* Parameter */:
55088                     return getContextuallyTypedParameterType(declaration);
55089                 case 191 /* BindingElement */:
55090                     return getContextualTypeForBindingElement(declaration);
55091                 // By default, do nothing and return undefined - only parameters and binding elements have context implied by a parent
55092             }
55093         }
55094         function getContextualTypeForBindingElement(declaration) {
55095             var parent = declaration.parent.parent;
55096             var name = declaration.propertyName || declaration.name;
55097             var parentType = getContextualTypeForVariableLikeDeclaration(parent) ||
55098                 parent.kind !== 191 /* BindingElement */ && parent.initializer && checkDeclarationInitializer(parent);
55099             if (parentType && !ts.isBindingPattern(name) && !ts.isComputedNonLiteralName(name)) {
55100                 var nameType = getLiteralTypeFromPropertyName(name);
55101                 if (isTypeUsableAsPropertyName(nameType)) {
55102                     var text = getPropertyNameFromType(nameType);
55103                     return getTypeOfPropertyOfType(parentType, text);
55104                 }
55105             }
55106         }
55107         // In a variable, parameter or property declaration with a type annotation,
55108         //   the contextual type of an initializer expression is the type of the variable, parameter or property.
55109         // Otherwise, in a parameter declaration of a contextually typed function expression,
55110         //   the contextual type of an initializer expression is the contextual type of the parameter.
55111         // Otherwise, in a variable or parameter declaration with a binding pattern name,
55112         //   the contextual type of an initializer expression is the type implied by the binding pattern.
55113         // Otherwise, in a binding pattern inside a variable or parameter declaration,
55114         //   the contextual type of an initializer expression is the type annotation of the containing declaration, if present.
55115         function getContextualTypeForInitializerExpression(node) {
55116             var declaration = node.parent;
55117             if (ts.hasInitializer(declaration) && node === declaration.initializer) {
55118                 var result = getContextualTypeForVariableLikeDeclaration(declaration);
55119                 if (result) {
55120                     return result;
55121                 }
55122                 if (ts.isBindingPattern(declaration.name)) { // This is less a contextual type and more an implied shape - in some cases, this may be undesirable
55123                     return getTypeFromBindingPattern(declaration.name, /*includePatternInType*/ true, /*reportErrors*/ false);
55124                 }
55125             }
55126             return undefined;
55127         }
55128         function getContextualTypeForReturnExpression(node) {
55129             var func = ts.getContainingFunction(node);
55130             if (func) {
55131                 var functionFlags = ts.getFunctionFlags(func);
55132                 if (functionFlags & 1 /* Generator */) { // AsyncGenerator function or Generator function
55133                     return undefined;
55134                 }
55135                 var contextualReturnType = getContextualReturnType(func);
55136                 if (contextualReturnType) {
55137                     if (functionFlags & 2 /* Async */) { // Async function
55138                         var contextualAwaitedType = mapType(contextualReturnType, getAwaitedTypeOfPromise);
55139                         return contextualAwaitedType && getUnionType([contextualAwaitedType, createPromiseLikeType(contextualAwaitedType)]);
55140                     }
55141                     return contextualReturnType; // Regular function
55142                 }
55143             }
55144             return undefined;
55145         }
55146         function getContextualTypeForAwaitOperand(node) {
55147             var contextualType = getContextualType(node);
55148             if (contextualType) {
55149                 var contextualAwaitedType = getAwaitedType(contextualType);
55150                 return contextualAwaitedType && getUnionType([contextualAwaitedType, createPromiseLikeType(contextualAwaitedType)]);
55151             }
55152             return undefined;
55153         }
55154         function getContextualTypeForYieldOperand(node) {
55155             var func = ts.getContainingFunction(node);
55156             if (func) {
55157                 var functionFlags = ts.getFunctionFlags(func);
55158                 var contextualReturnType = getContextualReturnType(func);
55159                 if (contextualReturnType) {
55160                     return node.asteriskToken
55161                         ? contextualReturnType
55162                         : getIterationTypeOfGeneratorFunctionReturnType(0 /* Yield */, contextualReturnType, (functionFlags & 2 /* Async */) !== 0);
55163                 }
55164             }
55165             return undefined;
55166         }
55167         function isInParameterInitializerBeforeContainingFunction(node) {
55168             var inBindingInitializer = false;
55169             while (node.parent && !ts.isFunctionLike(node.parent)) {
55170                 if (ts.isParameter(node.parent) && (inBindingInitializer || node.parent.initializer === node)) {
55171                     return true;
55172                 }
55173                 if (ts.isBindingElement(node.parent) && node.parent.initializer === node) {
55174                     inBindingInitializer = true;
55175                 }
55176                 node = node.parent;
55177             }
55178             return false;
55179         }
55180         function getContextualIterationType(kind, functionDecl) {
55181             var isAsync = !!(ts.getFunctionFlags(functionDecl) & 2 /* Async */);
55182             var contextualReturnType = getContextualReturnType(functionDecl);
55183             if (contextualReturnType) {
55184                 return getIterationTypeOfGeneratorFunctionReturnType(kind, contextualReturnType, isAsync)
55185                     || undefined;
55186             }
55187             return undefined;
55188         }
55189         function getContextualReturnType(functionDecl) {
55190             // If the containing function has a return type annotation, is a constructor, or is a get accessor whose
55191             // corresponding set accessor has a type annotation, return statements in the function are contextually typed
55192             var returnType = getReturnTypeFromAnnotation(functionDecl);
55193             if (returnType) {
55194                 return returnType;
55195             }
55196             // Otherwise, if the containing function is contextually typed by a function type with exactly one call signature
55197             // and that call signature is non-generic, return statements are contextually typed by the return type of the signature
55198             var signature = getContextualSignatureForFunctionLikeDeclaration(functionDecl);
55199             if (signature && !isResolvingReturnTypeOfSignature(signature)) {
55200                 return getReturnTypeOfSignature(signature);
55201             }
55202             return undefined;
55203         }
55204         // In a typed function call, an argument or substitution expression is contextually typed by the type of the corresponding parameter.
55205         function getContextualTypeForArgument(callTarget, arg) {
55206             var args = getEffectiveCallArguments(callTarget);
55207             var argIndex = args.indexOf(arg); // -1 for e.g. the expression of a CallExpression, or the tag of a TaggedTemplateExpression
55208             return argIndex === -1 ? undefined : getContextualTypeForArgumentAtIndex(callTarget, argIndex);
55209         }
55210         function getContextualTypeForArgumentAtIndex(callTarget, argIndex) {
55211             // If we're already in the process of resolving the given signature, don't resolve again as
55212             // that could cause infinite recursion. Instead, return anySignature.
55213             var signature = getNodeLinks(callTarget).resolvedSignature === resolvingSignature ? resolvingSignature : getResolvedSignature(callTarget);
55214             if (ts.isJsxOpeningLikeElement(callTarget) && argIndex === 0) {
55215                 return getEffectiveFirstArgumentForJsxSignature(signature, callTarget);
55216             }
55217             return getTypeAtPosition(signature, argIndex);
55218         }
55219         function getContextualTypeForSubstitutionExpression(template, substitutionExpression) {
55220             if (template.parent.kind === 198 /* TaggedTemplateExpression */) {
55221                 return getContextualTypeForArgument(template.parent, substitutionExpression);
55222             }
55223             return undefined;
55224         }
55225         function getContextualTypeForBinaryOperand(node, contextFlags) {
55226             var binaryExpression = node.parent;
55227             var left = binaryExpression.left, operatorToken = binaryExpression.operatorToken, right = binaryExpression.right;
55228             switch (operatorToken.kind) {
55229                 case 62 /* EqualsToken */:
55230                     if (node !== right) {
55231                         return undefined;
55232                     }
55233                     var contextSensitive = getIsContextSensitiveAssignmentOrContextType(binaryExpression);
55234                     if (!contextSensitive) {
55235                         return undefined;
55236                     }
55237                     return contextSensitive === true ? getTypeOfExpression(left) : contextSensitive;
55238                 case 56 /* BarBarToken */:
55239                 case 60 /* QuestionQuestionToken */:
55240                     // When an || expression has a contextual type, the operands are contextually typed by that type, except
55241                     // when that type originates in a binding pattern, the right operand is contextually typed by the type of
55242                     // the left operand. When an || expression has no contextual type, the right operand is contextually typed
55243                     // by the type of the left operand, except for the special case of Javascript declarations of the form
55244                     // `namespace.prop = namespace.prop || {}`.
55245                     var type = getContextualType(binaryExpression, contextFlags);
55246                     return node === right && (type && type.pattern || !type && !ts.isDefaultedExpandoInitializer(binaryExpression)) ?
55247                         getTypeOfExpression(left) : type;
55248                 case 55 /* AmpersandAmpersandToken */:
55249                 case 27 /* CommaToken */:
55250                     return node === right ? getContextualType(binaryExpression, contextFlags) : undefined;
55251                 default:
55252                     return undefined;
55253             }
55254         }
55255         // In an assignment expression, the right operand is contextually typed by the type of the left operand.
55256         // Don't do this for assignment declarations unless there is a type tag on the assignment, to avoid circularity from checking the right operand.
55257         function getIsContextSensitiveAssignmentOrContextType(binaryExpression) {
55258             var kind = ts.getAssignmentDeclarationKind(binaryExpression);
55259             switch (kind) {
55260                 case 0 /* None */:
55261                     return true;
55262                 case 5 /* Property */:
55263                 case 1 /* ExportsProperty */:
55264                 case 6 /* Prototype */:
55265                 case 3 /* PrototypeProperty */:
55266                     // If `binaryExpression.left` was assigned a symbol, then this is a new declaration; otherwise it is an assignment to an existing declaration.
55267                     // See `bindStaticPropertyAssignment` in `binder.ts`.
55268                     if (!binaryExpression.left.symbol) {
55269                         return true;
55270                     }
55271                     else {
55272                         var decl = binaryExpression.left.symbol.valueDeclaration;
55273                         if (!decl) {
55274                             return false;
55275                         }
55276                         var lhs = ts.cast(binaryExpression.left, ts.isAccessExpression);
55277                         var overallAnnotation = ts.getEffectiveTypeAnnotationNode(decl);
55278                         if (overallAnnotation) {
55279                             return getTypeFromTypeNode(overallAnnotation);
55280                         }
55281                         else if (ts.isIdentifier(lhs.expression)) {
55282                             var id = lhs.expression;
55283                             var parentSymbol = resolveName(id, id.escapedText, 111551 /* Value */, undefined, id.escapedText, /*isUse*/ true);
55284                             if (parentSymbol) {
55285                                 var annotated = ts.getEffectiveTypeAnnotationNode(parentSymbol.valueDeclaration);
55286                                 if (annotated) {
55287                                     var nameStr_1 = ts.getElementOrPropertyAccessName(lhs);
55288                                     if (nameStr_1 !== undefined) {
55289                                         var type = getTypeOfPropertyOfContextualType(getTypeFromTypeNode(annotated), nameStr_1);
55290                                         return type || false;
55291                                     }
55292                                 }
55293                                 return false;
55294                             }
55295                         }
55296                         return !ts.isInJSFile(decl);
55297                     }
55298                 case 2 /* ModuleExports */:
55299                 case 4 /* ThisProperty */:
55300                     if (!binaryExpression.symbol)
55301                         return true;
55302                     if (binaryExpression.symbol.valueDeclaration) {
55303                         var annotated = ts.getEffectiveTypeAnnotationNode(binaryExpression.symbol.valueDeclaration);
55304                         if (annotated) {
55305                             var type = getTypeFromTypeNode(annotated);
55306                             if (type) {
55307                                 return type;
55308                             }
55309                         }
55310                     }
55311                     if (kind === 2 /* ModuleExports */)
55312                         return false;
55313                     var thisAccess = ts.cast(binaryExpression.left, ts.isAccessExpression);
55314                     if (!ts.isObjectLiteralMethod(ts.getThisContainer(thisAccess.expression, /*includeArrowFunctions*/ false))) {
55315                         return false;
55316                     }
55317                     var thisType = checkThisExpression(thisAccess.expression);
55318                     var nameStr = ts.getElementOrPropertyAccessName(thisAccess);
55319                     return nameStr !== undefined && thisType && getTypeOfPropertyOfContextualType(thisType, nameStr) || false;
55320                 case 7 /* ObjectDefinePropertyValue */:
55321                 case 8 /* ObjectDefinePropertyExports */:
55322                 case 9 /* ObjectDefinePrototypeProperty */:
55323                     return ts.Debug.fail("Does not apply");
55324                 default:
55325                     return ts.Debug.assertNever(kind);
55326             }
55327         }
55328         function isCircularMappedProperty(symbol) {
55329             return !!(ts.getCheckFlags(symbol) & 262144 /* Mapped */ && !symbol.type && findResolutionCycleStartIndex(symbol, 0 /* Type */) >= 0);
55330         }
55331         function getTypeOfPropertyOfContextualType(type, name) {
55332             return mapType(type, function (t) {
55333                 if (isGenericMappedType(t)) {
55334                     var constraint = getConstraintTypeFromMappedType(t);
55335                     var constraintOfConstraint = getBaseConstraintOfType(constraint) || constraint;
55336                     var propertyNameType = getLiteralType(ts.unescapeLeadingUnderscores(name));
55337                     if (isTypeAssignableTo(propertyNameType, constraintOfConstraint)) {
55338                         return substituteIndexedMappedType(t, propertyNameType);
55339                     }
55340                 }
55341                 else if (t.flags & 3670016 /* StructuredType */) {
55342                     var prop = getPropertyOfType(t, name);
55343                     if (prop) {
55344                         return isCircularMappedProperty(prop) ? undefined : getTypeOfSymbol(prop);
55345                     }
55346                     if (isTupleType(t)) {
55347                         var restType = getRestTypeOfTupleType(t);
55348                         if (restType && isNumericLiteralName(name) && +name >= 0) {
55349                             return restType;
55350                         }
55351                     }
55352                     return isNumericLiteralName(name) && getIndexTypeOfContextualType(t, 1 /* Number */) ||
55353                         getIndexTypeOfContextualType(t, 0 /* String */);
55354                 }
55355                 return undefined;
55356             }, /*noReductions*/ true);
55357         }
55358         function getIndexTypeOfContextualType(type, kind) {
55359             return mapType(type, function (t) { return getIndexTypeOfStructuredType(t, kind); }, /*noReductions*/ true);
55360         }
55361         // In an object literal contextually typed by a type T, the contextual type of a property assignment is the type of
55362         // the matching property in T, if one exists. Otherwise, it is the type of the numeric index signature in T, if one
55363         // exists. Otherwise, it is the type of the string index signature in T, if one exists.
55364         function getContextualTypeForObjectLiteralMethod(node, contextFlags) {
55365             ts.Debug.assert(ts.isObjectLiteralMethod(node));
55366             if (node.flags & 16777216 /* InWithStatement */) {
55367                 // We cannot answer semantic questions within a with block, do not proceed any further
55368                 return undefined;
55369             }
55370             return getContextualTypeForObjectLiteralElement(node, contextFlags);
55371         }
55372         function getContextualTypeForObjectLiteralElement(element, contextFlags) {
55373             var objectLiteral = element.parent;
55374             var type = getApparentTypeOfContextualType(objectLiteral, contextFlags);
55375             if (type) {
55376                 if (!hasNonBindableDynamicName(element)) {
55377                     // For a (non-symbol) computed property, there is no reason to look up the name
55378                     // in the type. It will just be "__computed", which does not appear in any
55379                     // SymbolTable.
55380                     var symbolName_3 = getSymbolOfNode(element).escapedName;
55381                     var propertyType = getTypeOfPropertyOfContextualType(type, symbolName_3);
55382                     if (propertyType) {
55383                         return propertyType;
55384                     }
55385                 }
55386                 return isNumericName(element.name) && getIndexTypeOfContextualType(type, 1 /* Number */) ||
55387                     getIndexTypeOfContextualType(type, 0 /* String */);
55388             }
55389             return undefined;
55390         }
55391         // In an array literal contextually typed by a type T, the contextual type of an element expression at index N is
55392         // the type of the property with the numeric name N in T, if one exists. Otherwise, if T has a numeric index signature,
55393         // it is the type of the numeric index signature in T. Otherwise, in ES6 and higher, the contextual type is the iterated
55394         // type of T.
55395         function getContextualTypeForElementExpression(arrayContextualType, index) {
55396             return arrayContextualType && (getTypeOfPropertyOfContextualType(arrayContextualType, "" + index)
55397                 || getIteratedTypeOrElementType(1 /* Element */, arrayContextualType, undefinedType, /*errorNode*/ undefined, /*checkAssignability*/ false));
55398         }
55399         // In a contextually typed conditional expression, the true/false expressions are contextually typed by the same type.
55400         function getContextualTypeForConditionalOperand(node, contextFlags) {
55401             var conditional = node.parent;
55402             return node === conditional.whenTrue || node === conditional.whenFalse ? getContextualType(conditional, contextFlags) : undefined;
55403         }
55404         function getContextualTypeForChildJsxExpression(node, child) {
55405             var attributesType = getApparentTypeOfContextualType(node.openingElement.tagName);
55406             // JSX expression is in children of JSX Element, we will look for an "children" atttribute (we get the name from JSX.ElementAttributesProperty)
55407             var jsxChildrenPropertyName = getJsxElementChildrenPropertyName(getJsxNamespaceAt(node));
55408             if (!(attributesType && !isTypeAny(attributesType) && jsxChildrenPropertyName && jsxChildrenPropertyName !== "")) {
55409                 return undefined;
55410             }
55411             var realChildren = getSemanticJsxChildren(node.children);
55412             var childIndex = realChildren.indexOf(child);
55413             var childFieldType = getTypeOfPropertyOfContextualType(attributesType, jsxChildrenPropertyName);
55414             return childFieldType && (realChildren.length === 1 ? childFieldType : mapType(childFieldType, function (t) {
55415                 if (isArrayLikeType(t)) {
55416                     return getIndexedAccessType(t, getLiteralType(childIndex));
55417                 }
55418                 else {
55419                     return t;
55420                 }
55421             }, /*noReductions*/ true));
55422         }
55423         function getContextualTypeForJsxExpression(node) {
55424             var exprParent = node.parent;
55425             return ts.isJsxAttributeLike(exprParent)
55426                 ? getContextualType(node)
55427                 : ts.isJsxElement(exprParent)
55428                     ? getContextualTypeForChildJsxExpression(exprParent, node)
55429                     : undefined;
55430         }
55431         function getContextualTypeForJsxAttribute(attribute) {
55432             // When we trying to resolve JsxOpeningLikeElement as a stateless function element, we will already give its attributes a contextual type
55433             // which is a type of the parameter of the signature we are trying out.
55434             // If there is no contextual type (e.g. we are trying to resolve stateful component), get attributes type from resolving element's tagName
55435             if (ts.isJsxAttribute(attribute)) {
55436                 var attributesType = getApparentTypeOfContextualType(attribute.parent);
55437                 if (!attributesType || isTypeAny(attributesType)) {
55438                     return undefined;
55439                 }
55440                 return getTypeOfPropertyOfContextualType(attributesType, attribute.name.escapedText);
55441             }
55442             else {
55443                 return getContextualType(attribute.parent);
55444             }
55445         }
55446         // Return true if the given expression is possibly a discriminant value. We limit the kinds of
55447         // expressions we check to those that don't depend on their contextual type in order not to cause
55448         // recursive (and possibly infinite) invocations of getContextualType.
55449         function isPossiblyDiscriminantValue(node) {
55450             switch (node.kind) {
55451                 case 10 /* StringLiteral */:
55452                 case 8 /* NumericLiteral */:
55453                 case 9 /* BigIntLiteral */:
55454                 case 14 /* NoSubstitutionTemplateLiteral */:
55455                 case 106 /* TrueKeyword */:
55456                 case 91 /* FalseKeyword */:
55457                 case 100 /* NullKeyword */:
55458                 case 75 /* Identifier */:
55459                 case 146 /* UndefinedKeyword */:
55460                     return true;
55461                 case 194 /* PropertyAccessExpression */:
55462                 case 200 /* ParenthesizedExpression */:
55463                     return isPossiblyDiscriminantValue(node.expression);
55464                 case 276 /* JsxExpression */:
55465                     return !node.expression || isPossiblyDiscriminantValue(node.expression);
55466             }
55467             return false;
55468         }
55469         function discriminateContextualTypeByObjectMembers(node, contextualType) {
55470             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);
55471         }
55472         function discriminateContextualTypeByJSXAttributes(node, contextualType) {
55473             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);
55474         }
55475         // Return the contextual type for a given expression node. During overload resolution, a contextual type may temporarily
55476         // be "pushed" onto a node using the contextualType property.
55477         function getApparentTypeOfContextualType(node, contextFlags) {
55478             var contextualType = ts.isObjectLiteralMethod(node) ?
55479                 getContextualTypeForObjectLiteralMethod(node, contextFlags) :
55480                 getContextualType(node, contextFlags);
55481             var instantiatedType = instantiateContextualType(contextualType, node, contextFlags);
55482             if (instantiatedType && !(contextFlags && contextFlags & 2 /* NoConstraints */ && instantiatedType.flags & 8650752 /* TypeVariable */)) {
55483                 var apparentType = mapType(instantiatedType, getApparentType, /*noReductions*/ true);
55484                 if (apparentType.flags & 1048576 /* Union */) {
55485                     if (ts.isObjectLiteralExpression(node)) {
55486                         return discriminateContextualTypeByObjectMembers(node, apparentType);
55487                     }
55488                     else if (ts.isJsxAttributes(node)) {
55489                         return discriminateContextualTypeByJSXAttributes(node, apparentType);
55490                     }
55491                 }
55492                 return apparentType;
55493             }
55494         }
55495         // If the given contextual type contains instantiable types and if a mapper representing
55496         // return type inferences is available, instantiate those types using that mapper.
55497         function instantiateContextualType(contextualType, node, contextFlags) {
55498             if (contextualType && maybeTypeOfKind(contextualType, 63176704 /* Instantiable */)) {
55499                 var inferenceContext = getInferenceContext(node);
55500                 // If no inferences have been made, nothing is gained from instantiating as type parameters
55501                 // would just be replaced with their defaults similar to the apparent type.
55502                 if (inferenceContext && ts.some(inferenceContext.inferences, hasInferenceCandidates)) {
55503                     // For contextual signatures we incorporate all inferences made so far, e.g. from return
55504                     // types as well as arguments to the left in a function call.
55505                     if (contextFlags && contextFlags & 1 /* Signature */) {
55506                         return instantiateInstantiableTypes(contextualType, inferenceContext.nonFixingMapper);
55507                     }
55508                     // For other purposes (e.g. determining whether to produce literal types) we only
55509                     // incorporate inferences made from the return type in a function call.
55510                     if (inferenceContext.returnMapper) {
55511                         return instantiateInstantiableTypes(contextualType, inferenceContext.returnMapper);
55512                     }
55513                 }
55514             }
55515             return contextualType;
55516         }
55517         // This function is similar to instantiateType, except that (a) it only instantiates types that
55518         // are classified as instantiable (i.e. it doesn't instantiate object types), and (b) it performs
55519         // no reductions on instantiated union types.
55520         function instantiateInstantiableTypes(type, mapper) {
55521             if (type.flags & 63176704 /* Instantiable */) {
55522                 return instantiateType(type, mapper);
55523             }
55524             if (type.flags & 1048576 /* Union */) {
55525                 return getUnionType(ts.map(type.types, function (t) { return instantiateInstantiableTypes(t, mapper); }), 0 /* None */);
55526             }
55527             if (type.flags & 2097152 /* Intersection */) {
55528                 return getIntersectionType(ts.map(type.types, function (t) { return instantiateInstantiableTypes(t, mapper); }));
55529             }
55530             return type;
55531         }
55532         /**
55533          * Whoa! Do you really want to use this function?
55534          *
55535          * Unless you're trying to get the *non-apparent* type for a
55536          * value-literal type or you're authoring relevant portions of this algorithm,
55537          * you probably meant to use 'getApparentTypeOfContextualType'.
55538          * Otherwise this may not be very useful.
55539          *
55540          * In cases where you *are* working on this function, you should understand
55541          * when it is appropriate to use 'getContextualType' and 'getApparentTypeOfContextualType'.
55542          *
55543          *   - Use 'getContextualType' when you are simply going to propagate the result to the expression.
55544          *   - Use 'getApparentTypeOfContextualType' when you're going to need the members of the type.
55545          *
55546          * @param node the expression whose contextual type will be returned.
55547          * @returns the contextual type of an expression.
55548          */
55549         function getContextualType(node, contextFlags) {
55550             if (node.flags & 16777216 /* InWithStatement */) {
55551                 // We cannot answer semantic questions within a with block, do not proceed any further
55552                 return undefined;
55553             }
55554             if (node.contextualType) {
55555                 return node.contextualType;
55556             }
55557             var parent = node.parent;
55558             switch (parent.kind) {
55559                 case 242 /* VariableDeclaration */:
55560                 case 156 /* Parameter */:
55561                 case 159 /* PropertyDeclaration */:
55562                 case 158 /* PropertySignature */:
55563                 case 191 /* BindingElement */:
55564                     return getContextualTypeForInitializerExpression(node);
55565                 case 202 /* ArrowFunction */:
55566                 case 235 /* ReturnStatement */:
55567                     return getContextualTypeForReturnExpression(node);
55568                 case 212 /* YieldExpression */:
55569                     return getContextualTypeForYieldOperand(parent);
55570                 case 206 /* AwaitExpression */:
55571                     return getContextualTypeForAwaitOperand(parent);
55572                 case 196 /* CallExpression */:
55573                     if (parent.expression.kind === 96 /* ImportKeyword */) {
55574                         return stringType;
55575                     }
55576                 /* falls through */
55577                 case 197 /* NewExpression */:
55578                     return getContextualTypeForArgument(parent, node);
55579                 case 199 /* TypeAssertionExpression */:
55580                 case 217 /* AsExpression */:
55581                     return ts.isConstTypeReference(parent.type) ? undefined : getTypeFromTypeNode(parent.type);
55582                 case 209 /* BinaryExpression */:
55583                     return getContextualTypeForBinaryOperand(node, contextFlags);
55584                 case 281 /* PropertyAssignment */:
55585                 case 282 /* ShorthandPropertyAssignment */:
55586                     return getContextualTypeForObjectLiteralElement(parent, contextFlags);
55587                 case 283 /* SpreadAssignment */:
55588                     return getApparentTypeOfContextualType(parent.parent, contextFlags);
55589                 case 192 /* ArrayLiteralExpression */: {
55590                     var arrayLiteral = parent;
55591                     var type = getApparentTypeOfContextualType(arrayLiteral, contextFlags);
55592                     return getContextualTypeForElementExpression(type, ts.indexOfNode(arrayLiteral.elements, node));
55593                 }
55594                 case 210 /* ConditionalExpression */:
55595                     return getContextualTypeForConditionalOperand(node, contextFlags);
55596                 case 221 /* TemplateSpan */:
55597                     ts.Debug.assert(parent.parent.kind === 211 /* TemplateExpression */);
55598                     return getContextualTypeForSubstitutionExpression(parent.parent, node);
55599                 case 200 /* ParenthesizedExpression */: {
55600                     // Like in `checkParenthesizedExpression`, an `/** @type {xyz} */` comment before a parenthesized expression acts as a type cast.
55601                     var tag = ts.isInJSFile(parent) ? ts.getJSDocTypeTag(parent) : undefined;
55602                     return tag ? getTypeFromTypeNode(tag.typeExpression.type) : getContextualType(parent, contextFlags);
55603                 }
55604                 case 276 /* JsxExpression */:
55605                     return getContextualTypeForJsxExpression(parent);
55606                 case 273 /* JsxAttribute */:
55607                 case 275 /* JsxSpreadAttribute */:
55608                     return getContextualTypeForJsxAttribute(parent);
55609                 case 268 /* JsxOpeningElement */:
55610                 case 267 /* JsxSelfClosingElement */:
55611                     return getContextualJsxElementAttributesType(parent, contextFlags);
55612             }
55613             return undefined;
55614         }
55615         function getInferenceContext(node) {
55616             var ancestor = ts.findAncestor(node, function (n) { return !!n.inferenceContext; });
55617             return ancestor && ancestor.inferenceContext;
55618         }
55619         function getContextualJsxElementAttributesType(node, contextFlags) {
55620             if (ts.isJsxOpeningElement(node) && node.parent.contextualType && contextFlags !== 4 /* Completions */) {
55621                 // Contextually applied type is moved from attributes up to the outer jsx attributes so when walking up from the children they get hit
55622                 // _However_ to hit them from the _attributes_ we must look for them here; otherwise we'll used the declared type
55623                 // (as below) instead!
55624                 return node.parent.contextualType;
55625             }
55626             return getContextualTypeForArgumentAtIndex(node, 0);
55627         }
55628         function getEffectiveFirstArgumentForJsxSignature(signature, node) {
55629             return getJsxReferenceKind(node) !== 0 /* Component */
55630                 ? getJsxPropsTypeFromCallSignature(signature, node)
55631                 : getJsxPropsTypeFromClassType(signature, node);
55632         }
55633         function getJsxPropsTypeFromCallSignature(sig, context) {
55634             var propsType = getTypeOfFirstParameterOfSignatureWithFallback(sig, unknownType);
55635             propsType = getJsxManagedAttributesFromLocatedAttributes(context, getJsxNamespaceAt(context), propsType);
55636             var intrinsicAttribs = getJsxType(JsxNames.IntrinsicAttributes, context);
55637             if (intrinsicAttribs !== errorType) {
55638                 propsType = intersectTypes(intrinsicAttribs, propsType);
55639             }
55640             return propsType;
55641         }
55642         function getJsxPropsTypeForSignatureFromMember(sig, forcedLookupLocation) {
55643             if (sig.unionSignatures) {
55644                 // JSX Elements using the legacy `props`-field based lookup (eg, react class components) need to treat the `props` member as an input
55645                 // instead of an output position when resolving the signature. We need to go back to the input signatures of the composite signature,
55646                 // get the type of `props` on each return type individually, and then _intersect them_, rather than union them (as would normally occur
55647                 // 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.
55648                 // The default behavior of `getTypeOfFirstParameterOfSignatureWithFallback` when no `props` member name is defined is much more sane.
55649                 var results = [];
55650                 for (var _i = 0, _a = sig.unionSignatures; _i < _a.length; _i++) {
55651                     var signature = _a[_i];
55652                     var instance = getReturnTypeOfSignature(signature);
55653                     if (isTypeAny(instance)) {
55654                         return instance;
55655                     }
55656                     var propType = getTypeOfPropertyOfType(instance, forcedLookupLocation);
55657                     if (!propType) {
55658                         return;
55659                     }
55660                     results.push(propType);
55661                 }
55662                 return getIntersectionType(results);
55663             }
55664             var instanceType = getReturnTypeOfSignature(sig);
55665             return isTypeAny(instanceType) ? instanceType : getTypeOfPropertyOfType(instanceType, forcedLookupLocation);
55666         }
55667         function getStaticTypeOfReferencedJsxConstructor(context) {
55668             if (isJsxIntrinsicIdentifier(context.tagName)) {
55669                 var result = getIntrinsicAttributesTypeFromJsxOpeningLikeElement(context);
55670                 var fakeSignature = createSignatureForJSXIntrinsic(context, result);
55671                 return getOrCreateTypeFromSignature(fakeSignature);
55672             }
55673             var tagType = checkExpressionCached(context.tagName);
55674             if (tagType.flags & 128 /* StringLiteral */) {
55675                 var result = getIntrinsicAttributesTypeFromStringLiteralType(tagType, context);
55676                 if (!result) {
55677                     return errorType;
55678                 }
55679                 var fakeSignature = createSignatureForJSXIntrinsic(context, result);
55680                 return getOrCreateTypeFromSignature(fakeSignature);
55681             }
55682             return tagType;
55683         }
55684         function getJsxManagedAttributesFromLocatedAttributes(context, ns, attributesType) {
55685             var managedSym = getJsxLibraryManagedAttributes(ns);
55686             if (managedSym) {
55687                 var declaredManagedType = getDeclaredTypeOfSymbol(managedSym);
55688                 var ctorType = getStaticTypeOfReferencedJsxConstructor(context);
55689                 if (ts.length(declaredManagedType.typeParameters) >= 2) {
55690                     var args = fillMissingTypeArguments([ctorType, attributesType], declaredManagedType.typeParameters, 2, ts.isInJSFile(context));
55691                     return createTypeReference(declaredManagedType, args);
55692                 }
55693                 else if (ts.length(declaredManagedType.aliasTypeArguments) >= 2) {
55694                     var args = fillMissingTypeArguments([ctorType, attributesType], declaredManagedType.aliasTypeArguments, 2, ts.isInJSFile(context));
55695                     return getTypeAliasInstantiation(declaredManagedType.aliasSymbol, args);
55696                 }
55697             }
55698             return attributesType;
55699         }
55700         function getJsxPropsTypeFromClassType(sig, context) {
55701             var ns = getJsxNamespaceAt(context);
55702             var forcedLookupLocation = getJsxElementPropertiesName(ns);
55703             var attributesType = forcedLookupLocation === undefined
55704                 // If there is no type ElementAttributesProperty, return the type of the first parameter of the signature, which should be the props type
55705                 ? getTypeOfFirstParameterOfSignatureWithFallback(sig, unknownType)
55706                 : forcedLookupLocation === ""
55707                     // If there is no e.g. 'props' member in ElementAttributesProperty, use the element class type instead
55708                     ? getReturnTypeOfSignature(sig)
55709                     // Otherwise get the type of the property on the signature return type
55710                     : getJsxPropsTypeForSignatureFromMember(sig, forcedLookupLocation);
55711             if (!attributesType) {
55712                 // There is no property named 'props' on this instance type
55713                 if (!!forcedLookupLocation && !!ts.length(context.attributes.properties)) {
55714                     error(context, ts.Diagnostics.JSX_element_class_does_not_support_attributes_because_it_does_not_have_a_0_property, ts.unescapeLeadingUnderscores(forcedLookupLocation));
55715                 }
55716                 return unknownType;
55717             }
55718             attributesType = getJsxManagedAttributesFromLocatedAttributes(context, ns, attributesType);
55719             if (isTypeAny(attributesType)) {
55720                 // Props is of type 'any' or unknown
55721                 return attributesType;
55722             }
55723             else {
55724                 // Normal case -- add in IntrinsicClassElements<T> and IntrinsicElements
55725                 var apparentAttributesType = attributesType;
55726                 var intrinsicClassAttribs = getJsxType(JsxNames.IntrinsicClassAttributes, context);
55727                 if (intrinsicClassAttribs !== errorType) {
55728                     var typeParams = getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(intrinsicClassAttribs.symbol);
55729                     var hostClassType = getReturnTypeOfSignature(sig);
55730                     apparentAttributesType = intersectTypes(typeParams
55731                         ? createTypeReference(intrinsicClassAttribs, fillMissingTypeArguments([hostClassType], typeParams, getMinTypeArgumentCount(typeParams), ts.isInJSFile(context)))
55732                         : intrinsicClassAttribs, apparentAttributesType);
55733                 }
55734                 var intrinsicAttribs = getJsxType(JsxNames.IntrinsicAttributes, context);
55735                 if (intrinsicAttribs !== errorType) {
55736                     apparentAttributesType = intersectTypes(intrinsicAttribs, apparentAttributesType);
55737                 }
55738                 return apparentAttributesType;
55739             }
55740         }
55741         // If the given type is an object or union type with a single signature, and if that signature has at
55742         // least as many parameters as the given function, return the signature. Otherwise return undefined.
55743         function getContextualCallSignature(type, node) {
55744             var signatures = getSignaturesOfType(type, 0 /* Call */);
55745             if (signatures.length === 1) {
55746                 var signature = signatures[0];
55747                 if (!isAritySmaller(signature, node)) {
55748                     return signature;
55749                 }
55750             }
55751         }
55752         /** If the contextual signature has fewer parameters than the function expression, do not use it */
55753         function isAritySmaller(signature, target) {
55754             var targetParameterCount = 0;
55755             for (; targetParameterCount < target.parameters.length; targetParameterCount++) {
55756                 var param = target.parameters[targetParameterCount];
55757                 if (param.initializer || param.questionToken || param.dotDotDotToken || isJSDocOptionalParameter(param)) {
55758                     break;
55759                 }
55760             }
55761             if (target.parameters.length && ts.parameterIsThisKeyword(target.parameters[0])) {
55762                 targetParameterCount--;
55763             }
55764             return !hasEffectiveRestParameter(signature) && getParameterCount(signature) < targetParameterCount;
55765         }
55766         function isFunctionExpressionOrArrowFunction(node) {
55767             return node.kind === 201 /* FunctionExpression */ || node.kind === 202 /* ArrowFunction */;
55768         }
55769         function getContextualSignatureForFunctionLikeDeclaration(node) {
55770             // Only function expressions, arrow functions, and object literal methods are contextually typed.
55771             return isFunctionExpressionOrArrowFunction(node) || ts.isObjectLiteralMethod(node)
55772                 ? getContextualSignature(node)
55773                 : undefined;
55774         }
55775         // Return the contextual signature for a given expression node. A contextual type provides a
55776         // contextual signature if it has a single call signature and if that call signature is non-generic.
55777         // If the contextual type is a union type, get the signature from each type possible and if they are
55778         // all identical ignoring their return type, the result is same signature but with return type as
55779         // union type of return types from these signatures
55780         function getContextualSignature(node) {
55781             ts.Debug.assert(node.kind !== 161 /* MethodDeclaration */ || ts.isObjectLiteralMethod(node));
55782             var typeTagSignature = getSignatureOfTypeTag(node);
55783             if (typeTagSignature) {
55784                 return typeTagSignature;
55785             }
55786             var type = getApparentTypeOfContextualType(node, 1 /* Signature */);
55787             if (!type) {
55788                 return undefined;
55789             }
55790             if (!(type.flags & 1048576 /* Union */)) {
55791                 return getContextualCallSignature(type, node);
55792             }
55793             var signatureList;
55794             var types = type.types;
55795             for (var _i = 0, types_17 = types; _i < types_17.length; _i++) {
55796                 var current = types_17[_i];
55797                 var signature = getContextualCallSignature(current, node);
55798                 if (signature) {
55799                     if (!signatureList) {
55800                         // This signature will contribute to contextual union signature
55801                         signatureList = [signature];
55802                     }
55803                     else if (!compareSignaturesIdentical(signatureList[0], signature, /*partialMatch*/ false, /*ignoreThisTypes*/ true, /*ignoreReturnTypes*/ true, compareTypesIdentical)) {
55804                         // Signatures aren't identical, do not use
55805                         return undefined;
55806                     }
55807                     else {
55808                         // Use this signature for contextual union signature
55809                         signatureList.push(signature);
55810                     }
55811                 }
55812             }
55813             // Result is union of signatures collected (return type is union of return types of this signature set)
55814             if (signatureList) {
55815                 return signatureList.length === 1 ? signatureList[0] : createUnionSignature(signatureList[0], signatureList);
55816             }
55817         }
55818         function checkSpreadExpression(node, checkMode) {
55819             if (languageVersion < 2 /* ES2015 */) {
55820                 checkExternalEmitHelpers(node, compilerOptions.downlevelIteration ? 1536 /* SpreadIncludes */ : 2048 /* SpreadArrays */);
55821             }
55822             var arrayOrIterableType = checkExpression(node.expression, checkMode);
55823             return checkIteratedTypeOrElementType(33 /* Spread */, arrayOrIterableType, undefinedType, node.expression);
55824         }
55825         function hasDefaultValue(node) {
55826             return (node.kind === 191 /* BindingElement */ && !!node.initializer) ||
55827                 (node.kind === 209 /* BinaryExpression */ && node.operatorToken.kind === 62 /* EqualsToken */);
55828         }
55829         function checkArrayLiteral(node, checkMode, forceTuple) {
55830             var elements = node.elements;
55831             var elementCount = elements.length;
55832             var elementTypes = [];
55833             var hasEndingSpreadElement = false;
55834             var hasNonEndingSpreadElement = false;
55835             var contextualType = getApparentTypeOfContextualType(node);
55836             var inDestructuringPattern = ts.isAssignmentTarget(node);
55837             var inConstContext = isConstContext(node);
55838             for (var i = 0; i < elementCount; i++) {
55839                 var e = elements[i];
55840                 var spread = e.kind === 213 /* SpreadElement */ && e.expression;
55841                 var spreadType = spread && checkExpression(spread, checkMode, forceTuple);
55842                 if (spreadType && isTupleType(spreadType)) {
55843                     elementTypes.push.apply(elementTypes, getTypeArguments(spreadType));
55844                     if (spreadType.target.hasRestElement) {
55845                         if (i === elementCount - 1)
55846                             hasEndingSpreadElement = true;
55847                         else
55848                             hasNonEndingSpreadElement = true;
55849                     }
55850                 }
55851                 else {
55852                     if (inDestructuringPattern && spreadType) {
55853                         // Given the following situation:
55854                         //    var c: {};
55855                         //    [...c] = ["", 0];
55856                         //
55857                         // c is represented in the tree as a spread element in an array literal.
55858                         // But c really functions as a rest element, and its purpose is to provide
55859                         // a contextual type for the right hand side of the assignment. Therefore,
55860                         // instead of calling checkExpression on "...c", which will give an error
55861                         // if c is not iterable/array-like, we need to act as if we are trying to
55862                         // get the contextual element type from it. So we do something similar to
55863                         // getContextualTypeForElementExpression, which will crucially not error
55864                         // if there is no index type / iterated type.
55865                         var restElementType = getIndexTypeOfType(spreadType, 1 /* Number */) ||
55866                             getIteratedTypeOrElementType(65 /* Destructuring */, spreadType, undefinedType, /*errorNode*/ undefined, /*checkAssignability*/ false);
55867                         if (restElementType) {
55868                             elementTypes.push(restElementType);
55869                         }
55870                     }
55871                     else {
55872                         var elementContextualType = getContextualTypeForElementExpression(contextualType, elementTypes.length);
55873                         var type = checkExpressionForMutableLocation(e, checkMode, elementContextualType, forceTuple);
55874                         elementTypes.push(type);
55875                     }
55876                     if (spread) { // tuples are done above, so these are only arrays
55877                         if (i === elementCount - 1)
55878                             hasEndingSpreadElement = true;
55879                         else
55880                             hasNonEndingSpreadElement = true;
55881                     }
55882                 }
55883             }
55884             if (!hasNonEndingSpreadElement) {
55885                 var minLength = elementTypes.length - (hasEndingSpreadElement ? 1 : 0);
55886                 // If array literal is actually a destructuring pattern, mark it as an implied type. We do this such
55887                 // that we get the same behavior for "var [x, y] = []" and "[x, y] = []".
55888                 var tupleResult = void 0;
55889                 if (inDestructuringPattern && minLength > 0) {
55890                     var type = cloneTypeReference(createTupleType(elementTypes, minLength, hasEndingSpreadElement));
55891                     type.pattern = node;
55892                     return type;
55893                 }
55894                 else if (tupleResult = getArrayLiteralTupleTypeIfApplicable(elementTypes, contextualType, hasEndingSpreadElement, elementTypes.length, inConstContext)) {
55895                     return createArrayLiteralType(tupleResult);
55896                 }
55897                 else if (forceTuple) {
55898                     return createArrayLiteralType(createTupleType(elementTypes, minLength, hasEndingSpreadElement));
55899                 }
55900             }
55901             return createArrayLiteralType(createArrayType(elementTypes.length ?
55902                 getUnionType(elementTypes, 2 /* Subtype */) :
55903                 strictNullChecks ? implicitNeverType : undefinedWideningType, inConstContext));
55904         }
55905         function createArrayLiteralType(type) {
55906             if (!(ts.getObjectFlags(type) & 4 /* Reference */)) {
55907                 return type;
55908             }
55909             var literalType = type.literalType;
55910             if (!literalType) {
55911                 literalType = type.literalType = cloneTypeReference(type);
55912                 literalType.objectFlags |= 65536 /* ArrayLiteral */ | 1048576 /* ContainsObjectOrArrayLiteral */;
55913             }
55914             return literalType;
55915         }
55916         function getArrayLiteralTupleTypeIfApplicable(elementTypes, contextualType, hasRestElement, elementCount, readonly) {
55917             if (elementCount === void 0) { elementCount = elementTypes.length; }
55918             if (readonly === void 0) { readonly = false; }
55919             // Infer a tuple type when the contextual type is or contains a tuple-like type
55920             if (readonly || (contextualType && forEachType(contextualType, isTupleLikeType))) {
55921                 return createTupleType(elementTypes, elementCount - (hasRestElement ? 1 : 0), hasRestElement, readonly);
55922             }
55923         }
55924         function isNumericName(name) {
55925             switch (name.kind) {
55926                 case 154 /* ComputedPropertyName */:
55927                     return isNumericComputedName(name);
55928                 case 75 /* Identifier */:
55929                     return isNumericLiteralName(name.escapedText);
55930                 case 8 /* NumericLiteral */:
55931                 case 10 /* StringLiteral */:
55932                     return isNumericLiteralName(name.text);
55933                 default:
55934                     return false;
55935             }
55936         }
55937         function isNumericComputedName(name) {
55938             // It seems odd to consider an expression of type Any to result in a numeric name,
55939             // but this behavior is consistent with checkIndexedAccess
55940             return isTypeAssignableToKind(checkComputedPropertyName(name), 296 /* NumberLike */);
55941         }
55942         function isInfinityOrNaNString(name) {
55943             return name === "Infinity" || name === "-Infinity" || name === "NaN";
55944         }
55945         function isNumericLiteralName(name) {
55946             // The intent of numeric names is that
55947             //     - they are names with text in a numeric form, and that
55948             //     - setting properties/indexing with them is always equivalent to doing so with the numeric literal 'numLit',
55949             //         acquired by applying the abstract 'ToNumber' operation on the name's text.
55950             //
55951             // The subtlety is in the latter portion, as we cannot reliably say that anything that looks like a numeric literal is a numeric name.
55952             // In fact, it is the case that the text of the name must be equal to 'ToString(numLit)' for this to hold.
55953             //
55954             // Consider the property name '"0xF00D"'. When one indexes with '0xF00D', they are actually indexing with the value of 'ToString(0xF00D)'
55955             // according to the ECMAScript specification, so it is actually as if the user indexed with the string '"61453"'.
55956             // Thus, the text of all numeric literals equivalent to '61543' such as '0xF00D', '0xf00D', '0170015', etc. are not valid numeric names
55957             // because their 'ToString' representation is not equal to their original text.
55958             // This is motivated by ECMA-262 sections 9.3.1, 9.8.1, 11.1.5, and 11.2.1.
55959             //
55960             // Here, we test whether 'ToString(ToNumber(name))' is exactly equal to 'name'.
55961             // The '+' prefix operator is equivalent here to applying the abstract ToNumber operation.
55962             // Applying the 'toString()' method on a number gives us the abstract ToString operation on a number.
55963             //
55964             // Note that this accepts the values 'Infinity', '-Infinity', and 'NaN', and that this is intentional.
55965             // This is desired behavior, because when indexing with them as numeric entities, you are indexing
55966             // with the strings '"Infinity"', '"-Infinity"', and '"NaN"' respectively.
55967             return (+name).toString() === name;
55968         }
55969         function checkComputedPropertyName(node) {
55970             var links = getNodeLinks(node.expression);
55971             if (!links.resolvedType) {
55972                 links.resolvedType = checkExpression(node.expression);
55973                 // This will allow types number, string, symbol or any. It will also allow enums, the unknown
55974                 // type, and any union of these types (like string | number).
55975                 if (links.resolvedType.flags & 98304 /* Nullable */ ||
55976                     !isTypeAssignableToKind(links.resolvedType, 132 /* StringLike */ | 296 /* NumberLike */ | 12288 /* ESSymbolLike */) &&
55977                         !isTypeAssignableTo(links.resolvedType, stringNumberSymbolType)) {
55978                     error(node, ts.Diagnostics.A_computed_property_name_must_be_of_type_string_number_symbol_or_any);
55979                 }
55980                 else {
55981                     checkThatExpressionIsProperSymbolReference(node.expression, links.resolvedType, /*reportError*/ true);
55982                 }
55983             }
55984             return links.resolvedType;
55985         }
55986         function getObjectLiteralIndexInfo(node, offset, properties, kind) {
55987             var propTypes = [];
55988             for (var i = 0; i < properties.length; i++) {
55989                 if (kind === 0 /* String */ || isNumericName(node.properties[i + offset].name)) {
55990                     propTypes.push(getTypeOfSymbol(properties[i]));
55991                 }
55992             }
55993             var unionType = propTypes.length ? getUnionType(propTypes, 2 /* Subtype */) : undefinedType;
55994             return createIndexInfo(unionType, isConstContext(node));
55995         }
55996         function getImmediateAliasedSymbol(symbol) {
55997             ts.Debug.assert((symbol.flags & 2097152 /* Alias */) !== 0, "Should only get Alias here.");
55998             var links = getSymbolLinks(symbol);
55999             if (!links.immediateTarget) {
56000                 var node = getDeclarationOfAliasSymbol(symbol);
56001                 if (!node)
56002                     return ts.Debug.fail();
56003                 links.immediateTarget = getTargetOfAliasDeclaration(node, /*dontRecursivelyResolve*/ true);
56004             }
56005             return links.immediateTarget;
56006         }
56007         function checkObjectLiteral(node, checkMode) {
56008             var inDestructuringPattern = ts.isAssignmentTarget(node);
56009             // Grammar checking
56010             checkGrammarObjectLiteralExpression(node, inDestructuringPattern);
56011             var allPropertiesTable = strictNullChecks ? ts.createSymbolTable() : undefined;
56012             var propertiesTable = ts.createSymbolTable();
56013             var propertiesArray = [];
56014             var spread = emptyObjectType;
56015             var contextualType = getApparentTypeOfContextualType(node);
56016             var contextualTypeHasPattern = contextualType && contextualType.pattern &&
56017                 (contextualType.pattern.kind === 189 /* ObjectBindingPattern */ || contextualType.pattern.kind === 193 /* ObjectLiteralExpression */);
56018             var inConstContext = isConstContext(node);
56019             var checkFlags = inConstContext ? 8 /* Readonly */ : 0;
56020             var isInJavascript = ts.isInJSFile(node) && !ts.isInJsonFile(node);
56021             var enumTag = ts.getJSDocEnumTag(node);
56022             var isJSObjectLiteral = !contextualType && isInJavascript && !enumTag;
56023             var objectFlags = freshObjectLiteralFlag;
56024             var patternWithComputedProperties = false;
56025             var hasComputedStringProperty = false;
56026             var hasComputedNumberProperty = false;
56027             // Spreads may cause an early bail; ensure computed names are always checked (this is cached)
56028             // As otherwise they may not be checked until exports for the type at this position are retrieved,
56029             // which may never occur.
56030             for (var _i = 0, _a = node.properties; _i < _a.length; _i++) {
56031                 var elem = _a[_i];
56032                 if (elem.name && ts.isComputedPropertyName(elem.name) && !ts.isWellKnownSymbolSyntactically(elem.name)) {
56033                     checkComputedPropertyName(elem.name);
56034                 }
56035             }
56036             var offset = 0;
56037             for (var i = 0; i < node.properties.length; i++) {
56038                 var memberDecl = node.properties[i];
56039                 var member = getSymbolOfNode(memberDecl);
56040                 var computedNameType = memberDecl.name && memberDecl.name.kind === 154 /* ComputedPropertyName */ && !ts.isWellKnownSymbolSyntactically(memberDecl.name.expression) ?
56041                     checkComputedPropertyName(memberDecl.name) : undefined;
56042                 if (memberDecl.kind === 281 /* PropertyAssignment */ ||
56043                     memberDecl.kind === 282 /* ShorthandPropertyAssignment */ ||
56044                     ts.isObjectLiteralMethod(memberDecl)) {
56045                     var type = memberDecl.kind === 281 /* PropertyAssignment */ ? checkPropertyAssignment(memberDecl, checkMode) :
56046                         memberDecl.kind === 282 /* ShorthandPropertyAssignment */ ? checkExpressionForMutableLocation(memberDecl.name, checkMode) :
56047                             checkObjectLiteralMethod(memberDecl, checkMode);
56048                     if (isInJavascript) {
56049                         var jsDocType = getTypeForDeclarationFromJSDocComment(memberDecl);
56050                         if (jsDocType) {
56051                             checkTypeAssignableTo(type, jsDocType, memberDecl);
56052                             type = jsDocType;
56053                         }
56054                         else if (enumTag && enumTag.typeExpression) {
56055                             checkTypeAssignableTo(type, getTypeFromTypeNode(enumTag.typeExpression), memberDecl);
56056                         }
56057                     }
56058                     objectFlags |= ts.getObjectFlags(type) & 3670016 /* PropagatingFlags */;
56059                     var nameType = computedNameType && isTypeUsableAsPropertyName(computedNameType) ? computedNameType : undefined;
56060                     var prop = nameType ?
56061                         createSymbol(4 /* Property */ | member.flags, getPropertyNameFromType(nameType), checkFlags | 4096 /* Late */) :
56062                         createSymbol(4 /* Property */ | member.flags, member.escapedName, checkFlags);
56063                     if (nameType) {
56064                         prop.nameType = nameType;
56065                     }
56066                     if (inDestructuringPattern) {
56067                         // If object literal is an assignment pattern and if the assignment pattern specifies a default value
56068                         // for the property, make the property optional.
56069                         var isOptional = (memberDecl.kind === 281 /* PropertyAssignment */ && hasDefaultValue(memberDecl.initializer)) ||
56070                             (memberDecl.kind === 282 /* ShorthandPropertyAssignment */ && memberDecl.objectAssignmentInitializer);
56071                         if (isOptional) {
56072                             prop.flags |= 16777216 /* Optional */;
56073                         }
56074                     }
56075                     else if (contextualTypeHasPattern && !(ts.getObjectFlags(contextualType) & 512 /* ObjectLiteralPatternWithComputedProperties */)) {
56076                         // If object literal is contextually typed by the implied type of a binding pattern, and if the
56077                         // binding pattern specifies a default value for the property, make the property optional.
56078                         var impliedProp = getPropertyOfType(contextualType, member.escapedName);
56079                         if (impliedProp) {
56080                             prop.flags |= impliedProp.flags & 16777216 /* Optional */;
56081                         }
56082                         else if (!compilerOptions.suppressExcessPropertyErrors && !getIndexInfoOfType(contextualType, 0 /* String */)) {
56083                             error(memberDecl.name, ts.Diagnostics.Object_literal_may_only_specify_known_properties_and_0_does_not_exist_in_type_1, symbolToString(member), typeToString(contextualType));
56084                         }
56085                     }
56086                     prop.declarations = member.declarations;
56087                     prop.parent = member.parent;
56088                     if (member.valueDeclaration) {
56089                         prop.valueDeclaration = member.valueDeclaration;
56090                     }
56091                     prop.type = type;
56092                     prop.target = member;
56093                     member = prop;
56094                     allPropertiesTable === null || allPropertiesTable === void 0 ? void 0 : allPropertiesTable.set(prop.escapedName, prop);
56095                 }
56096                 else if (memberDecl.kind === 283 /* SpreadAssignment */) {
56097                     if (languageVersion < 2 /* ES2015 */) {
56098                         checkExternalEmitHelpers(memberDecl, 2 /* Assign */);
56099                     }
56100                     if (propertiesArray.length > 0) {
56101                         spread = getSpreadType(spread, createObjectLiteralType(), node.symbol, objectFlags, inConstContext);
56102                         propertiesArray = [];
56103                         propertiesTable = ts.createSymbolTable();
56104                         hasComputedStringProperty = false;
56105                         hasComputedNumberProperty = false;
56106                     }
56107                     var type = getReducedType(checkExpression(memberDecl.expression));
56108                     if (!isValidSpreadType(type)) {
56109                         error(memberDecl, ts.Diagnostics.Spread_types_may_only_be_created_from_object_types);
56110                         return errorType;
56111                     }
56112                     if (allPropertiesTable) {
56113                         checkSpreadPropOverrides(type, allPropertiesTable, memberDecl);
56114                     }
56115                     spread = getSpreadType(spread, type, node.symbol, objectFlags, inConstContext);
56116                     offset = i + 1;
56117                     continue;
56118                 }
56119                 else {
56120                     // TypeScript 1.0 spec (April 2014)
56121                     // A get accessor declaration is processed in the same manner as
56122                     // an ordinary function declaration(section 6.1) with no parameters.
56123                     // A set accessor declaration is processed in the same manner
56124                     // as an ordinary function declaration with a single parameter and a Void return type.
56125                     ts.Debug.assert(memberDecl.kind === 163 /* GetAccessor */ || memberDecl.kind === 164 /* SetAccessor */);
56126                     checkNodeDeferred(memberDecl);
56127                 }
56128                 if (computedNameType && !(computedNameType.flags & 8576 /* StringOrNumberLiteralOrUnique */)) {
56129                     if (isTypeAssignableTo(computedNameType, stringNumberSymbolType)) {
56130                         if (isTypeAssignableTo(computedNameType, numberType)) {
56131                             hasComputedNumberProperty = true;
56132                         }
56133                         else {
56134                             hasComputedStringProperty = true;
56135                         }
56136                         if (inDestructuringPattern) {
56137                             patternWithComputedProperties = true;
56138                         }
56139                     }
56140                 }
56141                 else {
56142                     propertiesTable.set(member.escapedName, member);
56143                 }
56144                 propertiesArray.push(member);
56145             }
56146             // If object literal is contextually typed by the implied type of a binding pattern, augment the result
56147             // type with those properties for which the binding pattern specifies a default value.
56148             // If the object literal is spread into another object literal, skip this step and let the top-level object
56149             // literal handle it instead.
56150             if (contextualTypeHasPattern && node.parent.kind !== 283 /* SpreadAssignment */) {
56151                 for (var _b = 0, _c = getPropertiesOfType(contextualType); _b < _c.length; _b++) {
56152                     var prop = _c[_b];
56153                     if (!propertiesTable.get(prop.escapedName) && !getPropertyOfType(spread, prop.escapedName)) {
56154                         if (!(prop.flags & 16777216 /* Optional */)) {
56155                             error(prop.valueDeclaration || prop.bindingElement, ts.Diagnostics.Initializer_provides_no_value_for_this_binding_element_and_the_binding_element_has_no_default_value);
56156                         }
56157                         propertiesTable.set(prop.escapedName, prop);
56158                         propertiesArray.push(prop);
56159                     }
56160                 }
56161             }
56162             if (spread !== emptyObjectType) {
56163                 if (propertiesArray.length > 0) {
56164                     spread = getSpreadType(spread, createObjectLiteralType(), node.symbol, objectFlags, inConstContext);
56165                     propertiesArray = [];
56166                     propertiesTable = ts.createSymbolTable();
56167                     hasComputedStringProperty = false;
56168                     hasComputedNumberProperty = false;
56169                 }
56170                 // remap the raw emptyObjectType fed in at the top into a fresh empty object literal type, unique to this use site
56171                 return mapType(spread, function (t) { return t === emptyObjectType ? createObjectLiteralType() : t; });
56172             }
56173             return createObjectLiteralType();
56174             function createObjectLiteralType() {
56175                 var stringIndexInfo = hasComputedStringProperty ? getObjectLiteralIndexInfo(node, offset, propertiesArray, 0 /* String */) : undefined;
56176                 var numberIndexInfo = hasComputedNumberProperty ? getObjectLiteralIndexInfo(node, offset, propertiesArray, 1 /* Number */) : undefined;
56177                 var result = createAnonymousType(node.symbol, propertiesTable, ts.emptyArray, ts.emptyArray, stringIndexInfo, numberIndexInfo);
56178                 result.objectFlags |= objectFlags | 128 /* ObjectLiteral */ | 1048576 /* ContainsObjectOrArrayLiteral */;
56179                 if (isJSObjectLiteral) {
56180                     result.objectFlags |= 16384 /* JSLiteral */;
56181                 }
56182                 if (patternWithComputedProperties) {
56183                     result.objectFlags |= 512 /* ObjectLiteralPatternWithComputedProperties */;
56184                 }
56185                 if (inDestructuringPattern) {
56186                     result.pattern = node;
56187                 }
56188                 return result;
56189             }
56190         }
56191         function isValidSpreadType(type) {
56192             if (type.flags & 63176704 /* Instantiable */) {
56193                 var constraint = getBaseConstraintOfType(type);
56194                 if (constraint !== undefined) {
56195                     return isValidSpreadType(constraint);
56196                 }
56197             }
56198             return !!(type.flags & (1 /* Any */ | 67108864 /* NonPrimitive */ | 524288 /* Object */ | 58982400 /* InstantiableNonPrimitive */) ||
56199                 getFalsyFlags(type) & 117632 /* DefinitelyFalsy */ && isValidSpreadType(removeDefinitelyFalsyTypes(type)) ||
56200                 type.flags & 3145728 /* UnionOrIntersection */ && ts.every(type.types, isValidSpreadType));
56201         }
56202         function checkJsxSelfClosingElementDeferred(node) {
56203             checkJsxOpeningLikeElementOrOpeningFragment(node);
56204             resolveUntypedCall(node); // ensure type arguments and parameters are typechecked, even if there is an arity error
56205         }
56206         function checkJsxSelfClosingElement(node, _checkMode) {
56207             checkNodeDeferred(node);
56208             return getJsxElementTypeAt(node) || anyType;
56209         }
56210         function checkJsxElementDeferred(node) {
56211             // Check attributes
56212             checkJsxOpeningLikeElementOrOpeningFragment(node.openingElement);
56213             // Perform resolution on the closing tag so that rename/go to definition/etc work
56214             if (isJsxIntrinsicIdentifier(node.closingElement.tagName)) {
56215                 getIntrinsicTagSymbol(node.closingElement);
56216             }
56217             else {
56218                 checkExpression(node.closingElement.tagName);
56219             }
56220             checkJsxChildren(node);
56221         }
56222         function checkJsxElement(node, _checkMode) {
56223             checkNodeDeferred(node);
56224             return getJsxElementTypeAt(node) || anyType;
56225         }
56226         function checkJsxFragment(node) {
56227             checkJsxOpeningLikeElementOrOpeningFragment(node.openingFragment);
56228             if (compilerOptions.jsx === 2 /* React */ && (compilerOptions.jsxFactory || ts.getSourceFileOfNode(node).pragmas.has("jsx"))) {
56229                 error(node, compilerOptions.jsxFactory
56230                     ? ts.Diagnostics.JSX_fragment_is_not_supported_when_using_jsxFactory
56231                     : ts.Diagnostics.JSX_fragment_is_not_supported_when_using_an_inline_JSX_factory_pragma);
56232             }
56233             checkJsxChildren(node);
56234             return getJsxElementTypeAt(node) || anyType;
56235         }
56236         /**
56237          * Returns true iff the JSX element name would be a valid JS identifier, ignoring restrictions about keywords not being identifiers
56238          */
56239         function isUnhyphenatedJsxName(name) {
56240             // - is the only character supported in JSX attribute names that isn't valid in JavaScript identifiers
56241             return !ts.stringContains(name, "-");
56242         }
56243         /**
56244          * Returns true iff React would emit this tag name as a string rather than an identifier or qualified name
56245          */
56246         function isJsxIntrinsicIdentifier(tagName) {
56247             return tagName.kind === 75 /* Identifier */ && ts.isIntrinsicJsxName(tagName.escapedText);
56248         }
56249         function checkJsxAttribute(node, checkMode) {
56250             return node.initializer
56251                 ? checkExpressionForMutableLocation(node.initializer, checkMode)
56252                 : trueType; // <Elem attr /> is sugar for <Elem attr={true} />
56253         }
56254         /**
56255          * Get attributes type of the JSX opening-like element. The result is from resolving "attributes" property of the opening-like element.
56256          *
56257          * @param openingLikeElement a JSX opening-like element
56258          * @param filter a function to remove attributes that will not participate in checking whether attributes are assignable
56259          * @return an anonymous type (similar to the one returned by checkObjectLiteral) in which its properties are attributes property.
56260          * @remarks Because this function calls getSpreadType, it needs to use the same checks as checkObjectLiteral,
56261          * which also calls getSpreadType.
56262          */
56263         function createJsxAttributesTypeFromAttributesProperty(openingLikeElement, checkMode) {
56264             var attributes = openingLikeElement.attributes;
56265             var allAttributesTable = strictNullChecks ? ts.createSymbolTable() : undefined;
56266             var attributesTable = ts.createSymbolTable();
56267             var spread = emptyJsxObjectType;
56268             var hasSpreadAnyType = false;
56269             var typeToIntersect;
56270             var explicitlySpecifyChildrenAttribute = false;
56271             var objectFlags = 4096 /* JsxAttributes */;
56272             var jsxChildrenPropertyName = getJsxElementChildrenPropertyName(getJsxNamespaceAt(openingLikeElement));
56273             for (var _i = 0, _a = attributes.properties; _i < _a.length; _i++) {
56274                 var attributeDecl = _a[_i];
56275                 var member = attributeDecl.symbol;
56276                 if (ts.isJsxAttribute(attributeDecl)) {
56277                     var exprType = checkJsxAttribute(attributeDecl, checkMode);
56278                     objectFlags |= ts.getObjectFlags(exprType) & 3670016 /* PropagatingFlags */;
56279                     var attributeSymbol = createSymbol(4 /* Property */ | 33554432 /* Transient */ | member.flags, member.escapedName);
56280                     attributeSymbol.declarations = member.declarations;
56281                     attributeSymbol.parent = member.parent;
56282                     if (member.valueDeclaration) {
56283                         attributeSymbol.valueDeclaration = member.valueDeclaration;
56284                     }
56285                     attributeSymbol.type = exprType;
56286                     attributeSymbol.target = member;
56287                     attributesTable.set(attributeSymbol.escapedName, attributeSymbol);
56288                     allAttributesTable === null || allAttributesTable === void 0 ? void 0 : allAttributesTable.set(attributeSymbol.escapedName, attributeSymbol);
56289                     if (attributeDecl.name.escapedText === jsxChildrenPropertyName) {
56290                         explicitlySpecifyChildrenAttribute = true;
56291                     }
56292                 }
56293                 else {
56294                     ts.Debug.assert(attributeDecl.kind === 275 /* JsxSpreadAttribute */);
56295                     if (attributesTable.size > 0) {
56296                         spread = getSpreadType(spread, createJsxAttributesType(), attributes.symbol, objectFlags, /*readonly*/ false);
56297                         attributesTable = ts.createSymbolTable();
56298                     }
56299                     var exprType = getReducedType(checkExpressionCached(attributeDecl.expression, checkMode));
56300                     if (isTypeAny(exprType)) {
56301                         hasSpreadAnyType = true;
56302                     }
56303                     if (isValidSpreadType(exprType)) {
56304                         spread = getSpreadType(spread, exprType, attributes.symbol, objectFlags, /*readonly*/ false);
56305                         if (allAttributesTable) {
56306                             checkSpreadPropOverrides(exprType, allAttributesTable, attributeDecl);
56307                         }
56308                     }
56309                     else {
56310                         typeToIntersect = typeToIntersect ? getIntersectionType([typeToIntersect, exprType]) : exprType;
56311                     }
56312                 }
56313             }
56314             if (!hasSpreadAnyType) {
56315                 if (attributesTable.size > 0) {
56316                     spread = getSpreadType(spread, createJsxAttributesType(), attributes.symbol, objectFlags, /*readonly*/ false);
56317                 }
56318             }
56319             // Handle children attribute
56320             var parent = openingLikeElement.parent.kind === 266 /* JsxElement */ ? openingLikeElement.parent : undefined;
56321             // We have to check that openingElement of the parent is the one we are visiting as this may not be true for selfClosingElement
56322             if (parent && parent.openingElement === openingLikeElement && parent.children.length > 0) {
56323                 var childrenTypes = checkJsxChildren(parent, checkMode);
56324                 if (!hasSpreadAnyType && jsxChildrenPropertyName && jsxChildrenPropertyName !== "") {
56325                     // Error if there is a attribute named "children" explicitly specified and children element.
56326                     // This is because children element will overwrite the value from attributes.
56327                     // Note: we will not warn "children" attribute overwritten if "children" attribute is specified in object spread.
56328                     if (explicitlySpecifyChildrenAttribute) {
56329                         error(attributes, ts.Diagnostics._0_are_specified_twice_The_attribute_named_0_will_be_overwritten, ts.unescapeLeadingUnderscores(jsxChildrenPropertyName));
56330                     }
56331                     var contextualType = getApparentTypeOfContextualType(openingLikeElement.attributes);
56332                     var childrenContextualType = contextualType && getTypeOfPropertyOfContextualType(contextualType, jsxChildrenPropertyName);
56333                     // 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
56334                     var childrenPropSymbol = createSymbol(4 /* Property */ | 33554432 /* Transient */, jsxChildrenPropertyName);
56335                     childrenPropSymbol.type = childrenTypes.length === 1 ?
56336                         childrenTypes[0] :
56337                         (getArrayLiteralTupleTypeIfApplicable(childrenTypes, childrenContextualType, /*hasRestElement*/ false) || createArrayType(getUnionType(childrenTypes)));
56338                     // Fake up a property declaration for the children
56339                     childrenPropSymbol.valueDeclaration = ts.createPropertySignature(/*modifiers*/ undefined, ts.unescapeLeadingUnderscores(jsxChildrenPropertyName), /*questionToken*/ undefined, /*type*/ undefined, /*initializer*/ undefined);
56340                     childrenPropSymbol.valueDeclaration.parent = attributes;
56341                     childrenPropSymbol.valueDeclaration.symbol = childrenPropSymbol;
56342                     var childPropMap = ts.createSymbolTable();
56343                     childPropMap.set(jsxChildrenPropertyName, childrenPropSymbol);
56344                     spread = getSpreadType(spread, createAnonymousType(attributes.symbol, childPropMap, ts.emptyArray, ts.emptyArray, /*stringIndexInfo*/ undefined, /*numberIndexInfo*/ undefined), attributes.symbol, objectFlags, /*readonly*/ false);
56345                 }
56346             }
56347             if (hasSpreadAnyType) {
56348                 return anyType;
56349             }
56350             if (typeToIntersect && spread !== emptyJsxObjectType) {
56351                 return getIntersectionType([typeToIntersect, spread]);
56352             }
56353             return typeToIntersect || (spread === emptyJsxObjectType ? createJsxAttributesType() : spread);
56354             /**
56355              * Create anonymous type from given attributes symbol table.
56356              * @param symbol a symbol of JsxAttributes containing attributes corresponding to attributesTable
56357              * @param attributesTable a symbol table of attributes property
56358              */
56359             function createJsxAttributesType() {
56360                 objectFlags |= freshObjectLiteralFlag;
56361                 var result = createAnonymousType(attributes.symbol, attributesTable, ts.emptyArray, ts.emptyArray, /*stringIndexInfo*/ undefined, /*numberIndexInfo*/ undefined);
56362                 result.objectFlags |= objectFlags | 128 /* ObjectLiteral */ | 1048576 /* ContainsObjectOrArrayLiteral */;
56363                 return result;
56364             }
56365         }
56366         function checkJsxChildren(node, checkMode) {
56367             var childrenTypes = [];
56368             for (var _i = 0, _a = node.children; _i < _a.length; _i++) {
56369                 var child = _a[_i];
56370                 // In React, JSX text that contains only whitespaces will be ignored so we don't want to type-check that
56371                 // because then type of children property will have constituent of string type.
56372                 if (child.kind === 11 /* JsxText */) {
56373                     if (!child.containsOnlyTriviaWhiteSpaces) {
56374                         childrenTypes.push(stringType);
56375                     }
56376                 }
56377                 else {
56378                     childrenTypes.push(checkExpressionForMutableLocation(child, checkMode));
56379                 }
56380             }
56381             return childrenTypes;
56382         }
56383         function checkSpreadPropOverrides(type, props, spread) {
56384             for (var _i = 0, _a = getPropertiesOfType(type); _i < _a.length; _i++) {
56385                 var right = _a[_i];
56386                 var left = props.get(right.escapedName);
56387                 var rightType = getTypeOfSymbol(right);
56388                 if (left && !maybeTypeOfKind(rightType, 98304 /* Nullable */) && !(maybeTypeOfKind(rightType, 3 /* AnyOrUnknown */) && right.flags & 16777216 /* Optional */)) {
56389                     var diagnostic = error(left.valueDeclaration, ts.Diagnostics._0_is_specified_more_than_once_so_this_usage_will_be_overwritten, ts.unescapeLeadingUnderscores(left.escapedName));
56390                     ts.addRelatedInfo(diagnostic, ts.createDiagnosticForNode(spread, ts.Diagnostics.This_spread_always_overwrites_this_property));
56391                 }
56392             }
56393         }
56394         /**
56395          * Check attributes property of opening-like element. This function is called during chooseOverload to get call signature of a JSX opening-like element.
56396          * (See "checkApplicableSignatureForJsxOpeningLikeElement" for how the function is used)
56397          * @param node a JSXAttributes to be resolved of its type
56398          */
56399         function checkJsxAttributes(node, checkMode) {
56400             return createJsxAttributesTypeFromAttributesProperty(node.parent, checkMode);
56401         }
56402         function getJsxType(name, location) {
56403             var namespace = getJsxNamespaceAt(location);
56404             var exports = namespace && getExportsOfSymbol(namespace);
56405             var typeSymbol = exports && getSymbol(exports, name, 788968 /* Type */);
56406             return typeSymbol ? getDeclaredTypeOfSymbol(typeSymbol) : errorType;
56407         }
56408         /**
56409          * Looks up an intrinsic tag name and returns a symbol that either points to an intrinsic
56410          * property (in which case nodeLinks.jsxFlags will be IntrinsicNamedElement) or an intrinsic
56411          * string index signature (in which case nodeLinks.jsxFlags will be IntrinsicIndexedElement).
56412          * May also return unknownSymbol if both of these lookups fail.
56413          */
56414         function getIntrinsicTagSymbol(node) {
56415             var links = getNodeLinks(node);
56416             if (!links.resolvedSymbol) {
56417                 var intrinsicElementsType = getJsxType(JsxNames.IntrinsicElements, node);
56418                 if (intrinsicElementsType !== errorType) {
56419                     // Property case
56420                     if (!ts.isIdentifier(node.tagName))
56421                         return ts.Debug.fail();
56422                     var intrinsicProp = getPropertyOfType(intrinsicElementsType, node.tagName.escapedText);
56423                     if (intrinsicProp) {
56424                         links.jsxFlags |= 1 /* IntrinsicNamedElement */;
56425                         return links.resolvedSymbol = intrinsicProp;
56426                     }
56427                     // Intrinsic string indexer case
56428                     var indexSignatureType = getIndexTypeOfType(intrinsicElementsType, 0 /* String */);
56429                     if (indexSignatureType) {
56430                         links.jsxFlags |= 2 /* IntrinsicIndexedElement */;
56431                         return links.resolvedSymbol = intrinsicElementsType.symbol;
56432                     }
56433                     // Wasn't found
56434                     error(node, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.idText(node.tagName), "JSX." + JsxNames.IntrinsicElements);
56435                     return links.resolvedSymbol = unknownSymbol;
56436                 }
56437                 else {
56438                     if (noImplicitAny) {
56439                         error(node, ts.Diagnostics.JSX_element_implicitly_has_type_any_because_no_interface_JSX_0_exists, ts.unescapeLeadingUnderscores(JsxNames.IntrinsicElements));
56440                     }
56441                     return links.resolvedSymbol = unknownSymbol;
56442                 }
56443             }
56444             return links.resolvedSymbol;
56445         }
56446         function getJsxNamespaceAt(location) {
56447             var links = location && getNodeLinks(location);
56448             if (links && links.jsxNamespace) {
56449                 return links.jsxNamespace;
56450             }
56451             if (!links || links.jsxNamespace !== false) {
56452                 var namespaceName = getJsxNamespace(location);
56453                 var resolvedNamespace = resolveName(location, namespaceName, 1920 /* Namespace */, /*diagnosticMessage*/ undefined, namespaceName, /*isUse*/ false);
56454                 if (resolvedNamespace) {
56455                     var candidate = resolveSymbol(getSymbol(getExportsOfSymbol(resolveSymbol(resolvedNamespace)), JsxNames.JSX, 1920 /* Namespace */));
56456                     if (candidate) {
56457                         if (links) {
56458                             links.jsxNamespace = candidate;
56459                         }
56460                         return candidate;
56461                     }
56462                     if (links) {
56463                         links.jsxNamespace = false;
56464                     }
56465                 }
56466             }
56467             // JSX global fallback
56468             return getGlobalSymbol(JsxNames.JSX, 1920 /* Namespace */, /*diagnosticMessage*/ undefined); // TODO: GH#18217
56469         }
56470         /**
56471          * Look into JSX namespace and then look for container with matching name as nameOfAttribPropContainer.
56472          * Get a single property from that container if existed. Report an error if there are more than one property.
56473          *
56474          * @param nameOfAttribPropContainer a string of value JsxNames.ElementAttributesPropertyNameContainer or JsxNames.ElementChildrenAttributeNameContainer
56475          *          if other string is given or the container doesn't exist, return undefined.
56476          */
56477         function getNameFromJsxElementAttributesContainer(nameOfAttribPropContainer, jsxNamespace) {
56478             // JSX.ElementAttributesProperty | JSX.ElementChildrenAttribute [symbol]
56479             var jsxElementAttribPropInterfaceSym = jsxNamespace && getSymbol(jsxNamespace.exports, nameOfAttribPropContainer, 788968 /* Type */);
56480             // JSX.ElementAttributesProperty | JSX.ElementChildrenAttribute [type]
56481             var jsxElementAttribPropInterfaceType = jsxElementAttribPropInterfaceSym && getDeclaredTypeOfSymbol(jsxElementAttribPropInterfaceSym);
56482             // The properties of JSX.ElementAttributesProperty | JSX.ElementChildrenAttribute
56483             var propertiesOfJsxElementAttribPropInterface = jsxElementAttribPropInterfaceType && getPropertiesOfType(jsxElementAttribPropInterfaceType);
56484             if (propertiesOfJsxElementAttribPropInterface) {
56485                 // Element Attributes has zero properties, so the element attributes type will be the class instance type
56486                 if (propertiesOfJsxElementAttribPropInterface.length === 0) {
56487                     return "";
56488                 }
56489                 // Element Attributes has one property, so the element attributes type will be the type of the corresponding
56490                 // property of the class instance type
56491                 else if (propertiesOfJsxElementAttribPropInterface.length === 1) {
56492                     return propertiesOfJsxElementAttribPropInterface[0].escapedName;
56493                 }
56494                 else if (propertiesOfJsxElementAttribPropInterface.length > 1) {
56495                     // More than one property on ElementAttributesProperty is an error
56496                     error(jsxElementAttribPropInterfaceSym.declarations[0], ts.Diagnostics.The_global_type_JSX_0_may_not_have_more_than_one_property, ts.unescapeLeadingUnderscores(nameOfAttribPropContainer));
56497                 }
56498             }
56499             return undefined;
56500         }
56501         function getJsxLibraryManagedAttributes(jsxNamespace) {
56502             // JSX.LibraryManagedAttributes [symbol]
56503             return jsxNamespace && getSymbol(jsxNamespace.exports, JsxNames.LibraryManagedAttributes, 788968 /* Type */);
56504         }
56505         /// e.g. "props" for React.d.ts,
56506         /// or 'undefined' if ElementAttributesProperty doesn't exist (which means all
56507         ///     non-intrinsic elements' attributes type is 'any'),
56508         /// or '' if it has 0 properties (which means every
56509         ///     non-intrinsic elements' attributes type is the element instance type)
56510         function getJsxElementPropertiesName(jsxNamespace) {
56511             return getNameFromJsxElementAttributesContainer(JsxNames.ElementAttributesPropertyNameContainer, jsxNamespace);
56512         }
56513         function getJsxElementChildrenPropertyName(jsxNamespace) {
56514             return getNameFromJsxElementAttributesContainer(JsxNames.ElementChildrenAttributeNameContainer, jsxNamespace);
56515         }
56516         function getUninstantiatedJsxSignaturesOfType(elementType, caller) {
56517             if (elementType.flags & 4 /* String */) {
56518                 return [anySignature];
56519             }
56520             else if (elementType.flags & 128 /* StringLiteral */) {
56521                 var intrinsicType = getIntrinsicAttributesTypeFromStringLiteralType(elementType, caller);
56522                 if (!intrinsicType) {
56523                     error(caller, ts.Diagnostics.Property_0_does_not_exist_on_type_1, elementType.value, "JSX." + JsxNames.IntrinsicElements);
56524                     return ts.emptyArray;
56525                 }
56526                 else {
56527                     var fakeSignature = createSignatureForJSXIntrinsic(caller, intrinsicType);
56528                     return [fakeSignature];
56529                 }
56530             }
56531             var apparentElemType = getApparentType(elementType);
56532             // Resolve the signatures, preferring constructor
56533             var signatures = getSignaturesOfType(apparentElemType, 1 /* Construct */);
56534             if (signatures.length === 0) {
56535                 // No construct signatures, try call signatures
56536                 signatures = getSignaturesOfType(apparentElemType, 0 /* Call */);
56537             }
56538             if (signatures.length === 0 && apparentElemType.flags & 1048576 /* Union */) {
56539                 // If each member has some combination of new/call signatures; make a union signature list for those
56540                 signatures = getUnionSignatures(ts.map(apparentElemType.types, function (t) { return getUninstantiatedJsxSignaturesOfType(t, caller); }));
56541             }
56542             return signatures;
56543         }
56544         function getIntrinsicAttributesTypeFromStringLiteralType(type, location) {
56545             // 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
56546             // For example:
56547             //      var CustomTag: "h1" = "h1";
56548             //      <CustomTag> Hello World </CustomTag>
56549             var intrinsicElementsType = getJsxType(JsxNames.IntrinsicElements, location);
56550             if (intrinsicElementsType !== errorType) {
56551                 var stringLiteralTypeName = type.value;
56552                 var intrinsicProp = getPropertyOfType(intrinsicElementsType, ts.escapeLeadingUnderscores(stringLiteralTypeName));
56553                 if (intrinsicProp) {
56554                     return getTypeOfSymbol(intrinsicProp);
56555                 }
56556                 var indexSignatureType = getIndexTypeOfType(intrinsicElementsType, 0 /* String */);
56557                 if (indexSignatureType) {
56558                     return indexSignatureType;
56559                 }
56560                 return undefined;
56561             }
56562             // If we need to report an error, we already done so here. So just return any to prevent any more error downstream
56563             return anyType;
56564         }
56565         function checkJsxReturnAssignableToAppropriateBound(refKind, elemInstanceType, openingLikeElement) {
56566             if (refKind === 1 /* Function */) {
56567                 var sfcReturnConstraint = getJsxStatelessElementTypeAt(openingLikeElement);
56568                 if (sfcReturnConstraint) {
56569                     checkTypeRelatedTo(elemInstanceType, sfcReturnConstraint, assignableRelation, openingLikeElement.tagName, ts.Diagnostics.Its_return_type_0_is_not_a_valid_JSX_element, generateInitialErrorChain);
56570                 }
56571             }
56572             else if (refKind === 0 /* Component */) {
56573                 var classConstraint = getJsxElementClassTypeAt(openingLikeElement);
56574                 if (classConstraint) {
56575                     // Issue an error if this return type isn't assignable to JSX.ElementClass, failing that
56576                     checkTypeRelatedTo(elemInstanceType, classConstraint, assignableRelation, openingLikeElement.tagName, ts.Diagnostics.Its_instance_type_0_is_not_a_valid_JSX_element, generateInitialErrorChain);
56577                 }
56578             }
56579             else { // Mixed
56580                 var sfcReturnConstraint = getJsxStatelessElementTypeAt(openingLikeElement);
56581                 var classConstraint = getJsxElementClassTypeAt(openingLikeElement);
56582                 if (!sfcReturnConstraint || !classConstraint) {
56583                     return;
56584                 }
56585                 var combined = getUnionType([sfcReturnConstraint, classConstraint]);
56586                 checkTypeRelatedTo(elemInstanceType, combined, assignableRelation, openingLikeElement.tagName, ts.Diagnostics.Its_element_type_0_is_not_a_valid_JSX_element, generateInitialErrorChain);
56587             }
56588             function generateInitialErrorChain() {
56589                 var componentName = ts.getTextOfNode(openingLikeElement.tagName);
56590                 return ts.chainDiagnosticMessages(/* details */ undefined, ts.Diagnostics._0_cannot_be_used_as_a_JSX_component, componentName);
56591             }
56592         }
56593         /**
56594          * Get attributes type of the given intrinsic opening-like Jsx element by resolving the tag name.
56595          * The function is intended to be called from a function which has checked that the opening element is an intrinsic element.
56596          * @param node an intrinsic JSX opening-like element
56597          */
56598         function getIntrinsicAttributesTypeFromJsxOpeningLikeElement(node) {
56599             ts.Debug.assert(isJsxIntrinsicIdentifier(node.tagName));
56600             var links = getNodeLinks(node);
56601             if (!links.resolvedJsxElementAttributesType) {
56602                 var symbol = getIntrinsicTagSymbol(node);
56603                 if (links.jsxFlags & 1 /* IntrinsicNamedElement */) {
56604                     return links.resolvedJsxElementAttributesType = getTypeOfSymbol(symbol);
56605                 }
56606                 else if (links.jsxFlags & 2 /* IntrinsicIndexedElement */) {
56607                     return links.resolvedJsxElementAttributesType =
56608                         getIndexTypeOfType(getDeclaredTypeOfSymbol(symbol), 0 /* String */);
56609                 }
56610                 else {
56611                     return links.resolvedJsxElementAttributesType = errorType;
56612                 }
56613             }
56614             return links.resolvedJsxElementAttributesType;
56615         }
56616         function getJsxElementClassTypeAt(location) {
56617             var type = getJsxType(JsxNames.ElementClass, location);
56618             if (type === errorType)
56619                 return undefined;
56620             return type;
56621         }
56622         function getJsxElementTypeAt(location) {
56623             return getJsxType(JsxNames.Element, location);
56624         }
56625         function getJsxStatelessElementTypeAt(location) {
56626             var jsxElementType = getJsxElementTypeAt(location);
56627             if (jsxElementType) {
56628                 return getUnionType([jsxElementType, nullType]);
56629             }
56630         }
56631         /**
56632          * Returns all the properties of the Jsx.IntrinsicElements interface
56633          */
56634         function getJsxIntrinsicTagNamesAt(location) {
56635             var intrinsics = getJsxType(JsxNames.IntrinsicElements, location);
56636             return intrinsics ? getPropertiesOfType(intrinsics) : ts.emptyArray;
56637         }
56638         function checkJsxPreconditions(errorNode) {
56639             // Preconditions for using JSX
56640             if ((compilerOptions.jsx || 0 /* None */) === 0 /* None */) {
56641                 error(errorNode, ts.Diagnostics.Cannot_use_JSX_unless_the_jsx_flag_is_provided);
56642             }
56643             if (getJsxElementTypeAt(errorNode) === undefined) {
56644                 if (noImplicitAny) {
56645                     error(errorNode, ts.Diagnostics.JSX_element_implicitly_has_type_any_because_the_global_type_JSX_Element_does_not_exist);
56646                 }
56647             }
56648         }
56649         function checkJsxOpeningLikeElementOrOpeningFragment(node) {
56650             var isNodeOpeningLikeElement = ts.isJsxOpeningLikeElement(node);
56651             if (isNodeOpeningLikeElement) {
56652                 checkGrammarJsxElement(node);
56653             }
56654             checkJsxPreconditions(node);
56655             // The reactNamespace/jsxFactory's root symbol should be marked as 'used' so we don't incorrectly elide its import.
56656             // And if there is no reactNamespace/jsxFactory's symbol in scope when targeting React emit, we should issue an error.
56657             var reactRefErr = diagnostics && compilerOptions.jsx === 2 /* React */ ? ts.Diagnostics.Cannot_find_name_0 : undefined;
56658             var reactNamespace = getJsxNamespace(node);
56659             var reactLocation = isNodeOpeningLikeElement ? node.tagName : node;
56660             var reactSym = resolveName(reactLocation, reactNamespace, 111551 /* Value */, reactRefErr, reactNamespace, /*isUse*/ true);
56661             if (reactSym) {
56662                 // Mark local symbol as referenced here because it might not have been marked
56663                 // if jsx emit was not react as there wont be error being emitted
56664                 reactSym.isReferenced = 67108863 /* All */;
56665                 // If react symbol is alias, mark it as refereced
56666                 if (reactSym.flags & 2097152 /* Alias */ && !getTypeOnlyAliasDeclaration(reactSym)) {
56667                     markAliasSymbolAsReferenced(reactSym);
56668                 }
56669             }
56670             if (isNodeOpeningLikeElement) {
56671                 var jsxOpeningLikeNode = node;
56672                 var sig = getResolvedSignature(jsxOpeningLikeNode);
56673                 checkJsxReturnAssignableToAppropriateBound(getJsxReferenceKind(jsxOpeningLikeNode), getReturnTypeOfSignature(sig), jsxOpeningLikeNode);
56674             }
56675         }
56676         /**
56677          * Check if a property with the given name is known anywhere in the given type. In an object type, a property
56678          * is considered known if
56679          * 1. the object type is empty and the check is for assignability, or
56680          * 2. if the object type has index signatures, or
56681          * 3. if the property is actually declared in the object type
56682          *    (this means that 'toString', for example, is not usually a known property).
56683          * 4. In a union or intersection type,
56684          *    a property is considered known if it is known in any constituent type.
56685          * @param targetType a type to search a given name in
56686          * @param name a property name to search
56687          * @param isComparingJsxAttributes a boolean flag indicating whether we are searching in JsxAttributesType
56688          */
56689         function isKnownProperty(targetType, name, isComparingJsxAttributes) {
56690             if (targetType.flags & 524288 /* Object */) {
56691                 var resolved = resolveStructuredTypeMembers(targetType);
56692                 if (resolved.stringIndexInfo ||
56693                     resolved.numberIndexInfo && isNumericLiteralName(name) ||
56694                     getPropertyOfObjectType(targetType, name) ||
56695                     isComparingJsxAttributes && !isUnhyphenatedJsxName(name)) {
56696                     // For JSXAttributes, if the attribute has a hyphenated name, consider that the attribute to be known.
56697                     return true;
56698                 }
56699             }
56700             else if (targetType.flags & 3145728 /* UnionOrIntersection */ && isExcessPropertyCheckTarget(targetType)) {
56701                 for (var _i = 0, _a = targetType.types; _i < _a.length; _i++) {
56702                     var t = _a[_i];
56703                     if (isKnownProperty(t, name, isComparingJsxAttributes)) {
56704                         return true;
56705                     }
56706                 }
56707             }
56708             return false;
56709         }
56710         function isExcessPropertyCheckTarget(type) {
56711             return !!(type.flags & 524288 /* Object */ && !(ts.getObjectFlags(type) & 512 /* ObjectLiteralPatternWithComputedProperties */) ||
56712                 type.flags & 67108864 /* NonPrimitive */ ||
56713                 type.flags & 1048576 /* Union */ && ts.some(type.types, isExcessPropertyCheckTarget) ||
56714                 type.flags & 2097152 /* Intersection */ && ts.every(type.types, isExcessPropertyCheckTarget));
56715         }
56716         function checkJsxExpression(node, checkMode) {
56717             checkGrammarJsxExpression(node);
56718             if (node.expression) {
56719                 var type = checkExpression(node.expression, checkMode);
56720                 if (node.dotDotDotToken && type !== anyType && !isArrayType(type)) {
56721                     error(node, ts.Diagnostics.JSX_spread_child_must_be_an_array_type);
56722                 }
56723                 return type;
56724             }
56725             else {
56726                 return errorType;
56727             }
56728         }
56729         function getDeclarationNodeFlagsFromSymbol(s) {
56730             return s.valueDeclaration ? ts.getCombinedNodeFlags(s.valueDeclaration) : 0;
56731         }
56732         /**
56733          * Return whether this symbol is a member of a prototype somewhere
56734          * Note that this is not tracked well within the compiler, so the answer may be incorrect.
56735          */
56736         function isPrototypeProperty(symbol) {
56737             if (symbol.flags & 8192 /* Method */ || ts.getCheckFlags(symbol) & 4 /* SyntheticMethod */) {
56738                 return true;
56739             }
56740             if (ts.isInJSFile(symbol.valueDeclaration)) {
56741                 var parent = symbol.valueDeclaration.parent;
56742                 return parent && ts.isBinaryExpression(parent) &&
56743                     ts.getAssignmentDeclarationKind(parent) === 3 /* PrototypeProperty */;
56744             }
56745         }
56746         /**
56747          * Check whether the requested property access is valid.
56748          * Returns true if node is a valid property access, and false otherwise.
56749          * @param node The node to be checked.
56750          * @param isSuper True if the access is from `super.`.
56751          * @param type The type of the object whose property is being accessed. (Not the type of the property.)
56752          * @param prop The symbol for the property being accessed.
56753          */
56754         function checkPropertyAccessibility(node, isSuper, type, prop) {
56755             var flags = ts.getDeclarationModifierFlagsFromSymbol(prop);
56756             var errorNode = node.kind === 153 /* QualifiedName */ ? node.right : node.kind === 188 /* ImportType */ ? node : node.name;
56757             if (isSuper) {
56758                 // TS 1.0 spec (April 2014): 4.8.2
56759                 // - In a constructor, instance member function, instance member accessor, or
56760                 //   instance member variable initializer where this references a derived class instance,
56761                 //   a super property access is permitted and must specify a public instance member function of the base class.
56762                 // - In a static member function or static member accessor
56763                 //   where this references the constructor function object of a derived class,
56764                 //   a super property access is permitted and must specify a public static member function of the base class.
56765                 if (languageVersion < 2 /* ES2015 */) {
56766                     if (symbolHasNonMethodDeclaration(prop)) {
56767                         error(errorNode, ts.Diagnostics.Only_public_and_protected_methods_of_the_base_class_are_accessible_via_the_super_keyword);
56768                         return false;
56769                     }
56770                 }
56771                 if (flags & 128 /* Abstract */) {
56772                     // A method cannot be accessed in a super property access if the method is abstract.
56773                     // This error could mask a private property access error. But, a member
56774                     // cannot simultaneously be private and abstract, so this will trigger an
56775                     // additional error elsewhere.
56776                     error(errorNode, ts.Diagnostics.Abstract_method_0_in_class_1_cannot_be_accessed_via_super_expression, symbolToString(prop), typeToString(getDeclaringClass(prop)));
56777                     return false;
56778                 }
56779             }
56780             // Referencing abstract properties within their own constructors is not allowed
56781             if ((flags & 128 /* Abstract */) && ts.isThisProperty(node) && symbolHasNonMethodDeclaration(prop)) {
56782                 var declaringClassDeclaration = ts.getClassLikeDeclarationOfSymbol(getParentOfSymbol(prop));
56783                 if (declaringClassDeclaration && isNodeUsedDuringClassInitialization(node)) {
56784                     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
56785                     return false;
56786                 }
56787             }
56788             if (ts.isPropertyAccessExpression(node) && ts.isPrivateIdentifier(node.name)) {
56789                 if (!ts.getContainingClass(node)) {
56790                     error(errorNode, ts.Diagnostics.Private_identifiers_are_not_allowed_outside_class_bodies);
56791                     return false;
56792                 }
56793                 return true;
56794             }
56795             // Public properties are otherwise accessible.
56796             if (!(flags & 24 /* NonPublicAccessibilityModifier */)) {
56797                 return true;
56798             }
56799             // Property is known to be private or protected at this point
56800             // Private property is accessible if the property is within the declaring class
56801             if (flags & 8 /* Private */) {
56802                 var declaringClassDeclaration = ts.getClassLikeDeclarationOfSymbol(getParentOfSymbol(prop));
56803                 if (!isNodeWithinClass(node, declaringClassDeclaration)) {
56804                     error(errorNode, ts.Diagnostics.Property_0_is_private_and_only_accessible_within_class_1, symbolToString(prop), typeToString(getDeclaringClass(prop)));
56805                     return false;
56806                 }
56807                 return true;
56808             }
56809             // Property is known to be protected at this point
56810             // All protected properties of a supertype are accessible in a super access
56811             if (isSuper) {
56812                 return true;
56813             }
56814             // Find the first enclosing class that has the declaring classes of the protected constituents
56815             // of the property as base classes
56816             var enclosingClass = forEachEnclosingClass(node, function (enclosingDeclaration) {
56817                 var enclosingClass = getDeclaredTypeOfSymbol(getSymbolOfNode(enclosingDeclaration));
56818                 return isClassDerivedFromDeclaringClasses(enclosingClass, prop) ? enclosingClass : undefined;
56819             });
56820             // A protected property is accessible if the property is within the declaring class or classes derived from it
56821             if (!enclosingClass) {
56822                 // allow PropertyAccessibility if context is in function with this parameter
56823                 // static member access is disallow
56824                 var thisParameter = void 0;
56825                 if (flags & 32 /* Static */ || !(thisParameter = getThisParameterFromNodeContext(node)) || !thisParameter.type) {
56826                     error(errorNode, ts.Diagnostics.Property_0_is_protected_and_only_accessible_within_class_1_and_its_subclasses, symbolToString(prop), typeToString(getDeclaringClass(prop) || type));
56827                     return false;
56828                 }
56829                 var thisType = getTypeFromTypeNode(thisParameter.type);
56830                 enclosingClass = ((thisType.flags & 262144 /* TypeParameter */) ? getConstraintOfTypeParameter(thisType) : thisType).target;
56831             }
56832             // No further restrictions for static properties
56833             if (flags & 32 /* Static */) {
56834                 return true;
56835             }
56836             if (type.flags & 262144 /* TypeParameter */) {
56837                 // get the original type -- represented as the type constraint of the 'this' type
56838                 type = type.isThisType ? getConstraintOfTypeParameter(type) : getBaseConstraintOfType(type); // TODO: GH#18217 Use a different variable that's allowed to be undefined
56839             }
56840             if (!type || !hasBaseType(type, enclosingClass)) {
56841                 error(errorNode, ts.Diagnostics.Property_0_is_protected_and_only_accessible_through_an_instance_of_class_1, symbolToString(prop), typeToString(enclosingClass));
56842                 return false;
56843             }
56844             return true;
56845         }
56846         function getThisParameterFromNodeContext(node) {
56847             var thisContainer = ts.getThisContainer(node, /* includeArrowFunctions */ false);
56848             return thisContainer && ts.isFunctionLike(thisContainer) ? ts.getThisParameter(thisContainer) : undefined;
56849         }
56850         function symbolHasNonMethodDeclaration(symbol) {
56851             return !!forEachProperty(symbol, function (prop) { return !(prop.flags & 8192 /* Method */); });
56852         }
56853         function checkNonNullExpression(node) {
56854             return checkNonNullType(checkExpression(node), node);
56855         }
56856         function isNullableType(type) {
56857             return !!((strictNullChecks ? getFalsyFlags(type) : type.flags) & 98304 /* Nullable */);
56858         }
56859         function getNonNullableTypeIfNeeded(type) {
56860             return isNullableType(type) ? getNonNullableType(type) : type;
56861         }
56862         function reportObjectPossiblyNullOrUndefinedError(node, flags) {
56863             error(node, flags & 32768 /* Undefined */ ? flags & 65536 /* Null */ ?
56864                 ts.Diagnostics.Object_is_possibly_null_or_undefined :
56865                 ts.Diagnostics.Object_is_possibly_undefined :
56866                 ts.Diagnostics.Object_is_possibly_null);
56867         }
56868         function reportCannotInvokePossiblyNullOrUndefinedError(node, flags) {
56869             error(node, flags & 32768 /* Undefined */ ? flags & 65536 /* Null */ ?
56870                 ts.Diagnostics.Cannot_invoke_an_object_which_is_possibly_null_or_undefined :
56871                 ts.Diagnostics.Cannot_invoke_an_object_which_is_possibly_undefined :
56872                 ts.Diagnostics.Cannot_invoke_an_object_which_is_possibly_null);
56873         }
56874         function checkNonNullTypeWithReporter(type, node, reportError) {
56875             if (strictNullChecks && type.flags & 2 /* Unknown */) {
56876                 error(node, ts.Diagnostics.Object_is_of_type_unknown);
56877                 return errorType;
56878             }
56879             var kind = (strictNullChecks ? getFalsyFlags(type) : type.flags) & 98304 /* Nullable */;
56880             if (kind) {
56881                 reportError(node, kind);
56882                 var t = getNonNullableType(type);
56883                 return t.flags & (98304 /* Nullable */ | 131072 /* Never */) ? errorType : t;
56884             }
56885             return type;
56886         }
56887         function checkNonNullType(type, node) {
56888             return checkNonNullTypeWithReporter(type, node, reportObjectPossiblyNullOrUndefinedError);
56889         }
56890         function checkNonNullNonVoidType(type, node) {
56891             var nonNullType = checkNonNullType(type, node);
56892             if (nonNullType !== errorType && nonNullType.flags & 16384 /* Void */) {
56893                 error(node, ts.Diagnostics.Object_is_possibly_undefined);
56894             }
56895             return nonNullType;
56896         }
56897         function checkPropertyAccessExpression(node) {
56898             return node.flags & 32 /* OptionalChain */ ? checkPropertyAccessChain(node) :
56899                 checkPropertyAccessExpressionOrQualifiedName(node, node.expression, checkNonNullExpression(node.expression), node.name);
56900         }
56901         function checkPropertyAccessChain(node) {
56902             var leftType = checkExpression(node.expression);
56903             var nonOptionalType = getOptionalExpressionType(leftType, node.expression);
56904             return propagateOptionalTypeMarker(checkPropertyAccessExpressionOrQualifiedName(node, node.expression, checkNonNullType(nonOptionalType, node.expression), node.name), node, nonOptionalType !== leftType);
56905         }
56906         function checkQualifiedName(node) {
56907             return checkPropertyAccessExpressionOrQualifiedName(node, node.left, checkNonNullExpression(node.left), node.right);
56908         }
56909         function isMethodAccessForCall(node) {
56910             while (node.parent.kind === 200 /* ParenthesizedExpression */) {
56911                 node = node.parent;
56912             }
56913             return ts.isCallOrNewExpression(node.parent) && node.parent.expression === node;
56914         }
56915         // Lookup the private identifier lexically.
56916         function lookupSymbolForPrivateIdentifierDeclaration(propName, location) {
56917             for (var containingClass = ts.getContainingClass(location); !!containingClass; containingClass = ts.getContainingClass(containingClass)) {
56918                 var symbol = containingClass.symbol;
56919                 var name = ts.getSymbolNameForPrivateIdentifier(symbol, propName);
56920                 var prop = (symbol.members && symbol.members.get(name)) || (symbol.exports && symbol.exports.get(name));
56921                 if (prop) {
56922                     return prop;
56923                 }
56924             }
56925         }
56926         function getPrivateIdentifierPropertyOfType(leftType, lexicallyScopedIdentifier) {
56927             return getPropertyOfType(leftType, lexicallyScopedIdentifier.escapedName);
56928         }
56929         function checkPrivateIdentifierPropertyAccess(leftType, right, lexicallyScopedIdentifier) {
56930             // Either the identifier could not be looked up in the lexical scope OR the lexically scoped identifier did not exist on the type.
56931             // Find a private identifier with the same description on the type.
56932             var propertyOnType;
56933             var properties = getPropertiesOfType(leftType);
56934             if (properties) {
56935                 ts.forEach(properties, function (symbol) {
56936                     var decl = symbol.valueDeclaration;
56937                     if (decl && ts.isNamedDeclaration(decl) && ts.isPrivateIdentifier(decl.name) && decl.name.escapedText === right.escapedText) {
56938                         propertyOnType = symbol;
56939                         return true;
56940                     }
56941                 });
56942             }
56943             var diagName = diagnosticName(right);
56944             if (propertyOnType) {
56945                 var typeValueDecl = propertyOnType.valueDeclaration;
56946                 var typeClass_1 = ts.getContainingClass(typeValueDecl);
56947                 ts.Debug.assert(!!typeClass_1);
56948                 // We found a private identifier property with the same description.
56949                 // Either:
56950                 // - There is a lexically scoped private identifier AND it shadows the one we found on the type.
56951                 // - It is an attempt to access the private identifier outside of the class.
56952                 if (lexicallyScopedIdentifier) {
56953                     var lexicalValueDecl = lexicallyScopedIdentifier.valueDeclaration;
56954                     var lexicalClass = ts.getContainingClass(lexicalValueDecl);
56955                     ts.Debug.assert(!!lexicalClass);
56956                     if (ts.findAncestor(lexicalClass, function (n) { return typeClass_1 === n; })) {
56957                         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));
56958                         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));
56959                         return true;
56960                     }
56961                 }
56962                 error(right, ts.Diagnostics.Property_0_is_not_accessible_outside_class_1_because_it_has_a_private_identifier, diagName, diagnosticName(typeClass_1.name || anon));
56963                 return true;
56964             }
56965             return false;
56966         }
56967         function checkPropertyAccessExpressionOrQualifiedName(node, left, leftType, right) {
56968             var parentSymbol = getNodeLinks(left).resolvedSymbol;
56969             var assignmentKind = ts.getAssignmentTargetKind(node);
56970             var apparentType = getApparentType(assignmentKind !== 0 /* None */ || isMethodAccessForCall(node) ? getWidenedType(leftType) : leftType);
56971             if (ts.isPrivateIdentifier(right)) {
56972                 checkExternalEmitHelpers(node, 262144 /* ClassPrivateFieldGet */);
56973             }
56974             var isAnyLike = isTypeAny(apparentType) || apparentType === silentNeverType;
56975             var prop;
56976             if (ts.isPrivateIdentifier(right)) {
56977                 var lexicallyScopedSymbol = lookupSymbolForPrivateIdentifierDeclaration(right.escapedText, right);
56978                 if (isAnyLike) {
56979                     if (lexicallyScopedSymbol) {
56980                         return apparentType;
56981                     }
56982                     if (!ts.getContainingClass(right)) {
56983                         grammarErrorOnNode(right, ts.Diagnostics.Private_identifiers_are_not_allowed_outside_class_bodies);
56984                         return anyType;
56985                     }
56986                 }
56987                 prop = lexicallyScopedSymbol ? getPrivateIdentifierPropertyOfType(leftType, lexicallyScopedSymbol) : undefined;
56988                 // Check for private-identifier-specific shadowing and lexical-scoping errors.
56989                 if (!prop && checkPrivateIdentifierPropertyAccess(leftType, right, lexicallyScopedSymbol)) {
56990                     return errorType;
56991                 }
56992             }
56993             else {
56994                 if (isAnyLike) {
56995                     if (ts.isIdentifier(left) && parentSymbol) {
56996                         markAliasReferenced(parentSymbol, node);
56997                     }
56998                     return apparentType;
56999                 }
57000                 prop = getPropertyOfType(apparentType, right.escapedText);
57001             }
57002             if (ts.isIdentifier(left) && parentSymbol && !(prop && isConstEnumOrConstEnumOnlyModule(prop))) {
57003                 markAliasReferenced(parentSymbol, node);
57004             }
57005             var propType;
57006             if (!prop) {
57007                 var indexInfo = !ts.isPrivateIdentifier(right) && (assignmentKind === 0 /* None */ || !isGenericObjectType(leftType) || isThisTypeParameter(leftType)) ? getIndexInfoOfType(apparentType, 0 /* String */) : undefined;
57008                 if (!(indexInfo && indexInfo.type)) {
57009                     if (isJSLiteralType(leftType)) {
57010                         return anyType;
57011                     }
57012                     if (leftType.symbol === globalThisSymbol) {
57013                         if (globalThisSymbol.exports.has(right.escapedText) && (globalThisSymbol.exports.get(right.escapedText).flags & 418 /* BlockScoped */)) {
57014                             error(right, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.unescapeLeadingUnderscores(right.escapedText), typeToString(leftType));
57015                         }
57016                         else if (noImplicitAny) {
57017                             error(right, ts.Diagnostics.Element_implicitly_has_an_any_type_because_type_0_has_no_index_signature, typeToString(leftType));
57018                         }
57019                         return anyType;
57020                     }
57021                     if (right.escapedText && !checkAndReportErrorForExtendingInterface(node)) {
57022                         reportNonexistentProperty(right, isThisTypeParameter(leftType) ? apparentType : leftType);
57023                     }
57024                     return errorType;
57025                 }
57026                 if (indexInfo.isReadonly && (ts.isAssignmentTarget(node) || ts.isDeleteTarget(node))) {
57027                     error(node, ts.Diagnostics.Index_signature_in_type_0_only_permits_reading, typeToString(apparentType));
57028                 }
57029                 propType = indexInfo.type;
57030             }
57031             else {
57032                 checkPropertyNotUsedBeforeDeclaration(prop, node, right);
57033                 markPropertyAsReferenced(prop, node, left.kind === 104 /* ThisKeyword */);
57034                 getNodeLinks(node).resolvedSymbol = prop;
57035                 checkPropertyAccessibility(node, left.kind === 102 /* SuperKeyword */, apparentType, prop);
57036                 if (isAssignmentToReadonlyEntity(node, prop, assignmentKind)) {
57037                     error(right, ts.Diagnostics.Cannot_assign_to_0_because_it_is_a_read_only_property, ts.idText(right));
57038                     return errorType;
57039                 }
57040                 propType = getConstraintForLocation(getTypeOfSymbol(prop), node);
57041             }
57042             return getFlowTypeOfAccessExpression(node, prop, propType, right);
57043         }
57044         function getFlowTypeOfAccessExpression(node, prop, propType, errorNode) {
57045             // Only compute control flow type if this is a property access expression that isn't an
57046             // assignment target, and the referenced property was declared as a variable, property,
57047             // accessor, or optional method.
57048             var assignmentKind = ts.getAssignmentTargetKind(node);
57049             if (!ts.isAccessExpression(node) ||
57050                 assignmentKind === 1 /* Definite */ ||
57051                 prop && !(prop.flags & (3 /* Variable */ | 4 /* Property */ | 98304 /* Accessor */)) && !(prop.flags & 8192 /* Method */ && propType.flags & 1048576 /* Union */)) {
57052                 return propType;
57053             }
57054             // If strict null checks and strict property initialization checks are enabled, if we have
57055             // a this.xxx property access, if the property is an instance property without an initializer,
57056             // and if we are in a constructor of the same class as the property declaration, assume that
57057             // the property is uninitialized at the top of the control flow.
57058             var assumeUninitialized = false;
57059             if (strictNullChecks && strictPropertyInitialization && node.expression.kind === 104 /* ThisKeyword */) {
57060                 var declaration = prop && prop.valueDeclaration;
57061                 if (declaration && isInstancePropertyWithoutInitializer(declaration)) {
57062                     var flowContainer = getControlFlowContainer(node);
57063                     if (flowContainer.kind === 162 /* Constructor */ && flowContainer.parent === declaration.parent && !(declaration.flags & 8388608 /* Ambient */)) {
57064                         assumeUninitialized = true;
57065                     }
57066                 }
57067             }
57068             else if (strictNullChecks && prop && prop.valueDeclaration &&
57069                 ts.isPropertyAccessExpression(prop.valueDeclaration) &&
57070                 ts.getAssignmentDeclarationPropertyAccessKind(prop.valueDeclaration) &&
57071                 getControlFlowContainer(node) === getControlFlowContainer(prop.valueDeclaration)) {
57072                 assumeUninitialized = true;
57073             }
57074             var flowType = getFlowTypeOfReference(node, propType, assumeUninitialized ? getOptionalType(propType) : propType);
57075             if (assumeUninitialized && !(getFalsyFlags(propType) & 32768 /* Undefined */) && getFalsyFlags(flowType) & 32768 /* Undefined */) {
57076                 error(errorNode, ts.Diagnostics.Property_0_is_used_before_being_assigned, symbolToString(prop)); // TODO: GH#18217
57077                 // Return the declared type to reduce follow-on errors
57078                 return propType;
57079             }
57080             return assignmentKind ? getBaseTypeOfLiteralType(flowType) : flowType;
57081         }
57082         function checkPropertyNotUsedBeforeDeclaration(prop, node, right) {
57083             var valueDeclaration = prop.valueDeclaration;
57084             if (!valueDeclaration || ts.getSourceFileOfNode(node).isDeclarationFile) {
57085                 return;
57086             }
57087             var diagnosticMessage;
57088             var declarationName = ts.idText(right);
57089             if (isInPropertyInitializer(node)
57090                 && !(ts.isAccessExpression(node) && ts.isAccessExpression(node.expression))
57091                 && !isBlockScopedNameDeclaredBeforeUse(valueDeclaration, right)
57092                 && !isPropertyDeclaredInAncestorClass(prop)) {
57093                 diagnosticMessage = error(right, ts.Diagnostics.Property_0_is_used_before_its_initialization, declarationName);
57094             }
57095             else if (valueDeclaration.kind === 245 /* ClassDeclaration */ &&
57096                 node.parent.kind !== 169 /* TypeReference */ &&
57097                 !(valueDeclaration.flags & 8388608 /* Ambient */) &&
57098                 !isBlockScopedNameDeclaredBeforeUse(valueDeclaration, right)) {
57099                 diagnosticMessage = error(right, ts.Diagnostics.Class_0_used_before_its_declaration, declarationName);
57100             }
57101             if (diagnosticMessage) {
57102                 ts.addRelatedInfo(diagnosticMessage, ts.createDiagnosticForNode(valueDeclaration, ts.Diagnostics._0_is_declared_here, declarationName));
57103             }
57104         }
57105         function isInPropertyInitializer(node) {
57106             return !!ts.findAncestor(node, function (node) {
57107                 switch (node.kind) {
57108                     case 159 /* PropertyDeclaration */:
57109                         return true;
57110                     case 281 /* PropertyAssignment */:
57111                     case 161 /* MethodDeclaration */:
57112                     case 163 /* GetAccessor */:
57113                     case 164 /* SetAccessor */:
57114                     case 283 /* SpreadAssignment */:
57115                     case 154 /* ComputedPropertyName */:
57116                     case 221 /* TemplateSpan */:
57117                     case 276 /* JsxExpression */:
57118                     case 273 /* JsxAttribute */:
57119                     case 274 /* JsxAttributes */:
57120                     case 275 /* JsxSpreadAttribute */:
57121                     case 268 /* JsxOpeningElement */:
57122                     case 216 /* ExpressionWithTypeArguments */:
57123                     case 279 /* HeritageClause */:
57124                         return false;
57125                     default:
57126                         return ts.isExpressionNode(node) ? false : "quit";
57127                 }
57128             });
57129         }
57130         /**
57131          * It's possible that "prop.valueDeclaration" is a local declaration, but the property was also declared in a superclass.
57132          * In that case we won't consider it used before its declaration, because it gets its value from the superclass' declaration.
57133          */
57134         function isPropertyDeclaredInAncestorClass(prop) {
57135             if (!(prop.parent.flags & 32 /* Class */)) {
57136                 return false;
57137             }
57138             var classType = getTypeOfSymbol(prop.parent);
57139             while (true) {
57140                 classType = classType.symbol && getSuperClass(classType);
57141                 if (!classType) {
57142                     return false;
57143                 }
57144                 var superProperty = getPropertyOfType(classType, prop.escapedName);
57145                 if (superProperty && superProperty.valueDeclaration) {
57146                     return true;
57147                 }
57148             }
57149         }
57150         function getSuperClass(classType) {
57151             var x = getBaseTypes(classType);
57152             if (x.length === 0) {
57153                 return undefined;
57154             }
57155             return getIntersectionType(x);
57156         }
57157         function reportNonexistentProperty(propNode, containingType) {
57158             var errorInfo;
57159             var relatedInfo;
57160             if (!ts.isPrivateIdentifier(propNode) && containingType.flags & 1048576 /* Union */ && !(containingType.flags & 131068 /* Primitive */)) {
57161                 for (var _i = 0, _a = containingType.types; _i < _a.length; _i++) {
57162                     var subtype = _a[_i];
57163                     if (!getPropertyOfType(subtype, propNode.escapedText) && !getIndexInfoOfType(subtype, 0 /* String */)) {
57164                         errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.declarationNameToString(propNode), typeToString(subtype));
57165                         break;
57166                     }
57167                 }
57168             }
57169             if (typeHasStaticProperty(propNode.escapedText, containingType)) {
57170                 errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Property_0_is_a_static_member_of_type_1, ts.declarationNameToString(propNode), typeToString(containingType));
57171             }
57172             else {
57173                 var promisedType = getPromisedTypeOfPromise(containingType);
57174                 if (promisedType && getPropertyOfType(promisedType, propNode.escapedText)) {
57175                     errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.declarationNameToString(propNode), typeToString(containingType));
57176                     relatedInfo = ts.createDiagnosticForNode(propNode, ts.Diagnostics.Did_you_forget_to_use_await);
57177                 }
57178                 else {
57179                     var suggestion = getSuggestedSymbolForNonexistentProperty(propNode, containingType);
57180                     if (suggestion !== undefined) {
57181                         var suggestedName = ts.symbolName(suggestion);
57182                         errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Property_0_does_not_exist_on_type_1_Did_you_mean_2, ts.declarationNameToString(propNode), typeToString(containingType), suggestedName);
57183                         relatedInfo = suggestion.valueDeclaration && ts.createDiagnosticForNode(suggestion.valueDeclaration, ts.Diagnostics._0_is_declared_here, suggestedName);
57184                     }
57185                     else {
57186                         errorInfo = ts.chainDiagnosticMessages(elaborateNeverIntersection(errorInfo, containingType), ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.declarationNameToString(propNode), typeToString(containingType));
57187                     }
57188                 }
57189             }
57190             var resultDiagnostic = ts.createDiagnosticForNodeFromMessageChain(propNode, errorInfo);
57191             if (relatedInfo) {
57192                 ts.addRelatedInfo(resultDiagnostic, relatedInfo);
57193             }
57194             diagnostics.add(resultDiagnostic);
57195         }
57196         function typeHasStaticProperty(propName, containingType) {
57197             var prop = containingType.symbol && getPropertyOfType(getTypeOfSymbol(containingType.symbol), propName);
57198             return prop !== undefined && prop.valueDeclaration && ts.hasModifier(prop.valueDeclaration, 32 /* Static */);
57199         }
57200         function getSuggestedSymbolForNonexistentProperty(name, containingType) {
57201             return getSpellingSuggestionForName(ts.isString(name) ? name : ts.idText(name), getPropertiesOfType(containingType), 111551 /* Value */);
57202         }
57203         function getSuggestionForNonexistentProperty(name, containingType) {
57204             var suggestion = getSuggestedSymbolForNonexistentProperty(name, containingType);
57205             return suggestion && ts.symbolName(suggestion);
57206         }
57207         function getSuggestedSymbolForNonexistentSymbol(location, outerName, meaning) {
57208             ts.Debug.assert(outerName !== undefined, "outername should always be defined");
57209             var result = resolveNameHelper(location, outerName, meaning, /*nameNotFoundMessage*/ undefined, outerName, /*isUse*/ false, /*excludeGlobals*/ false, function (symbols, name, meaning) {
57210                 ts.Debug.assertEqual(outerName, name, "name should equal outerName");
57211                 var symbol = getSymbol(symbols, name, meaning);
57212                 // 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
57213                 // So the table *contains* `x` but `x` isn't actually in scope.
57214                 // However, resolveNameHelper will continue and call this callback again, so we'll eventually get a correct suggestion.
57215                 return symbol || getSpellingSuggestionForName(ts.unescapeLeadingUnderscores(name), ts.arrayFrom(symbols.values()), meaning);
57216             });
57217             return result;
57218         }
57219         function getSuggestionForNonexistentSymbol(location, outerName, meaning) {
57220             var symbolResult = getSuggestedSymbolForNonexistentSymbol(location, outerName, meaning);
57221             return symbolResult && ts.symbolName(symbolResult);
57222         }
57223         function getSuggestedSymbolForNonexistentModule(name, targetModule) {
57224             return targetModule.exports && getSpellingSuggestionForName(ts.idText(name), getExportsOfModuleAsArray(targetModule), 2623475 /* ModuleMember */);
57225         }
57226         function getSuggestionForNonexistentExport(name, targetModule) {
57227             var suggestion = getSuggestedSymbolForNonexistentModule(name, targetModule);
57228             return suggestion && ts.symbolName(suggestion);
57229         }
57230         function getSuggestionForNonexistentIndexSignature(objectType, expr, keyedType) {
57231             // check if object type has setter or getter
57232             function hasProp(name) {
57233                 var prop = getPropertyOfObjectType(objectType, name);
57234                 if (prop) {
57235                     var s = getSingleCallSignature(getTypeOfSymbol(prop));
57236                     return !!s && getMinArgumentCount(s) >= 1 && isTypeAssignableTo(keyedType, getTypeAtPosition(s, 0));
57237                 }
57238                 return false;
57239             }
57240             ;
57241             var suggestedMethod = ts.isAssignmentTarget(expr) ? "set" : "get";
57242             if (!hasProp(suggestedMethod)) {
57243                 return undefined;
57244             }
57245             var suggestion = ts.tryGetPropertyAccessOrIdentifierToString(expr.expression);
57246             if (suggestion === undefined) {
57247                 suggestion = suggestedMethod;
57248             }
57249             else {
57250                 suggestion += "." + suggestedMethod;
57251             }
57252             return suggestion;
57253         }
57254         /**
57255          * 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.
57256          * Names less than length 3 only check for case-insensitive equality, not levenshtein distance.
57257          *
57258          * If there is a candidate that's the same except for case, return that.
57259          * If there is a candidate that's within one edit of the name, return that.
57260          * Otherwise, return the candidate with the smallest Levenshtein distance,
57261          *    except for candidates:
57262          *      * With no name
57263          *      * Whose meaning doesn't match the `meaning` parameter.
57264          *      * Whose length differs from the target name by more than 0.34 of the length of the name.
57265          *      * Whose levenshtein distance is more than 0.4 of the length of the name
57266          *        (0.4 allows 1 substitution/transposition for every 5 characters,
57267          *         and 1 insertion/deletion at 3 characters)
57268          */
57269         function getSpellingSuggestionForName(name, symbols, meaning) {
57270             return ts.getSpellingSuggestion(name, symbols, getCandidateName);
57271             function getCandidateName(candidate) {
57272                 var candidateName = ts.symbolName(candidate);
57273                 if (ts.startsWith(candidateName, "\"")) {
57274                     return undefined;
57275                 }
57276                 if (candidate.flags & meaning) {
57277                     return candidateName;
57278                 }
57279                 if (candidate.flags & 2097152 /* Alias */) {
57280                     var alias = tryResolveAlias(candidate);
57281                     if (alias && alias.flags & meaning) {
57282                         return candidateName;
57283                     }
57284                 }
57285                 return undefined;
57286             }
57287         }
57288         function markPropertyAsReferenced(prop, nodeForCheckWriteOnly, isThisAccess) {
57289             var valueDeclaration = prop && (prop.flags & 106500 /* ClassMember */) && prop.valueDeclaration;
57290             if (!valueDeclaration) {
57291                 return;
57292             }
57293             var hasPrivateModifier = ts.hasModifier(valueDeclaration, 8 /* Private */);
57294             var hasPrivateIdentifier = ts.isNamedDeclaration(prop.valueDeclaration) && ts.isPrivateIdentifier(prop.valueDeclaration.name);
57295             if (!hasPrivateModifier && !hasPrivateIdentifier) {
57296                 return;
57297             }
57298             if (nodeForCheckWriteOnly && ts.isWriteOnlyAccess(nodeForCheckWriteOnly) && !(prop.flags & 65536 /* SetAccessor */)) {
57299                 return;
57300             }
57301             if (isThisAccess) {
57302                 // Find any FunctionLikeDeclaration because those create a new 'this' binding. But this should only matter for methods (or getters/setters).
57303                 var containingMethod = ts.findAncestor(nodeForCheckWriteOnly, ts.isFunctionLikeDeclaration);
57304                 if (containingMethod && containingMethod.symbol === prop) {
57305                     return;
57306                 }
57307             }
57308             (ts.getCheckFlags(prop) & 1 /* Instantiated */ ? getSymbolLinks(prop).target : prop).isReferenced = 67108863 /* All */;
57309         }
57310         function isValidPropertyAccess(node, propertyName) {
57311             switch (node.kind) {
57312                 case 194 /* PropertyAccessExpression */:
57313                     return isValidPropertyAccessWithType(node, node.expression.kind === 102 /* SuperKeyword */, propertyName, getWidenedType(checkExpression(node.expression)));
57314                 case 153 /* QualifiedName */:
57315                     return isValidPropertyAccessWithType(node, /*isSuper*/ false, propertyName, getWidenedType(checkExpression(node.left)));
57316                 case 188 /* ImportType */:
57317                     return isValidPropertyAccessWithType(node, /*isSuper*/ false, propertyName, getTypeFromTypeNode(node));
57318             }
57319         }
57320         function isValidPropertyAccessForCompletions(node, type, property) {
57321             return isValidPropertyAccessWithType(node, node.kind === 194 /* PropertyAccessExpression */ && node.expression.kind === 102 /* SuperKeyword */, property.escapedName, type);
57322             // Previously we validated the 'this' type of methods but this adversely affected performance. See #31377 for more context.
57323         }
57324         function isValidPropertyAccessWithType(node, isSuper, propertyName, type) {
57325             if (type === errorType || isTypeAny(type)) {
57326                 return true;
57327             }
57328             var prop = getPropertyOfType(type, propertyName);
57329             if (prop) {
57330                 if (ts.isPropertyAccessExpression(node) && prop.valueDeclaration && ts.isPrivateIdentifierPropertyDeclaration(prop.valueDeclaration)) {
57331                     var declClass_1 = ts.getContainingClass(prop.valueDeclaration);
57332                     return !ts.isOptionalChain(node) && !!ts.findAncestor(node, function (parent) { return parent === declClass_1; });
57333                 }
57334                 return checkPropertyAccessibility(node, isSuper, type, prop);
57335             }
57336             // In js files properties of unions are allowed in completion
57337             return ts.isInJSFile(node) && (type.flags & 1048576 /* Union */) !== 0 && type.types.some(function (elementType) { return isValidPropertyAccessWithType(node, isSuper, propertyName, elementType); });
57338         }
57339         /**
57340          * Return the symbol of the for-in variable declared or referenced by the given for-in statement.
57341          */
57342         function getForInVariableSymbol(node) {
57343             var initializer = node.initializer;
57344             if (initializer.kind === 243 /* VariableDeclarationList */) {
57345                 var variable = initializer.declarations[0];
57346                 if (variable && !ts.isBindingPattern(variable.name)) {
57347                     return getSymbolOfNode(variable);
57348                 }
57349             }
57350             else if (initializer.kind === 75 /* Identifier */) {
57351                 return getResolvedSymbol(initializer);
57352             }
57353             return undefined;
57354         }
57355         /**
57356          * Return true if the given type is considered to have numeric property names.
57357          */
57358         function hasNumericPropertyNames(type) {
57359             return getIndexTypeOfType(type, 1 /* Number */) && !getIndexTypeOfType(type, 0 /* String */);
57360         }
57361         /**
57362          * Return true if given node is an expression consisting of an identifier (possibly parenthesized)
57363          * that references a for-in variable for an object with numeric property names.
57364          */
57365         function isForInVariableForNumericPropertyNames(expr) {
57366             var e = ts.skipParentheses(expr);
57367             if (e.kind === 75 /* Identifier */) {
57368                 var symbol = getResolvedSymbol(e);
57369                 if (symbol.flags & 3 /* Variable */) {
57370                     var child = expr;
57371                     var node = expr.parent;
57372                     while (node) {
57373                         if (node.kind === 231 /* ForInStatement */ &&
57374                             child === node.statement &&
57375                             getForInVariableSymbol(node) === symbol &&
57376                             hasNumericPropertyNames(getTypeOfExpression(node.expression))) {
57377                             return true;
57378                         }
57379                         child = node;
57380                         node = node.parent;
57381                     }
57382                 }
57383             }
57384             return false;
57385         }
57386         function checkIndexedAccess(node) {
57387             return node.flags & 32 /* OptionalChain */ ? checkElementAccessChain(node) :
57388                 checkElementAccessExpression(node, checkNonNullExpression(node.expression));
57389         }
57390         function checkElementAccessChain(node) {
57391             var exprType = checkExpression(node.expression);
57392             var nonOptionalType = getOptionalExpressionType(exprType, node.expression);
57393             return propagateOptionalTypeMarker(checkElementAccessExpression(node, checkNonNullType(nonOptionalType, node.expression)), node, nonOptionalType !== exprType);
57394         }
57395         function checkElementAccessExpression(node, exprType) {
57396             var objectType = ts.getAssignmentTargetKind(node) !== 0 /* None */ || isMethodAccessForCall(node) ? getWidenedType(exprType) : exprType;
57397             var indexExpression = node.argumentExpression;
57398             var indexType = checkExpression(indexExpression);
57399             if (objectType === errorType || objectType === silentNeverType) {
57400                 return objectType;
57401             }
57402             if (isConstEnumObjectType(objectType) && !ts.isStringLiteralLike(indexExpression)) {
57403                 error(indexExpression, ts.Diagnostics.A_const_enum_member_can_only_be_accessed_using_a_string_literal);
57404                 return errorType;
57405             }
57406             var effectiveIndexType = isForInVariableForNumericPropertyNames(indexExpression) ? numberType : indexType;
57407             var accessFlags = ts.isAssignmentTarget(node) ?
57408                 2 /* Writing */ | (isGenericObjectType(objectType) && !isThisTypeParameter(objectType) ? 1 /* NoIndexSignatures */ : 0) :
57409                 0 /* None */;
57410             var indexedAccessType = getIndexedAccessTypeOrUndefined(objectType, effectiveIndexType, node, accessFlags) || errorType;
57411             return checkIndexedAccessIndexType(getFlowTypeOfAccessExpression(node, indexedAccessType.symbol, indexedAccessType, indexExpression), node);
57412         }
57413         function checkThatExpressionIsProperSymbolReference(expression, expressionType, reportError) {
57414             if (expressionType === errorType) {
57415                 // There is already an error, so no need to report one.
57416                 return false;
57417             }
57418             if (!ts.isWellKnownSymbolSyntactically(expression)) {
57419                 return false;
57420             }
57421             // Make sure the property type is the primitive symbol type
57422             if ((expressionType.flags & 12288 /* ESSymbolLike */) === 0) {
57423                 if (reportError) {
57424                     error(expression, ts.Diagnostics.A_computed_property_name_of_the_form_0_must_be_of_type_symbol, ts.getTextOfNode(expression));
57425                 }
57426                 return false;
57427             }
57428             // The name is Symbol.<someName>, so make sure Symbol actually resolves to the
57429             // global Symbol object
57430             var leftHandSide = expression.expression;
57431             var leftHandSideSymbol = getResolvedSymbol(leftHandSide);
57432             if (!leftHandSideSymbol) {
57433                 return false;
57434             }
57435             var globalESSymbol = getGlobalESSymbolConstructorSymbol(/*reportErrors*/ true);
57436             if (!globalESSymbol) {
57437                 // Already errored when we tried to look up the symbol
57438                 return false;
57439             }
57440             if (leftHandSideSymbol !== globalESSymbol) {
57441                 if (reportError) {
57442                     error(leftHandSide, ts.Diagnostics.Symbol_reference_does_not_refer_to_the_global_Symbol_constructor_object);
57443                 }
57444                 return false;
57445             }
57446             return true;
57447         }
57448         function callLikeExpressionMayHaveTypeArguments(node) {
57449             return ts.isCallOrNewExpression(node) || ts.isTaggedTemplateExpression(node) || ts.isJsxOpeningLikeElement(node);
57450         }
57451         function resolveUntypedCall(node) {
57452             if (callLikeExpressionMayHaveTypeArguments(node)) {
57453                 // Check type arguments even though we will give an error that untyped calls may not accept type arguments.
57454                 // This gets us diagnostics for the type arguments and marks them as referenced.
57455                 ts.forEach(node.typeArguments, checkSourceElement);
57456             }
57457             if (node.kind === 198 /* TaggedTemplateExpression */) {
57458                 checkExpression(node.template);
57459             }
57460             else if (ts.isJsxOpeningLikeElement(node)) {
57461                 checkExpression(node.attributes);
57462             }
57463             else if (node.kind !== 157 /* Decorator */) {
57464                 ts.forEach(node.arguments, function (argument) {
57465                     checkExpression(argument);
57466                 });
57467             }
57468             return anySignature;
57469         }
57470         function resolveErrorCall(node) {
57471             resolveUntypedCall(node);
57472             return unknownSignature;
57473         }
57474         // Re-order candidate signatures into the result array. Assumes the result array to be empty.
57475         // The candidate list orders groups in reverse, but within a group signatures are kept in declaration order
57476         // A nit here is that we reorder only signatures that belong to the same symbol,
57477         // so order how inherited signatures are processed is still preserved.
57478         // interface A { (x: string): void }
57479         // interface B extends A { (x: 'foo'): string }
57480         // const b: B;
57481         // b('foo') // <- here overloads should be processed as [(x:'foo'): string, (x: string): void]
57482         function reorderCandidates(signatures, result, callChainFlags) {
57483             var lastParent;
57484             var lastSymbol;
57485             var cutoffIndex = 0;
57486             var index;
57487             var specializedIndex = -1;
57488             var spliceIndex;
57489             ts.Debug.assert(!result.length);
57490             for (var _i = 0, signatures_7 = signatures; _i < signatures_7.length; _i++) {
57491                 var signature = signatures_7[_i];
57492                 var symbol = signature.declaration && getSymbolOfNode(signature.declaration);
57493                 var parent = signature.declaration && signature.declaration.parent;
57494                 if (!lastSymbol || symbol === lastSymbol) {
57495                     if (lastParent && parent === lastParent) {
57496                         index = index + 1;
57497                     }
57498                     else {
57499                         lastParent = parent;
57500                         index = cutoffIndex;
57501                     }
57502                 }
57503                 else {
57504                     // current declaration belongs to a different symbol
57505                     // set cutoffIndex so re-orderings in the future won't change result set from 0 to cutoffIndex
57506                     index = cutoffIndex = result.length;
57507                     lastParent = parent;
57508                 }
57509                 lastSymbol = symbol;
57510                 // specialized signatures always need to be placed before non-specialized signatures regardless
57511                 // of the cutoff position; see GH#1133
57512                 if (signatureHasLiteralTypes(signature)) {
57513                     specializedIndex++;
57514                     spliceIndex = specializedIndex;
57515                     // The cutoff index always needs to be greater than or equal to the specialized signature index
57516                     // in order to prevent non-specialized signatures from being added before a specialized
57517                     // signature.
57518                     cutoffIndex++;
57519                 }
57520                 else {
57521                     spliceIndex = index;
57522                 }
57523                 result.splice(spliceIndex, 0, callChainFlags ? getOptionalCallSignature(signature, callChainFlags) : signature);
57524             }
57525         }
57526         function isSpreadArgument(arg) {
57527             return !!arg && (arg.kind === 213 /* SpreadElement */ || arg.kind === 220 /* SyntheticExpression */ && arg.isSpread);
57528         }
57529         function getSpreadArgumentIndex(args) {
57530             return ts.findIndex(args, isSpreadArgument);
57531         }
57532         function acceptsVoid(t) {
57533             return !!(t.flags & 16384 /* Void */);
57534         }
57535         function hasCorrectArity(node, args, signature, signatureHelpTrailingComma) {
57536             if (signatureHelpTrailingComma === void 0) { signatureHelpTrailingComma = false; }
57537             var argCount;
57538             var callIsIncomplete = false; // In incomplete call we want to be lenient when we have too few arguments
57539             var effectiveParameterCount = getParameterCount(signature);
57540             var effectiveMinimumArguments = getMinArgumentCount(signature);
57541             if (node.kind === 198 /* TaggedTemplateExpression */) {
57542                 argCount = args.length;
57543                 if (node.template.kind === 211 /* TemplateExpression */) {
57544                     // If a tagged template expression lacks a tail literal, the call is incomplete.
57545                     // Specifically, a template only can end in a TemplateTail or a Missing literal.
57546                     var lastSpan = ts.last(node.template.templateSpans); // we should always have at least one span.
57547                     callIsIncomplete = ts.nodeIsMissing(lastSpan.literal) || !!lastSpan.literal.isUnterminated;
57548                 }
57549                 else {
57550                     // If the template didn't end in a backtick, or its beginning occurred right prior to EOF,
57551                     // then this might actually turn out to be a TemplateHead in the future;
57552                     // so we consider the call to be incomplete.
57553                     var templateLiteral = node.template;
57554                     ts.Debug.assert(templateLiteral.kind === 14 /* NoSubstitutionTemplateLiteral */);
57555                     callIsIncomplete = !!templateLiteral.isUnterminated;
57556                 }
57557             }
57558             else if (node.kind === 157 /* Decorator */) {
57559                 argCount = getDecoratorArgumentCount(node, signature);
57560             }
57561             else if (ts.isJsxOpeningLikeElement(node)) {
57562                 callIsIncomplete = node.attributes.end === node.end;
57563                 if (callIsIncomplete) {
57564                     return true;
57565                 }
57566                 argCount = effectiveMinimumArguments === 0 ? args.length : 1;
57567                 effectiveParameterCount = args.length === 0 ? effectiveParameterCount : 1; // class may have argumentless ctor functions - still resolve ctor and compare vs props member type
57568                 effectiveMinimumArguments = Math.min(effectiveMinimumArguments, 1); // sfc may specify context argument - handled by framework and not typechecked
57569             }
57570             else {
57571                 if (!node.arguments) {
57572                     // This only happens when we have something of the form: 'new C'
57573                     ts.Debug.assert(node.kind === 197 /* NewExpression */);
57574                     return getMinArgumentCount(signature) === 0;
57575                 }
57576                 argCount = signatureHelpTrailingComma ? args.length + 1 : args.length;
57577                 // If we are missing the close parenthesis, the call is incomplete.
57578                 callIsIncomplete = node.arguments.end === node.end;
57579                 // If a spread argument is present, check that it corresponds to a rest parameter or at least that it's in the valid range.
57580                 var spreadArgIndex = getSpreadArgumentIndex(args);
57581                 if (spreadArgIndex >= 0) {
57582                     return spreadArgIndex >= getMinArgumentCount(signature) && (hasEffectiveRestParameter(signature) || spreadArgIndex < getParameterCount(signature));
57583                 }
57584             }
57585             // Too many arguments implies incorrect arity.
57586             if (!hasEffectiveRestParameter(signature) && argCount > effectiveParameterCount) {
57587                 return false;
57588             }
57589             // If the call is incomplete, we should skip the lower bound check.
57590             // JSX signatures can have extra parameters provided by the library which we don't check
57591             if (callIsIncomplete || argCount >= effectiveMinimumArguments) {
57592                 return true;
57593             }
57594             for (var i = argCount; i < effectiveMinimumArguments; i++) {
57595                 var type = getTypeAtPosition(signature, i);
57596                 if (filterType(type, acceptsVoid).flags & 131072 /* Never */) {
57597                     return false;
57598                 }
57599             }
57600             return true;
57601         }
57602         function hasCorrectTypeArgumentArity(signature, typeArguments) {
57603             // If the user supplied type arguments, but the number of type arguments does not match
57604             // the declared number of type parameters, the call has an incorrect arity.
57605             var numTypeParameters = ts.length(signature.typeParameters);
57606             var minTypeArgumentCount = getMinTypeArgumentCount(signature.typeParameters);
57607             return !ts.some(typeArguments) ||
57608                 (typeArguments.length >= minTypeArgumentCount && typeArguments.length <= numTypeParameters);
57609         }
57610         // If type has a single call signature and no other members, return that signature. Otherwise, return undefined.
57611         function getSingleCallSignature(type) {
57612             return getSingleSignature(type, 0 /* Call */, /*allowMembers*/ false);
57613         }
57614         function getSingleCallOrConstructSignature(type) {
57615             return getSingleSignature(type, 0 /* Call */, /*allowMembers*/ false) ||
57616                 getSingleSignature(type, 1 /* Construct */, /*allowMembers*/ false);
57617         }
57618         function getSingleSignature(type, kind, allowMembers) {
57619             if (type.flags & 524288 /* Object */) {
57620                 var resolved = resolveStructuredTypeMembers(type);
57621                 if (allowMembers || resolved.properties.length === 0 && !resolved.stringIndexInfo && !resolved.numberIndexInfo) {
57622                     if (kind === 0 /* Call */ && resolved.callSignatures.length === 1 && resolved.constructSignatures.length === 0) {
57623                         return resolved.callSignatures[0];
57624                     }
57625                     if (kind === 1 /* Construct */ && resolved.constructSignatures.length === 1 && resolved.callSignatures.length === 0) {
57626                         return resolved.constructSignatures[0];
57627                     }
57628                 }
57629             }
57630             return undefined;
57631         }
57632         // Instantiate a generic signature in the context of a non-generic signature (section 3.8.5 in TypeScript spec)
57633         function instantiateSignatureInContextOf(signature, contextualSignature, inferenceContext, compareTypes) {
57634             var context = createInferenceContext(signature.typeParameters, signature, 0 /* None */, compareTypes);
57635             // We clone the inferenceContext to avoid fixing. For example, when the source signature is <T>(x: T) => T[] and
57636             // the contextual signature is (...args: A) => B, we want to infer the element type of A's constraint (say 'any')
57637             // for T but leave it possible to later infer '[any]' back to A.
57638             var restType = getEffectiveRestType(contextualSignature);
57639             var mapper = inferenceContext && (restType && restType.flags & 262144 /* TypeParameter */ ? inferenceContext.nonFixingMapper : inferenceContext.mapper);
57640             var sourceSignature = mapper ? instantiateSignature(contextualSignature, mapper) : contextualSignature;
57641             applyToParameterTypes(sourceSignature, signature, function (source, target) {
57642                 // Type parameters from outer context referenced by source type are fixed by instantiation of the source type
57643                 inferTypes(context.inferences, source, target);
57644             });
57645             if (!inferenceContext) {
57646                 applyToReturnTypes(contextualSignature, signature, function (source, target) {
57647                     inferTypes(context.inferences, source, target, 32 /* ReturnType */);
57648                 });
57649             }
57650             return getSignatureInstantiation(signature, getInferredTypes(context), ts.isInJSFile(contextualSignature.declaration));
57651         }
57652         function inferJsxTypeArguments(node, signature, checkMode, context) {
57653             var paramType = getEffectiveFirstArgumentForJsxSignature(signature, node);
57654             var checkAttrType = checkExpressionWithContextualType(node.attributes, paramType, context, checkMode);
57655             inferTypes(context.inferences, checkAttrType, paramType);
57656             return getInferredTypes(context);
57657         }
57658         function inferTypeArguments(node, signature, args, checkMode, context) {
57659             if (ts.isJsxOpeningLikeElement(node)) {
57660                 return inferJsxTypeArguments(node, signature, checkMode, context);
57661             }
57662             // If a contextual type is available, infer from that type to the return type of the call expression. For
57663             // example, given a 'function wrap<T, U>(cb: (x: T) => U): (x: T) => U' and a call expression
57664             // 'let f: (x: string) => number = wrap(s => s.length)', we infer from the declared type of 'f' to the
57665             // return type of 'wrap'.
57666             if (node.kind !== 157 /* Decorator */) {
57667                 var contextualType = getContextualType(node);
57668                 if (contextualType) {
57669                     // We clone the inference context to avoid disturbing a resolution in progress for an
57670                     // outer call expression. Effectively we just want a snapshot of whatever has been
57671                     // inferred for any outer call expression so far.
57672                     var outerContext = getInferenceContext(node);
57673                     var outerMapper = getMapperFromContext(cloneInferenceContext(outerContext, 1 /* NoDefault */));
57674                     var instantiatedType = instantiateType(contextualType, outerMapper);
57675                     // If the contextual type is a generic function type with a single call signature, we
57676                     // instantiate the type with its own type parameters and type arguments. This ensures that
57677                     // the type parameters are not erased to type any during type inference such that they can
57678                     // be inferred as actual types from the contextual type. For example:
57679                     //   declare function arrayMap<T, U>(f: (x: T) => U): (a: T[]) => U[];
57680                     //   const boxElements: <A>(a: A[]) => { value: A }[] = arrayMap(value => ({ value }));
57681                     // Above, the type of the 'value' parameter is inferred to be 'A'.
57682                     var contextualSignature = getSingleCallSignature(instantiatedType);
57683                     var inferenceSourceType = contextualSignature && contextualSignature.typeParameters ?
57684                         getOrCreateTypeFromSignature(getSignatureInstantiationWithoutFillingInTypeArguments(contextualSignature, contextualSignature.typeParameters)) :
57685                         instantiatedType;
57686                     var inferenceTargetType = getReturnTypeOfSignature(signature);
57687                     // Inferences made from return types have lower priority than all other inferences.
57688                     inferTypes(context.inferences, inferenceSourceType, inferenceTargetType, 32 /* ReturnType */);
57689                     // Create a type mapper for instantiating generic contextual types using the inferences made
57690                     // from the return type. We need a separate inference pass here because (a) instantiation of
57691                     // the source type uses the outer context's return mapper (which excludes inferences made from
57692                     // outer arguments), and (b) we don't want any further inferences going into this context.
57693                     var returnContext = createInferenceContext(signature.typeParameters, signature, context.flags);
57694                     var returnSourceType = instantiateType(contextualType, outerContext && outerContext.returnMapper);
57695                     inferTypes(returnContext.inferences, returnSourceType, inferenceTargetType);
57696                     context.returnMapper = ts.some(returnContext.inferences, hasInferenceCandidates) ? getMapperFromContext(cloneInferredPartOfContext(returnContext)) : undefined;
57697                 }
57698             }
57699             var thisType = getThisTypeOfSignature(signature);
57700             if (thisType) {
57701                 var thisArgumentNode = getThisArgumentOfCall(node);
57702                 var thisArgumentType = thisArgumentNode ? checkExpression(thisArgumentNode) : voidType;
57703                 inferTypes(context.inferences, thisArgumentType, thisType);
57704             }
57705             var restType = getNonArrayRestType(signature);
57706             var argCount = restType ? Math.min(getParameterCount(signature) - 1, args.length) : args.length;
57707             for (var i = 0; i < argCount; i++) {
57708                 var arg = args[i];
57709                 if (arg.kind !== 215 /* OmittedExpression */) {
57710                     var paramType = getTypeAtPosition(signature, i);
57711                     var argType = checkExpressionWithContextualType(arg, paramType, context, checkMode);
57712                     inferTypes(context.inferences, argType, paramType);
57713                 }
57714             }
57715             if (restType) {
57716                 var spreadType = getSpreadArgumentType(args, argCount, args.length, restType, context);
57717                 inferTypes(context.inferences, spreadType, restType);
57718             }
57719             return getInferredTypes(context);
57720         }
57721         function getArrayifiedType(type) {
57722             return type.flags & 1048576 /* Union */ ? mapType(type, getArrayifiedType) :
57723                 type.flags & (1 /* Any */ | 63176704 /* Instantiable */) || isMutableArrayOrTuple(type) ? type :
57724                     isTupleType(type) ? createTupleType(getTypeArguments(type), type.target.minLength, type.target.hasRestElement, /*readonly*/ false, type.target.associatedNames) :
57725                         createArrayType(getIndexedAccessType(type, numberType));
57726         }
57727         function getSpreadArgumentType(args, index, argCount, restType, context) {
57728             if (index >= argCount - 1) {
57729                 var arg = args[argCount - 1];
57730                 if (isSpreadArgument(arg)) {
57731                     // We are inferring from a spread expression in the last argument position, i.e. both the parameter
57732                     // and the argument are ...x forms.
57733                     return arg.kind === 220 /* SyntheticExpression */ ?
57734                         createArrayType(arg.type) :
57735                         getArrayifiedType(checkExpressionWithContextualType(arg.expression, restType, context, 0 /* Normal */));
57736                 }
57737             }
57738             var types = [];
57739             var spreadIndex = -1;
57740             for (var i = index; i < argCount; i++) {
57741                 var contextualType = getIndexedAccessType(restType, getLiteralType(i - index));
57742                 var argType = checkExpressionWithContextualType(args[i], contextualType, context, 0 /* Normal */);
57743                 if (spreadIndex < 0 && isSpreadArgument(args[i])) {
57744                     spreadIndex = i - index;
57745                 }
57746                 var hasPrimitiveContextualType = maybeTypeOfKind(contextualType, 131068 /* Primitive */ | 4194304 /* Index */);
57747                 types.push(hasPrimitiveContextualType ? getRegularTypeOfLiteralType(argType) : getWidenedLiteralType(argType));
57748             }
57749             return spreadIndex < 0 ?
57750                 createTupleType(types) :
57751                 createTupleType(ts.append(types.slice(0, spreadIndex), getUnionType(types.slice(spreadIndex))), spreadIndex, /*hasRestElement*/ true);
57752         }
57753         function checkTypeArguments(signature, typeArgumentNodes, reportErrors, headMessage) {
57754             var isJavascript = ts.isInJSFile(signature.declaration);
57755             var typeParameters = signature.typeParameters;
57756             var typeArgumentTypes = fillMissingTypeArguments(ts.map(typeArgumentNodes, getTypeFromTypeNode), typeParameters, getMinTypeArgumentCount(typeParameters), isJavascript);
57757             var mapper;
57758             for (var i = 0; i < typeArgumentNodes.length; i++) {
57759                 ts.Debug.assert(typeParameters[i] !== undefined, "Should not call checkTypeArguments with too many type arguments");
57760                 var constraint = getConstraintOfTypeParameter(typeParameters[i]);
57761                 if (constraint) {
57762                     var errorInfo = reportErrors && headMessage ? (function () { return ts.chainDiagnosticMessages(/*details*/ undefined, ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1); }) : undefined;
57763                     var typeArgumentHeadMessage = headMessage || ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1;
57764                     if (!mapper) {
57765                         mapper = createTypeMapper(typeParameters, typeArgumentTypes);
57766                     }
57767                     var typeArgument = typeArgumentTypes[i];
57768                     if (!checkTypeAssignableTo(typeArgument, getTypeWithThisArgument(instantiateType(constraint, mapper), typeArgument), reportErrors ? typeArgumentNodes[i] : undefined, typeArgumentHeadMessage, errorInfo)) {
57769                         return undefined;
57770                     }
57771                 }
57772             }
57773             return typeArgumentTypes;
57774         }
57775         function getJsxReferenceKind(node) {
57776             if (isJsxIntrinsicIdentifier(node.tagName)) {
57777                 return 2 /* Mixed */;
57778             }
57779             var tagType = getApparentType(checkExpression(node.tagName));
57780             if (ts.length(getSignaturesOfType(tagType, 1 /* Construct */))) {
57781                 return 0 /* Component */;
57782             }
57783             if (ts.length(getSignaturesOfType(tagType, 0 /* Call */))) {
57784                 return 1 /* Function */;
57785             }
57786             return 2 /* Mixed */;
57787         }
57788         /**
57789          * Check if the given signature can possibly be a signature called by the JSX opening-like element.
57790          * @param node a JSX opening-like element we are trying to figure its call signature
57791          * @param signature a candidate signature we are trying whether it is a call signature
57792          * @param relation a relationship to check parameter and argument type
57793          */
57794         function checkApplicableSignatureForJsxOpeningLikeElement(node, signature, relation, checkMode, reportErrors, containingMessageChain, errorOutputContainer) {
57795             // Stateless function components can have maximum of three arguments: "props", "context", and "updater".
57796             // However "context" and "updater" are implicit and can't be specify by users. Only the first parameter, props,
57797             // can be specified by users through attributes property.
57798             var paramType = getEffectiveFirstArgumentForJsxSignature(signature, node);
57799             var attributesType = checkExpressionWithContextualType(node.attributes, paramType, /*inferenceContext*/ undefined, checkMode);
57800             return checkTagNameDoesNotExpectTooManyArguments() && checkTypeRelatedToAndOptionallyElaborate(attributesType, paramType, relation, reportErrors ? node.tagName : undefined, node.attributes, 
57801             /*headMessage*/ undefined, containingMessageChain, errorOutputContainer);
57802             function checkTagNameDoesNotExpectTooManyArguments() {
57803                 var _a;
57804                 var tagType = ts.isJsxOpeningElement(node) || ts.isJsxSelfClosingElement(node) && !isJsxIntrinsicIdentifier(node.tagName) ? checkExpression(node.tagName) : undefined;
57805                 if (!tagType) {
57806                     return true;
57807                 }
57808                 var tagCallSignatures = getSignaturesOfType(tagType, 0 /* Call */);
57809                 if (!ts.length(tagCallSignatures)) {
57810                     return true;
57811                 }
57812                 var factory = getJsxFactoryEntity(node);
57813                 if (!factory) {
57814                     return true;
57815                 }
57816                 var factorySymbol = resolveEntityName(factory, 111551 /* Value */, /*ignoreErrors*/ true, /*dontResolveAlias*/ false, node);
57817                 if (!factorySymbol) {
57818                     return true;
57819                 }
57820                 var factoryType = getTypeOfSymbol(factorySymbol);
57821                 var callSignatures = getSignaturesOfType(factoryType, 0 /* Call */);
57822                 if (!ts.length(callSignatures)) {
57823                     return true;
57824                 }
57825                 var hasFirstParamSignatures = false;
57826                 var maxParamCount = 0;
57827                 // Check that _some_ first parameter expects a FC-like thing, and that some overload of the SFC expects an acceptable number of arguments
57828                 for (var _i = 0, callSignatures_1 = callSignatures; _i < callSignatures_1.length; _i++) {
57829                     var sig = callSignatures_1[_i];
57830                     var firstparam = getTypeAtPosition(sig, 0);
57831                     var signaturesOfParam = getSignaturesOfType(firstparam, 0 /* Call */);
57832                     if (!ts.length(signaturesOfParam))
57833                         continue;
57834                     for (var _b = 0, signaturesOfParam_1 = signaturesOfParam; _b < signaturesOfParam_1.length; _b++) {
57835                         var paramSig = signaturesOfParam_1[_b];
57836                         hasFirstParamSignatures = true;
57837                         if (hasEffectiveRestParameter(paramSig)) {
57838                             return true; // some signature has a rest param, so function components can have an arbitrary number of arguments
57839                         }
57840                         var paramCount = getParameterCount(paramSig);
57841                         if (paramCount > maxParamCount) {
57842                             maxParamCount = paramCount;
57843                         }
57844                     }
57845                 }
57846                 if (!hasFirstParamSignatures) {
57847                     // Not a single signature had a first parameter which expected a signature - for back compat, and
57848                     // to guard against generic factories which won't have signatures directly, do not error
57849                     return true;
57850                 }
57851                 var absoluteMinArgCount = Infinity;
57852                 for (var _c = 0, tagCallSignatures_1 = tagCallSignatures; _c < tagCallSignatures_1.length; _c++) {
57853                     var tagSig = tagCallSignatures_1[_c];
57854                     var tagRequiredArgCount = getMinArgumentCount(tagSig);
57855                     if (tagRequiredArgCount < absoluteMinArgCount) {
57856                         absoluteMinArgCount = tagRequiredArgCount;
57857                     }
57858                 }
57859                 if (absoluteMinArgCount <= maxParamCount) {
57860                     return true; // some signature accepts the number of arguments the function component provides
57861                 }
57862                 if (reportErrors) {
57863                     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);
57864                     var tagNameDeclaration = (_a = getSymbolAtLocation(node.tagName)) === null || _a === void 0 ? void 0 : _a.valueDeclaration;
57865                     if (tagNameDeclaration) {
57866                         ts.addRelatedInfo(diag, ts.createDiagnosticForNode(tagNameDeclaration, ts.Diagnostics._0_is_declared_here, ts.entityNameToString(node.tagName)));
57867                     }
57868                     if (errorOutputContainer && errorOutputContainer.skipLogging) {
57869                         (errorOutputContainer.errors || (errorOutputContainer.errors = [])).push(diag);
57870                     }
57871                     if (!errorOutputContainer.skipLogging) {
57872                         diagnostics.add(diag);
57873                     }
57874                 }
57875                 return false;
57876             }
57877         }
57878         function getSignatureApplicabilityError(node, args, signature, relation, checkMode, reportErrors, containingMessageChain) {
57879             var errorOutputContainer = { errors: undefined, skipLogging: true };
57880             if (ts.isJsxOpeningLikeElement(node)) {
57881                 if (!checkApplicableSignatureForJsxOpeningLikeElement(node, signature, relation, checkMode, reportErrors, containingMessageChain, errorOutputContainer)) {
57882                     ts.Debug.assert(!reportErrors || !!errorOutputContainer.errors, "jsx should have errors when reporting errors");
57883                     return errorOutputContainer.errors || ts.emptyArray;
57884                 }
57885                 return undefined;
57886             }
57887             var thisType = getThisTypeOfSignature(signature);
57888             if (thisType && thisType !== voidType && node.kind !== 197 /* NewExpression */) {
57889                 // If the called expression is not of the form `x.f` or `x["f"]`, then sourceType = voidType
57890                 // If the signature's 'this' type is voidType, then the check is skipped -- anything is compatible.
57891                 // If the expression is a new expression, then the check is skipped.
57892                 var thisArgumentNode = getThisArgumentOfCall(node);
57893                 var thisArgumentType = void 0;
57894                 if (thisArgumentNode) {
57895                     thisArgumentType = checkExpression(thisArgumentNode);
57896                     if (ts.isOptionalChainRoot(thisArgumentNode.parent)) {
57897                         thisArgumentType = getNonNullableType(thisArgumentType);
57898                     }
57899                     else if (ts.isOptionalChain(thisArgumentNode.parent)) {
57900                         thisArgumentType = removeOptionalTypeMarker(thisArgumentType);
57901                     }
57902                 }
57903                 else {
57904                     thisArgumentType = voidType;
57905                 }
57906                 var errorNode = reportErrors ? (thisArgumentNode || node) : undefined;
57907                 var headMessage_1 = ts.Diagnostics.The_this_context_of_type_0_is_not_assignable_to_method_s_this_of_type_1;
57908                 if (!checkTypeRelatedTo(thisArgumentType, thisType, relation, errorNode, headMessage_1, containingMessageChain, errorOutputContainer)) {
57909                     ts.Debug.assert(!reportErrors || !!errorOutputContainer.errors, "this parameter should have errors when reporting errors");
57910                     return errorOutputContainer.errors || ts.emptyArray;
57911                 }
57912             }
57913             var headMessage = ts.Diagnostics.Argument_of_type_0_is_not_assignable_to_parameter_of_type_1;
57914             var restType = getNonArrayRestType(signature);
57915             var argCount = restType ? Math.min(getParameterCount(signature) - 1, args.length) : args.length;
57916             for (var i = 0; i < argCount; i++) {
57917                 var arg = args[i];
57918                 if (arg.kind !== 215 /* OmittedExpression */) {
57919                     var paramType = getTypeAtPosition(signature, i);
57920                     var argType = checkExpressionWithContextualType(arg, paramType, /*inferenceContext*/ undefined, checkMode);
57921                     // If one or more arguments are still excluded (as indicated by CheckMode.SkipContextSensitive),
57922                     // we obtain the regular type of any object literal arguments because we may not have inferred complete
57923                     // parameter types yet and therefore excess property checks may yield false positives (see #17041).
57924                     var checkArgType = checkMode & 4 /* SkipContextSensitive */ ? getRegularTypeOfObjectLiteral(argType) : argType;
57925                     if (!checkTypeRelatedToAndOptionallyElaborate(checkArgType, paramType, relation, reportErrors ? arg : undefined, arg, headMessage, containingMessageChain, errorOutputContainer)) {
57926                         ts.Debug.assert(!reportErrors || !!errorOutputContainer.errors, "parameter should have errors when reporting errors");
57927                         maybeAddMissingAwaitInfo(arg, checkArgType, paramType);
57928                         return errorOutputContainer.errors || ts.emptyArray;
57929                     }
57930                 }
57931             }
57932             if (restType) {
57933                 var spreadType = getSpreadArgumentType(args, argCount, args.length, restType, /*context*/ undefined);
57934                 var errorNode = reportErrors ? argCount < args.length ? args[argCount] : node : undefined;
57935                 if (!checkTypeRelatedTo(spreadType, restType, relation, errorNode, headMessage, /*containingMessageChain*/ undefined, errorOutputContainer)) {
57936                     ts.Debug.assert(!reportErrors || !!errorOutputContainer.errors, "rest parameter should have errors when reporting errors");
57937                     maybeAddMissingAwaitInfo(errorNode, spreadType, restType);
57938                     return errorOutputContainer.errors || ts.emptyArray;
57939                 }
57940             }
57941             return undefined;
57942             function maybeAddMissingAwaitInfo(errorNode, source, target) {
57943                 if (errorNode && reportErrors && errorOutputContainer.errors && errorOutputContainer.errors.length) {
57944                     // Bail if target is Promise-like---something else is wrong
57945                     if (getAwaitedTypeOfPromise(target)) {
57946                         return;
57947                     }
57948                     var awaitedTypeOfSource = getAwaitedTypeOfPromise(source);
57949                     if (awaitedTypeOfSource && isTypeRelatedTo(awaitedTypeOfSource, target, relation)) {
57950                         ts.addRelatedInfo(errorOutputContainer.errors[0], ts.createDiagnosticForNode(errorNode, ts.Diagnostics.Did_you_forget_to_use_await));
57951                     }
57952                 }
57953             }
57954         }
57955         /**
57956          * Returns the this argument in calls like x.f(...) and x[f](...). Undefined otherwise.
57957          */
57958         function getThisArgumentOfCall(node) {
57959             if (node.kind === 196 /* CallExpression */) {
57960                 var callee = ts.skipOuterExpressions(node.expression);
57961                 if (ts.isAccessExpression(callee)) {
57962                     return callee.expression;
57963                 }
57964             }
57965         }
57966         function createSyntheticExpression(parent, type, isSpread) {
57967             var result = ts.createNode(220 /* SyntheticExpression */, parent.pos, parent.end);
57968             result.parent = parent;
57969             result.type = type;
57970             result.isSpread = isSpread || false;
57971             return result;
57972         }
57973         /**
57974          * Returns the effective arguments for an expression that works like a function invocation.
57975          */
57976         function getEffectiveCallArguments(node) {
57977             if (node.kind === 198 /* TaggedTemplateExpression */) {
57978                 var template = node.template;
57979                 var args_3 = [createSyntheticExpression(template, getGlobalTemplateStringsArrayType())];
57980                 if (template.kind === 211 /* TemplateExpression */) {
57981                     ts.forEach(template.templateSpans, function (span) {
57982                         args_3.push(span.expression);
57983                     });
57984                 }
57985                 return args_3;
57986             }
57987             if (node.kind === 157 /* Decorator */) {
57988                 return getEffectiveDecoratorArguments(node);
57989             }
57990             if (ts.isJsxOpeningLikeElement(node)) {
57991                 return node.attributes.properties.length > 0 || (ts.isJsxOpeningElement(node) && node.parent.children.length > 0) ? [node.attributes] : ts.emptyArray;
57992             }
57993             var args = node.arguments || ts.emptyArray;
57994             var length = args.length;
57995             if (length && isSpreadArgument(args[length - 1]) && getSpreadArgumentIndex(args) === length - 1) {
57996                 // We have a spread argument in the last position and no other spread arguments. If the type
57997                 // of the argument is a tuple type, spread the tuple elements into the argument list. We can
57998                 // call checkExpressionCached because spread expressions never have a contextual type.
57999                 var spreadArgument_1 = args[length - 1];
58000                 var type = flowLoopCount ? checkExpression(spreadArgument_1.expression) : checkExpressionCached(spreadArgument_1.expression);
58001                 if (isTupleType(type)) {
58002                     var typeArguments = getTypeArguments(type);
58003                     var restIndex_2 = type.target.hasRestElement ? typeArguments.length - 1 : -1;
58004                     var syntheticArgs = ts.map(typeArguments, function (t, i) { return createSyntheticExpression(spreadArgument_1, t, /*isSpread*/ i === restIndex_2); });
58005                     return ts.concatenate(args.slice(0, length - 1), syntheticArgs);
58006                 }
58007             }
58008             return args;
58009         }
58010         /**
58011          * Returns the synthetic argument list for a decorator invocation.
58012          */
58013         function getEffectiveDecoratorArguments(node) {
58014             var parent = node.parent;
58015             var expr = node.expression;
58016             switch (parent.kind) {
58017                 case 245 /* ClassDeclaration */:
58018                 case 214 /* ClassExpression */:
58019                     // For a class decorator, the `target` is the type of the class (e.g. the
58020                     // "static" or "constructor" side of the class).
58021                     return [
58022                         createSyntheticExpression(expr, getTypeOfSymbol(getSymbolOfNode(parent)))
58023                     ];
58024                 case 156 /* Parameter */:
58025                     // A parameter declaration decorator will have three arguments (see
58026                     // `ParameterDecorator` in core.d.ts).
58027                     var func = parent.parent;
58028                     return [
58029                         createSyntheticExpression(expr, parent.parent.kind === 162 /* Constructor */ ? getTypeOfSymbol(getSymbolOfNode(func)) : errorType),
58030                         createSyntheticExpression(expr, anyType),
58031                         createSyntheticExpression(expr, numberType)
58032                     ];
58033                 case 159 /* PropertyDeclaration */:
58034                 case 161 /* MethodDeclaration */:
58035                 case 163 /* GetAccessor */:
58036                 case 164 /* SetAccessor */:
58037                     // A method or accessor declaration decorator will have two or three arguments (see
58038                     // `PropertyDecorator` and `MethodDecorator` in core.d.ts). If we are emitting decorators
58039                     // for ES3, we will only pass two arguments.
58040                     var hasPropDesc = parent.kind !== 159 /* PropertyDeclaration */ && languageVersion !== 0 /* ES3 */;
58041                     return [
58042                         createSyntheticExpression(expr, getParentTypeOfClassElement(parent)),
58043                         createSyntheticExpression(expr, getClassElementPropertyKeyType(parent)),
58044                         createSyntheticExpression(expr, hasPropDesc ? createTypedPropertyDescriptorType(getTypeOfNode(parent)) : anyType)
58045                     ];
58046             }
58047             return ts.Debug.fail();
58048         }
58049         /**
58050          * Returns the argument count for a decorator node that works like a function invocation.
58051          */
58052         function getDecoratorArgumentCount(node, signature) {
58053             switch (node.parent.kind) {
58054                 case 245 /* ClassDeclaration */:
58055                 case 214 /* ClassExpression */:
58056                     return 1;
58057                 case 159 /* PropertyDeclaration */:
58058                     return 2;
58059                 case 161 /* MethodDeclaration */:
58060                 case 163 /* GetAccessor */:
58061                 case 164 /* SetAccessor */:
58062                     // For ES3 or decorators with only two parameters we supply only two arguments
58063                     return languageVersion === 0 /* ES3 */ || signature.parameters.length <= 2 ? 2 : 3;
58064                 case 156 /* Parameter */:
58065                     return 3;
58066                 default:
58067                     return ts.Debug.fail();
58068             }
58069         }
58070         function getDiagnosticSpanForCallNode(node, doNotIncludeArguments) {
58071             var start;
58072             var length;
58073             var sourceFile = ts.getSourceFileOfNode(node);
58074             if (ts.isPropertyAccessExpression(node.expression)) {
58075                 var nameSpan = ts.getErrorSpanForNode(sourceFile, node.expression.name);
58076                 start = nameSpan.start;
58077                 length = doNotIncludeArguments ? nameSpan.length : node.end - start;
58078             }
58079             else {
58080                 var expressionSpan = ts.getErrorSpanForNode(sourceFile, node.expression);
58081                 start = expressionSpan.start;
58082                 length = doNotIncludeArguments ? expressionSpan.length : node.end - start;
58083             }
58084             return { start: start, length: length, sourceFile: sourceFile };
58085         }
58086         function getDiagnosticForCallNode(node, message, arg0, arg1, arg2, arg3) {
58087             if (ts.isCallExpression(node)) {
58088                 var _a = getDiagnosticSpanForCallNode(node), sourceFile = _a.sourceFile, start = _a.start, length_5 = _a.length;
58089                 return ts.createFileDiagnostic(sourceFile, start, length_5, message, arg0, arg1, arg2, arg3);
58090             }
58091             else {
58092                 return ts.createDiagnosticForNode(node, message, arg0, arg1, arg2, arg3);
58093             }
58094         }
58095         function getArgumentArityError(node, signatures, args) {
58096             var min = Number.POSITIVE_INFINITY;
58097             var max = Number.NEGATIVE_INFINITY;
58098             var belowArgCount = Number.NEGATIVE_INFINITY;
58099             var aboveArgCount = Number.POSITIVE_INFINITY;
58100             var argCount = args.length;
58101             var closestSignature;
58102             for (var _i = 0, signatures_8 = signatures; _i < signatures_8.length; _i++) {
58103                 var sig = signatures_8[_i];
58104                 var minCount = getMinArgumentCount(sig);
58105                 var maxCount = getParameterCount(sig);
58106                 if (minCount < argCount && minCount > belowArgCount)
58107                     belowArgCount = minCount;
58108                 if (argCount < maxCount && maxCount < aboveArgCount)
58109                     aboveArgCount = maxCount;
58110                 if (minCount < min) {
58111                     min = minCount;
58112                     closestSignature = sig;
58113                 }
58114                 max = Math.max(max, maxCount);
58115             }
58116             var hasRestParameter = ts.some(signatures, hasEffectiveRestParameter);
58117             var paramRange = hasRestParameter ? min :
58118                 min < max ? min + "-" + max :
58119                     min;
58120             var hasSpreadArgument = getSpreadArgumentIndex(args) > -1;
58121             if (argCount <= max && hasSpreadArgument) {
58122                 argCount--;
58123             }
58124             var spanArray;
58125             var related;
58126             var error = hasRestParameter || hasSpreadArgument ? hasRestParameter && hasSpreadArgument ? ts.Diagnostics.Expected_at_least_0_arguments_but_got_1_or_more :
58127                 hasRestParameter ? ts.Diagnostics.Expected_at_least_0_arguments_but_got_1 :
58128                     ts.Diagnostics.Expected_0_arguments_but_got_1_or_more : ts.Diagnostics.Expected_0_arguments_but_got_1;
58129             if (closestSignature && getMinArgumentCount(closestSignature) > argCount && closestSignature.declaration) {
58130                 var paramDecl = closestSignature.declaration.parameters[closestSignature.thisParameter ? argCount + 1 : argCount];
58131                 if (paramDecl) {
58132                     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);
58133                 }
58134             }
58135             if (min < argCount && argCount < max) {
58136                 return getDiagnosticForCallNode(node, ts.Diagnostics.No_overload_expects_0_arguments_but_overloads_do_exist_that_expect_either_1_or_2_arguments, argCount, belowArgCount, aboveArgCount);
58137             }
58138             if (!hasSpreadArgument && argCount < min) {
58139                 var diagnostic_1 = getDiagnosticForCallNode(node, error, paramRange, argCount);
58140                 return related ? ts.addRelatedInfo(diagnostic_1, related) : diagnostic_1;
58141             }
58142             if (hasRestParameter || hasSpreadArgument) {
58143                 spanArray = ts.createNodeArray(args);
58144                 if (hasSpreadArgument && argCount) {
58145                     var nextArg = ts.elementAt(args, getSpreadArgumentIndex(args) + 1) || undefined;
58146                     spanArray = ts.createNodeArray(args.slice(max > argCount && nextArg ? args.indexOf(nextArg) : Math.min(max, args.length - 1)));
58147                 }
58148             }
58149             else {
58150                 spanArray = ts.createNodeArray(args.slice(max));
58151             }
58152             spanArray.pos = ts.first(spanArray).pos;
58153             spanArray.end = ts.last(spanArray).end;
58154             if (spanArray.end === spanArray.pos) {
58155                 spanArray.end++;
58156             }
58157             var diagnostic = ts.createDiagnosticForNodeArray(ts.getSourceFileOfNode(node), spanArray, error, paramRange, argCount);
58158             return related ? ts.addRelatedInfo(diagnostic, related) : diagnostic;
58159         }
58160         function getTypeArgumentArityError(node, signatures, typeArguments) {
58161             var argCount = typeArguments.length;
58162             // No overloads exist
58163             if (signatures.length === 1) {
58164                 var sig = signatures[0];
58165                 var min_1 = getMinTypeArgumentCount(sig.typeParameters);
58166                 var max = ts.length(sig.typeParameters);
58167                 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);
58168             }
58169             // Overloads exist
58170             var belowArgCount = -Infinity;
58171             var aboveArgCount = Infinity;
58172             for (var _i = 0, signatures_9 = signatures; _i < signatures_9.length; _i++) {
58173                 var sig = signatures_9[_i];
58174                 var min_2 = getMinTypeArgumentCount(sig.typeParameters);
58175                 var max = ts.length(sig.typeParameters);
58176                 if (min_2 > argCount) {
58177                     aboveArgCount = Math.min(aboveArgCount, min_2);
58178                 }
58179                 else if (max < argCount) {
58180                     belowArgCount = Math.max(belowArgCount, max);
58181                 }
58182             }
58183             if (belowArgCount !== -Infinity && aboveArgCount !== Infinity) {
58184                 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);
58185             }
58186             return ts.createDiagnosticForNodeArray(ts.getSourceFileOfNode(node), typeArguments, ts.Diagnostics.Expected_0_type_arguments_but_got_1, belowArgCount === -Infinity ? aboveArgCount : belowArgCount, argCount);
58187         }
58188         function resolveCall(node, signatures, candidatesOutArray, checkMode, callChainFlags, fallbackError) {
58189             var isTaggedTemplate = node.kind === 198 /* TaggedTemplateExpression */;
58190             var isDecorator = node.kind === 157 /* Decorator */;
58191             var isJsxOpeningOrSelfClosingElement = ts.isJsxOpeningLikeElement(node);
58192             var reportErrors = !candidatesOutArray;
58193             var typeArguments;
58194             if (!isDecorator) {
58195                 typeArguments = node.typeArguments;
58196                 // We already perform checking on the type arguments on the class declaration itself.
58197                 if (isTaggedTemplate || isJsxOpeningOrSelfClosingElement || node.expression.kind !== 102 /* SuperKeyword */) {
58198                     ts.forEach(typeArguments, checkSourceElement);
58199                 }
58200             }
58201             var candidates = candidatesOutArray || [];
58202             // reorderCandidates fills up the candidates array directly
58203             reorderCandidates(signatures, candidates, callChainFlags);
58204             if (!candidates.length) {
58205                 if (reportErrors) {
58206                     diagnostics.add(getDiagnosticForCallNode(node, ts.Diagnostics.Call_target_does_not_contain_any_signatures));
58207                 }
58208                 return resolveErrorCall(node);
58209             }
58210             var args = getEffectiveCallArguments(node);
58211             // The excludeArgument array contains true for each context sensitive argument (an argument
58212             // is context sensitive it is susceptible to a one-time permanent contextual typing).
58213             //
58214             // The idea is that we will perform type argument inference & assignability checking once
58215             // without using the susceptible parameters that are functions, and once more for those
58216             // parameters, contextually typing each as we go along.
58217             //
58218             // For a tagged template, then the first argument be 'undefined' if necessary because it
58219             // represents a TemplateStringsArray.
58220             //
58221             // For a decorator, no arguments are susceptible to contextual typing due to the fact
58222             // decorators are applied to a declaration by the emitter, and not to an expression.
58223             var isSingleNonGenericCandidate = candidates.length === 1 && !candidates[0].typeParameters;
58224             var argCheckMode = !isDecorator && !isSingleNonGenericCandidate && ts.some(args, isContextSensitive) ? 4 /* SkipContextSensitive */ : 0 /* Normal */;
58225             // The following variables are captured and modified by calls to chooseOverload.
58226             // If overload resolution or type argument inference fails, we want to report the
58227             // best error possible. The best error is one which says that an argument was not
58228             // assignable to a parameter. This implies that everything else about the overload
58229             // was fine. So if there is any overload that is only incorrect because of an
58230             // argument, we will report an error on that one.
58231             //
58232             //     function foo(s: string): void;
58233             //     function foo(n: number): void; // Report argument error on this overload
58234             //     function foo(): void;
58235             //     foo(true);
58236             //
58237             // If none of the overloads even made it that far, there are two possibilities.
58238             // There was a problem with type arguments for some overload, in which case
58239             // report an error on that. Or none of the overloads even had correct arity,
58240             // in which case give an arity error.
58241             //
58242             //     function foo<T extends string>(x: T): void; // Report type argument error
58243             //     function foo(): void;
58244             //     foo<number>(0);
58245             //
58246             var candidatesForArgumentError;
58247             var candidateForArgumentArityError;
58248             var candidateForTypeArgumentError;
58249             var result;
58250             // If we are in signature help, a trailing comma indicates that we intend to provide another argument,
58251             // so we will only accept overloads with arity at least 1 higher than the current number of provided arguments.
58252             var signatureHelpTrailingComma = !!(checkMode & 16 /* IsForSignatureHelp */) && node.kind === 196 /* CallExpression */ && node.arguments.hasTrailingComma;
58253             // Section 4.12.1:
58254             // if the candidate list contains one or more signatures for which the type of each argument
58255             // expression is a subtype of each corresponding parameter type, the return type of the first
58256             // of those signatures becomes the return type of the function call.
58257             // Otherwise, the return type of the first signature in the candidate list becomes the return
58258             // type of the function call.
58259             //
58260             // Whether the call is an error is determined by assignability of the arguments. The subtype pass
58261             // is just important for choosing the best signature. So in the case where there is only one
58262             // signature, the subtype pass is useless. So skipping it is an optimization.
58263             if (candidates.length > 1) {
58264                 result = chooseOverload(candidates, subtypeRelation, signatureHelpTrailingComma);
58265             }
58266             if (!result) {
58267                 result = chooseOverload(candidates, assignableRelation, signatureHelpTrailingComma);
58268             }
58269             if (result) {
58270                 return result;
58271             }
58272             // No signatures were applicable. Now report errors based on the last applicable signature with
58273             // no arguments excluded from assignability checks.
58274             // If candidate is undefined, it means that no candidates had a suitable arity. In that case,
58275             // skip the checkApplicableSignature check.
58276             if (reportErrors) {
58277                 if (candidatesForArgumentError) {
58278                     if (candidatesForArgumentError.length === 1 || candidatesForArgumentError.length > 3) {
58279                         var last_2 = candidatesForArgumentError[candidatesForArgumentError.length - 1];
58280                         var chain_1;
58281                         if (candidatesForArgumentError.length > 3) {
58282                             chain_1 = ts.chainDiagnosticMessages(chain_1, ts.Diagnostics.The_last_overload_gave_the_following_error);
58283                             chain_1 = ts.chainDiagnosticMessages(chain_1, ts.Diagnostics.No_overload_matches_this_call);
58284                         }
58285                         var diags = getSignatureApplicabilityError(node, args, last_2, assignableRelation, 0 /* Normal */, /*reportErrors*/ true, function () { return chain_1; });
58286                         if (diags) {
58287                             for (var _i = 0, diags_1 = diags; _i < diags_1.length; _i++) {
58288                                 var d = diags_1[_i];
58289                                 if (last_2.declaration && candidatesForArgumentError.length > 3) {
58290                                     ts.addRelatedInfo(d, ts.createDiagnosticForNode(last_2.declaration, ts.Diagnostics.The_last_overload_is_declared_here));
58291                                 }
58292                                 diagnostics.add(d);
58293                             }
58294                         }
58295                         else {
58296                             ts.Debug.fail("No error for last overload signature");
58297                         }
58298                     }
58299                     else {
58300                         var allDiagnostics = [];
58301                         var max = 0;
58302                         var min_3 = Number.MAX_VALUE;
58303                         var minIndex = 0;
58304                         var i_1 = 0;
58305                         var _loop_17 = function (c) {
58306                             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)); };
58307                             var diags_2 = getSignatureApplicabilityError(node, args, c, assignableRelation, 0 /* Normal */, /*reportErrors*/ true, chain_2);
58308                             if (diags_2) {
58309                                 if (diags_2.length <= min_3) {
58310                                     min_3 = diags_2.length;
58311                                     minIndex = i_1;
58312                                 }
58313                                 max = Math.max(max, diags_2.length);
58314                                 allDiagnostics.push(diags_2);
58315                             }
58316                             else {
58317                                 ts.Debug.fail("No error for 3 or fewer overload signatures");
58318                             }
58319                             i_1++;
58320                         };
58321                         for (var _a = 0, candidatesForArgumentError_1 = candidatesForArgumentError; _a < candidatesForArgumentError_1.length; _a++) {
58322                             var c = candidatesForArgumentError_1[_a];
58323                             _loop_17(c);
58324                         }
58325                         var diags_3 = max > 1 ? allDiagnostics[minIndex] : ts.flatten(allDiagnostics);
58326                         ts.Debug.assert(diags_3.length > 0, "No errors reported for 3 or fewer overload signatures");
58327                         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);
58328                         var related = ts.flatMap(diags_3, function (d) { return d.relatedInformation; });
58329                         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; })) {
58330                             var _b = diags_3[0], file = _b.file, start = _b.start, length_6 = _b.length;
58331                             diagnostics.add({ file: file, start: start, length: length_6, code: chain.code, category: chain.category, messageText: chain, relatedInformation: related });
58332                         }
58333                         else {
58334                             diagnostics.add(ts.createDiagnosticForNodeFromMessageChain(node, chain, related));
58335                         }
58336                     }
58337                 }
58338                 else if (candidateForArgumentArityError) {
58339                     diagnostics.add(getArgumentArityError(node, [candidateForArgumentArityError], args));
58340                 }
58341                 else if (candidateForTypeArgumentError) {
58342                     checkTypeArguments(candidateForTypeArgumentError, node.typeArguments, /*reportErrors*/ true, fallbackError);
58343                 }
58344                 else {
58345                     var signaturesWithCorrectTypeArgumentArity = ts.filter(signatures, function (s) { return hasCorrectTypeArgumentArity(s, typeArguments); });
58346                     if (signaturesWithCorrectTypeArgumentArity.length === 0) {
58347                         diagnostics.add(getTypeArgumentArityError(node, signatures, typeArguments));
58348                     }
58349                     else if (!isDecorator) {
58350                         diagnostics.add(getArgumentArityError(node, signaturesWithCorrectTypeArgumentArity, args));
58351                     }
58352                     else if (fallbackError) {
58353                         diagnostics.add(getDiagnosticForCallNode(node, fallbackError));
58354                     }
58355                 }
58356             }
58357             return getCandidateForOverloadFailure(node, candidates, args, !!candidatesOutArray);
58358             function chooseOverload(candidates, relation, signatureHelpTrailingComma) {
58359                 if (signatureHelpTrailingComma === void 0) { signatureHelpTrailingComma = false; }
58360                 candidatesForArgumentError = undefined;
58361                 candidateForArgumentArityError = undefined;
58362                 candidateForTypeArgumentError = undefined;
58363                 if (isSingleNonGenericCandidate) {
58364                     var candidate = candidates[0];
58365                     if (ts.some(typeArguments) || !hasCorrectArity(node, args, candidate, signatureHelpTrailingComma)) {
58366                         return undefined;
58367                     }
58368                     if (getSignatureApplicabilityError(node, args, candidate, relation, 0 /* Normal */, /*reportErrors*/ false, /*containingMessageChain*/ undefined)) {
58369                         candidatesForArgumentError = [candidate];
58370                         return undefined;
58371                     }
58372                     return candidate;
58373                 }
58374                 for (var candidateIndex = 0; candidateIndex < candidates.length; candidateIndex++) {
58375                     var candidate = candidates[candidateIndex];
58376                     if (!hasCorrectTypeArgumentArity(candidate, typeArguments) || !hasCorrectArity(node, args, candidate, signatureHelpTrailingComma)) {
58377                         continue;
58378                     }
58379                     var checkCandidate = void 0;
58380                     var inferenceContext = void 0;
58381                     if (candidate.typeParameters) {
58382                         var typeArgumentTypes = void 0;
58383                         if (ts.some(typeArguments)) {
58384                             typeArgumentTypes = checkTypeArguments(candidate, typeArguments, /*reportErrors*/ false);
58385                             if (!typeArgumentTypes) {
58386                                 candidateForTypeArgumentError = candidate;
58387                                 continue;
58388                             }
58389                         }
58390                         else {
58391                             inferenceContext = createInferenceContext(candidate.typeParameters, candidate, /*flags*/ ts.isInJSFile(node) ? 2 /* AnyDefault */ : 0 /* None */);
58392                             typeArgumentTypes = inferTypeArguments(node, candidate, args, argCheckMode | 8 /* SkipGenericFunctions */, inferenceContext);
58393                             argCheckMode |= inferenceContext.flags & 4 /* SkippedGenericFunction */ ? 8 /* SkipGenericFunctions */ : 0 /* Normal */;
58394                         }
58395                         checkCandidate = getSignatureInstantiation(candidate, typeArgumentTypes, ts.isInJSFile(candidate.declaration), inferenceContext && inferenceContext.inferredTypeParameters);
58396                         // If the original signature has a generic rest type, instantiation may produce a
58397                         // signature with different arity and we need to perform another arity check.
58398                         if (getNonArrayRestType(candidate) && !hasCorrectArity(node, args, checkCandidate, signatureHelpTrailingComma)) {
58399                             candidateForArgumentArityError = checkCandidate;
58400                             continue;
58401                         }
58402                     }
58403                     else {
58404                         checkCandidate = candidate;
58405                     }
58406                     if (getSignatureApplicabilityError(node, args, checkCandidate, relation, argCheckMode, /*reportErrors*/ false, /*containingMessageChain*/ undefined)) {
58407                         // Give preference to error candidates that have no rest parameters (as they are more specific)
58408                         (candidatesForArgumentError || (candidatesForArgumentError = [])).push(checkCandidate);
58409                         continue;
58410                     }
58411                     if (argCheckMode) {
58412                         // If one or more context sensitive arguments were excluded, we start including
58413                         // them now (and keeping do so for any subsequent candidates) and perform a second
58414                         // round of type inference and applicability checking for this particular candidate.
58415                         argCheckMode = 0 /* Normal */;
58416                         if (inferenceContext) {
58417                             var typeArgumentTypes = inferTypeArguments(node, candidate, args, argCheckMode, inferenceContext);
58418                             checkCandidate = getSignatureInstantiation(candidate, typeArgumentTypes, ts.isInJSFile(candidate.declaration), inferenceContext && inferenceContext.inferredTypeParameters);
58419                             // If the original signature has a generic rest type, instantiation may produce a
58420                             // signature with different arity and we need to perform another arity check.
58421                             if (getNonArrayRestType(candidate) && !hasCorrectArity(node, args, checkCandidate, signatureHelpTrailingComma)) {
58422                                 candidateForArgumentArityError = checkCandidate;
58423                                 continue;
58424                             }
58425                         }
58426                         if (getSignatureApplicabilityError(node, args, checkCandidate, relation, argCheckMode, /*reportErrors*/ false, /*containingMessageChain*/ undefined)) {
58427                             // Give preference to error candidates that have no rest parameters (as they are more specific)
58428                             (candidatesForArgumentError || (candidatesForArgumentError = [])).push(checkCandidate);
58429                             continue;
58430                         }
58431                     }
58432                     candidates[candidateIndex] = checkCandidate;
58433                     return checkCandidate;
58434                 }
58435                 return undefined;
58436             }
58437         }
58438         // No signature was applicable. We have already reported the errors for the invalid signature.
58439         function getCandidateForOverloadFailure(node, candidates, args, hasCandidatesOutArray) {
58440             ts.Debug.assert(candidates.length > 0); // Else should not have called this.
58441             checkNodeDeferred(node);
58442             // Normally we will combine overloads. Skip this if they have type parameters since that's hard to combine.
58443             // Don't do this if there is a `candidatesOutArray`,
58444             // because then we want the chosen best candidate to be one of the overloads, not a combination.
58445             return hasCandidatesOutArray || candidates.length === 1 || candidates.some(function (c) { return !!c.typeParameters; })
58446                 ? pickLongestCandidateSignature(node, candidates, args)
58447                 : createUnionOfSignaturesForOverloadFailure(candidates);
58448         }
58449         function createUnionOfSignaturesForOverloadFailure(candidates) {
58450             var thisParameters = ts.mapDefined(candidates, function (c) { return c.thisParameter; });
58451             var thisParameter;
58452             if (thisParameters.length) {
58453                 thisParameter = createCombinedSymbolFromTypes(thisParameters, thisParameters.map(getTypeOfParameter));
58454             }
58455             var _a = ts.minAndMax(candidates, getNumNonRestParameters), minArgumentCount = _a.min, maxNonRestParam = _a.max;
58456             var parameters = [];
58457             var _loop_18 = function (i) {
58458                 var symbols = ts.mapDefined(candidates, function (s) { return signatureHasRestParameter(s) ?
58459                     i < s.parameters.length - 1 ? s.parameters[i] : ts.last(s.parameters) :
58460                     i < s.parameters.length ? s.parameters[i] : undefined; });
58461                 ts.Debug.assert(symbols.length !== 0);
58462                 parameters.push(createCombinedSymbolFromTypes(symbols, ts.mapDefined(candidates, function (candidate) { return tryGetTypeAtPosition(candidate, i); })));
58463             };
58464             for (var i = 0; i < maxNonRestParam; i++) {
58465                 _loop_18(i);
58466             }
58467             var restParameterSymbols = ts.mapDefined(candidates, function (c) { return signatureHasRestParameter(c) ? ts.last(c.parameters) : undefined; });
58468             var flags = 0 /* None */;
58469             if (restParameterSymbols.length !== 0) {
58470                 var type = createArrayType(getUnionType(ts.mapDefined(candidates, tryGetRestTypeOfSignature), 2 /* Subtype */));
58471                 parameters.push(createCombinedSymbolForOverloadFailure(restParameterSymbols, type));
58472                 flags |= 1 /* HasRestParameter */;
58473             }
58474             if (candidates.some(signatureHasLiteralTypes)) {
58475                 flags |= 2 /* HasLiteralTypes */;
58476             }
58477             return createSignature(candidates[0].declaration, 
58478             /*typeParameters*/ undefined, // Before calling this we tested for `!candidates.some(c => !!c.typeParameters)`.
58479             thisParameter, parameters, 
58480             /*resolvedReturnType*/ getIntersectionType(candidates.map(getReturnTypeOfSignature)), 
58481             /*typePredicate*/ undefined, minArgumentCount, flags);
58482         }
58483         function getNumNonRestParameters(signature) {
58484             var numParams = signature.parameters.length;
58485             return signatureHasRestParameter(signature) ? numParams - 1 : numParams;
58486         }
58487         function createCombinedSymbolFromTypes(sources, types) {
58488             return createCombinedSymbolForOverloadFailure(sources, getUnionType(types, 2 /* Subtype */));
58489         }
58490         function createCombinedSymbolForOverloadFailure(sources, type) {
58491             // This function is currently only used for erroneous overloads, so it's good enough to just use the first source.
58492             return createSymbolWithType(ts.first(sources), type);
58493         }
58494         function pickLongestCandidateSignature(node, candidates, args) {
58495             // Pick the longest signature. This way we can get a contextual type for cases like:
58496             //     declare function f(a: { xa: number; xb: number; }, b: number);
58497             //     f({ |
58498             // Also, use explicitly-supplied type arguments if they are provided, so we can get a contextual signature in cases like:
58499             //     declare function f<T>(k: keyof T);
58500             //     f<Foo>("
58501             var bestIndex = getLongestCandidateIndex(candidates, apparentArgumentCount === undefined ? args.length : apparentArgumentCount);
58502             var candidate = candidates[bestIndex];
58503             var typeParameters = candidate.typeParameters;
58504             if (!typeParameters) {
58505                 return candidate;
58506             }
58507             var typeArgumentNodes = callLikeExpressionMayHaveTypeArguments(node) ? node.typeArguments : undefined;
58508             var instantiated = typeArgumentNodes
58509                 ? createSignatureInstantiation(candidate, getTypeArgumentsFromNodes(typeArgumentNodes, typeParameters, ts.isInJSFile(node)))
58510                 : inferSignatureInstantiationForOverloadFailure(node, typeParameters, candidate, args);
58511             candidates[bestIndex] = instantiated;
58512             return instantiated;
58513         }
58514         function getTypeArgumentsFromNodes(typeArgumentNodes, typeParameters, isJs) {
58515             var typeArguments = typeArgumentNodes.map(getTypeOfNode);
58516             while (typeArguments.length > typeParameters.length) {
58517                 typeArguments.pop();
58518             }
58519             while (typeArguments.length < typeParameters.length) {
58520                 typeArguments.push(getConstraintOfTypeParameter(typeParameters[typeArguments.length]) || getDefaultTypeArgumentType(isJs));
58521             }
58522             return typeArguments;
58523         }
58524         function inferSignatureInstantiationForOverloadFailure(node, typeParameters, candidate, args) {
58525             var inferenceContext = createInferenceContext(typeParameters, candidate, /*flags*/ ts.isInJSFile(node) ? 2 /* AnyDefault */ : 0 /* None */);
58526             var typeArgumentTypes = inferTypeArguments(node, candidate, args, 4 /* SkipContextSensitive */ | 8 /* SkipGenericFunctions */, inferenceContext);
58527             return createSignatureInstantiation(candidate, typeArgumentTypes);
58528         }
58529         function getLongestCandidateIndex(candidates, argsCount) {
58530             var maxParamsIndex = -1;
58531             var maxParams = -1;
58532             for (var i = 0; i < candidates.length; i++) {
58533                 var candidate = candidates[i];
58534                 var paramCount = getParameterCount(candidate);
58535                 if (hasEffectiveRestParameter(candidate) || paramCount >= argsCount) {
58536                     return i;
58537                 }
58538                 if (paramCount > maxParams) {
58539                     maxParams = paramCount;
58540                     maxParamsIndex = i;
58541                 }
58542             }
58543             return maxParamsIndex;
58544         }
58545         function resolveCallExpression(node, candidatesOutArray, checkMode) {
58546             if (node.expression.kind === 102 /* SuperKeyword */) {
58547                 var superType = checkSuperExpression(node.expression);
58548                 if (isTypeAny(superType)) {
58549                     for (var _i = 0, _a = node.arguments; _i < _a.length; _i++) {
58550                         var arg = _a[_i];
58551                         checkExpression(arg); // Still visit arguments so they get marked for visibility, etc
58552                     }
58553                     return anySignature;
58554                 }
58555                 if (superType !== errorType) {
58556                     // In super call, the candidate signatures are the matching arity signatures of the base constructor function instantiated
58557                     // with the type arguments specified in the extends clause.
58558                     var baseTypeNode = ts.getEffectiveBaseTypeNode(ts.getContainingClass(node));
58559                     if (baseTypeNode) {
58560                         var baseConstructors = getInstantiatedConstructorsForTypeArguments(superType, baseTypeNode.typeArguments, baseTypeNode);
58561                         return resolveCall(node, baseConstructors, candidatesOutArray, checkMode, 0 /* None */);
58562                     }
58563                 }
58564                 return resolveUntypedCall(node);
58565             }
58566             var callChainFlags;
58567             var funcType = checkExpression(node.expression);
58568             if (ts.isCallChain(node)) {
58569                 var nonOptionalType = getOptionalExpressionType(funcType, node.expression);
58570                 callChainFlags = nonOptionalType === funcType ? 0 /* None */ :
58571                     ts.isOutermostOptionalChain(node) ? 8 /* IsOuterCallChain */ :
58572                         4 /* IsInnerCallChain */;
58573                 funcType = nonOptionalType;
58574             }
58575             else {
58576                 callChainFlags = 0 /* None */;
58577             }
58578             funcType = checkNonNullTypeWithReporter(funcType, node.expression, reportCannotInvokePossiblyNullOrUndefinedError);
58579             if (funcType === silentNeverType) {
58580                 return silentNeverSignature;
58581             }
58582             var apparentType = getApparentType(funcType);
58583             if (apparentType === errorType) {
58584                 // Another error has already been reported
58585                 return resolveErrorCall(node);
58586             }
58587             // Technically, this signatures list may be incomplete. We are taking the apparent type,
58588             // but we are not including call signatures that may have been added to the Object or
58589             // Function interface, since they have none by default. This is a bit of a leap of faith
58590             // that the user will not add any.
58591             var callSignatures = getSignaturesOfType(apparentType, 0 /* Call */);
58592             var numConstructSignatures = getSignaturesOfType(apparentType, 1 /* Construct */).length;
58593             // TS 1.0 Spec: 4.12
58594             // In an untyped function call no TypeArgs are permitted, Args can be any argument list, no contextual
58595             // types are provided for the argument expressions, and the result is always of type Any.
58596             if (isUntypedFunctionCall(funcType, apparentType, callSignatures.length, numConstructSignatures)) {
58597                 // The unknownType indicates that an error already occurred (and was reported).  No
58598                 // need to report another error in this case.
58599                 if (funcType !== errorType && node.typeArguments) {
58600                     error(node, ts.Diagnostics.Untyped_function_calls_may_not_accept_type_arguments);
58601                 }
58602                 return resolveUntypedCall(node);
58603             }
58604             // If FuncExpr's apparent type(section 3.8.1) is a function type, the call is a typed function call.
58605             // TypeScript employs overload resolution in typed function calls in order to support functions
58606             // with multiple call signatures.
58607             if (!callSignatures.length) {
58608                 if (numConstructSignatures) {
58609                     error(node, ts.Diagnostics.Value_of_type_0_is_not_callable_Did_you_mean_to_include_new, typeToString(funcType));
58610                 }
58611                 else {
58612                     var relatedInformation = void 0;
58613                     if (node.arguments.length === 1) {
58614                         var text = ts.getSourceFileOfNode(node).text;
58615                         if (ts.isLineBreak(text.charCodeAt(ts.skipTrivia(text, node.expression.end, /* stopAfterLineBreak */ true) - 1))) {
58616                             relatedInformation = ts.createDiagnosticForNode(node.expression, ts.Diagnostics.Are_you_missing_a_semicolon);
58617                         }
58618                     }
58619                     invocationError(node.expression, apparentType, 0 /* Call */, relatedInformation);
58620                 }
58621                 return resolveErrorCall(node);
58622             }
58623             // When a call to a generic function is an argument to an outer call to a generic function for which
58624             // inference is in process, we have a choice to make. If the inner call relies on inferences made from
58625             // its contextual type to its return type, deferring the inner call processing allows the best possible
58626             // contextual type to accumulate. But if the outer call relies on inferences made from the return type of
58627             // the inner call, the inner call should be processed early. There's no sure way to know which choice is
58628             // right (only a full unification algorithm can determine that), so we resort to the following heuristic:
58629             // If no type arguments are specified in the inner call and at least one call signature is generic and
58630             // returns a function type, we choose to defer processing. This narrowly permits function composition
58631             // operators to flow inferences through return types, but otherwise processes calls right away. We
58632             // use the resolvingSignature singleton to indicate that we deferred processing. This result will be
58633             // propagated out and eventually turned into nonInferrableType (a type that is assignable to anything and
58634             // from which we never make inferences).
58635             if (checkMode & 8 /* SkipGenericFunctions */ && !node.typeArguments && callSignatures.some(isGenericFunctionReturningFunction)) {
58636                 skippedGenericFunction(node, checkMode);
58637                 return resolvingSignature;
58638             }
58639             // If the function is explicitly marked with `@class`, then it must be constructed.
58640             if (callSignatures.some(function (sig) { return ts.isInJSFile(sig.declaration) && !!ts.getJSDocClassTag(sig.declaration); })) {
58641                 error(node, ts.Diagnostics.Value_of_type_0_is_not_callable_Did_you_mean_to_include_new, typeToString(funcType));
58642                 return resolveErrorCall(node);
58643             }
58644             return resolveCall(node, callSignatures, candidatesOutArray, checkMode, callChainFlags);
58645         }
58646         function isGenericFunctionReturningFunction(signature) {
58647             return !!(signature.typeParameters && isFunctionType(getReturnTypeOfSignature(signature)));
58648         }
58649         /**
58650          * TS 1.0 spec: 4.12
58651          * If FuncExpr is of type Any, or of an object type that has no call or construct signatures
58652          * but is a subtype of the Function interface, the call is an untyped function call.
58653          */
58654         function isUntypedFunctionCall(funcType, apparentFuncType, numCallSignatures, numConstructSignatures) {
58655             // We exclude union types because we may have a union of function types that happen to have no common signatures.
58656             return isTypeAny(funcType) || isTypeAny(apparentFuncType) && !!(funcType.flags & 262144 /* TypeParameter */) ||
58657                 !numCallSignatures && !numConstructSignatures && !(apparentFuncType.flags & (1048576 /* Union */ | 131072 /* Never */)) && isTypeAssignableTo(funcType, globalFunctionType);
58658         }
58659         function resolveNewExpression(node, candidatesOutArray, checkMode) {
58660             if (node.arguments && languageVersion < 1 /* ES5 */) {
58661                 var spreadIndex = getSpreadArgumentIndex(node.arguments);
58662                 if (spreadIndex >= 0) {
58663                     error(node.arguments[spreadIndex], ts.Diagnostics.Spread_operator_in_new_expressions_is_only_available_when_targeting_ECMAScript_5_and_higher);
58664                 }
58665             }
58666             var expressionType = checkNonNullExpression(node.expression);
58667             if (expressionType === silentNeverType) {
58668                 return silentNeverSignature;
58669             }
58670             // If expressionType's apparent type(section 3.8.1) is an object type with one or
58671             // more construct signatures, the expression is processed in the same manner as a
58672             // function call, but using the construct signatures as the initial set of candidate
58673             // signatures for overload resolution. The result type of the function call becomes
58674             // the result type of the operation.
58675             expressionType = getApparentType(expressionType);
58676             if (expressionType === errorType) {
58677                 // Another error has already been reported
58678                 return resolveErrorCall(node);
58679             }
58680             // TS 1.0 spec: 4.11
58681             // If expressionType is of type Any, Args can be any argument
58682             // list and the result of the operation is of type Any.
58683             if (isTypeAny(expressionType)) {
58684                 if (node.typeArguments) {
58685                     error(node, ts.Diagnostics.Untyped_function_calls_may_not_accept_type_arguments);
58686                 }
58687                 return resolveUntypedCall(node);
58688             }
58689             // Technically, this signatures list may be incomplete. We are taking the apparent type,
58690             // but we are not including construct signatures that may have been added to the Object or
58691             // Function interface, since they have none by default. This is a bit of a leap of faith
58692             // that the user will not add any.
58693             var constructSignatures = getSignaturesOfType(expressionType, 1 /* Construct */);
58694             if (constructSignatures.length) {
58695                 if (!isConstructorAccessible(node, constructSignatures[0])) {
58696                     return resolveErrorCall(node);
58697                 }
58698                 // If the expression is a class of abstract type, then it cannot be instantiated.
58699                 // Note, only class declarations can be declared abstract.
58700                 // In the case of a merged class-module or class-interface declaration,
58701                 // only the class declaration node will have the Abstract flag set.
58702                 var valueDecl = expressionType.symbol && ts.getClassLikeDeclarationOfSymbol(expressionType.symbol);
58703                 if (valueDecl && ts.hasModifier(valueDecl, 128 /* Abstract */)) {
58704                     error(node, ts.Diagnostics.Cannot_create_an_instance_of_an_abstract_class);
58705                     return resolveErrorCall(node);
58706                 }
58707                 return resolveCall(node, constructSignatures, candidatesOutArray, checkMode, 0 /* None */);
58708             }
58709             // If expressionType's apparent type is an object type with no construct signatures but
58710             // one or more call signatures, the expression is processed as a function call. A compile-time
58711             // error occurs if the result of the function call is not Void. The type of the result of the
58712             // operation is Any. It is an error to have a Void this type.
58713             var callSignatures = getSignaturesOfType(expressionType, 0 /* Call */);
58714             if (callSignatures.length) {
58715                 var signature = resolveCall(node, callSignatures, candidatesOutArray, checkMode, 0 /* None */);
58716                 if (!noImplicitAny) {
58717                     if (signature.declaration && !isJSConstructor(signature.declaration) && getReturnTypeOfSignature(signature) !== voidType) {
58718                         error(node, ts.Diagnostics.Only_a_void_function_can_be_called_with_the_new_keyword);
58719                     }
58720                     if (getThisTypeOfSignature(signature) === voidType) {
58721                         error(node, ts.Diagnostics.A_function_that_is_called_with_the_new_keyword_cannot_have_a_this_type_that_is_void);
58722                     }
58723                 }
58724                 return signature;
58725             }
58726             invocationError(node.expression, expressionType, 1 /* Construct */);
58727             return resolveErrorCall(node);
58728         }
58729         function typeHasProtectedAccessibleBase(target, type) {
58730             var baseTypes = getBaseTypes(type);
58731             if (!ts.length(baseTypes)) {
58732                 return false;
58733             }
58734             var firstBase = baseTypes[0];
58735             if (firstBase.flags & 2097152 /* Intersection */) {
58736                 var types = firstBase.types;
58737                 var mixinFlags = findMixins(types);
58738                 var i = 0;
58739                 for (var _i = 0, _a = firstBase.types; _i < _a.length; _i++) {
58740                     var intersectionMember = _a[_i];
58741                     // We want to ignore mixin ctors
58742                     if (!mixinFlags[i]) {
58743                         if (ts.getObjectFlags(intersectionMember) & (1 /* Class */ | 2 /* Interface */)) {
58744                             if (intersectionMember.symbol === target) {
58745                                 return true;
58746                             }
58747                             if (typeHasProtectedAccessibleBase(target, intersectionMember)) {
58748                                 return true;
58749                             }
58750                         }
58751                     }
58752                     i++;
58753                 }
58754                 return false;
58755             }
58756             if (firstBase.symbol === target) {
58757                 return true;
58758             }
58759             return typeHasProtectedAccessibleBase(target, firstBase);
58760         }
58761         function isConstructorAccessible(node, signature) {
58762             if (!signature || !signature.declaration) {
58763                 return true;
58764             }
58765             var declaration = signature.declaration;
58766             var modifiers = ts.getSelectedModifierFlags(declaration, 24 /* NonPublicAccessibilityModifier */);
58767             // (1) Public constructors and (2) constructor functions are always accessible.
58768             if (!modifiers || declaration.kind !== 162 /* Constructor */) {
58769                 return true;
58770             }
58771             var declaringClassDeclaration = ts.getClassLikeDeclarationOfSymbol(declaration.parent.symbol);
58772             var declaringClass = getDeclaredTypeOfSymbol(declaration.parent.symbol);
58773             // A private or protected constructor can only be instantiated within its own class (or a subclass, for protected)
58774             if (!isNodeWithinClass(node, declaringClassDeclaration)) {
58775                 var containingClass = ts.getContainingClass(node);
58776                 if (containingClass && modifiers & 16 /* Protected */) {
58777                     var containingType = getTypeOfNode(containingClass);
58778                     if (typeHasProtectedAccessibleBase(declaration.parent.symbol, containingType)) {
58779                         return true;
58780                     }
58781                 }
58782                 if (modifiers & 8 /* Private */) {
58783                     error(node, ts.Diagnostics.Constructor_of_class_0_is_private_and_only_accessible_within_the_class_declaration, typeToString(declaringClass));
58784                 }
58785                 if (modifiers & 16 /* Protected */) {
58786                     error(node, ts.Diagnostics.Constructor_of_class_0_is_protected_and_only_accessible_within_the_class_declaration, typeToString(declaringClass));
58787                 }
58788                 return false;
58789             }
58790             return true;
58791         }
58792         function invocationErrorDetails(apparentType, kind) {
58793             var errorInfo;
58794             var isCall = kind === 0 /* Call */;
58795             var awaitedType = getAwaitedType(apparentType);
58796             var maybeMissingAwait = awaitedType && getSignaturesOfType(awaitedType, kind).length > 0;
58797             if (apparentType.flags & 1048576 /* Union */) {
58798                 var types = apparentType.types;
58799                 var hasSignatures = false;
58800                 for (var _i = 0, types_18 = types; _i < types_18.length; _i++) {
58801                     var constituent = types_18[_i];
58802                     var signatures = getSignaturesOfType(constituent, kind);
58803                     if (signatures.length !== 0) {
58804                         hasSignatures = true;
58805                         if (errorInfo) {
58806                             // Bail early if we already have an error, no chance of "No constituent of type is callable"
58807                             break;
58808                         }
58809                     }
58810                     else {
58811                         // Error on the first non callable constituent only
58812                         if (!errorInfo) {
58813                             errorInfo = ts.chainDiagnosticMessages(errorInfo, isCall ?
58814                                 ts.Diagnostics.Type_0_has_no_call_signatures :
58815                                 ts.Diagnostics.Type_0_has_no_construct_signatures, typeToString(constituent));
58816                             errorInfo = ts.chainDiagnosticMessages(errorInfo, isCall ?
58817                                 ts.Diagnostics.Not_all_constituents_of_type_0_are_callable :
58818                                 ts.Diagnostics.Not_all_constituents_of_type_0_are_constructable, typeToString(apparentType));
58819                         }
58820                         if (hasSignatures) {
58821                             // Bail early if we already found a siganture, no chance of "No constituent of type is callable"
58822                             break;
58823                         }
58824                     }
58825                 }
58826                 if (!hasSignatures) {
58827                     errorInfo = ts.chainDiagnosticMessages(
58828                     /* detials */ undefined, isCall ?
58829                         ts.Diagnostics.No_constituent_of_type_0_is_callable :
58830                         ts.Diagnostics.No_constituent_of_type_0_is_constructable, typeToString(apparentType));
58831                 }
58832                 if (!errorInfo) {
58833                     errorInfo = ts.chainDiagnosticMessages(errorInfo, isCall ?
58834                         ts.Diagnostics.Each_member_of_the_union_type_0_has_signatures_but_none_of_those_signatures_are_compatible_with_each_other :
58835                         ts.Diagnostics.Each_member_of_the_union_type_0_has_construct_signatures_but_none_of_those_signatures_are_compatible_with_each_other, typeToString(apparentType));
58836                 }
58837             }
58838             else {
58839                 errorInfo = ts.chainDiagnosticMessages(errorInfo, isCall ?
58840                     ts.Diagnostics.Type_0_has_no_call_signatures :
58841                     ts.Diagnostics.Type_0_has_no_construct_signatures, typeToString(apparentType));
58842             }
58843             return {
58844                 messageChain: ts.chainDiagnosticMessages(errorInfo, isCall ? ts.Diagnostics.This_expression_is_not_callable : ts.Diagnostics.This_expression_is_not_constructable),
58845                 relatedMessage: maybeMissingAwait ? ts.Diagnostics.Did_you_forget_to_use_await : undefined,
58846             };
58847         }
58848         function invocationError(errorTarget, apparentType, kind, relatedInformation) {
58849             var _a = invocationErrorDetails(apparentType, kind), messageChain = _a.messageChain, relatedInfo = _a.relatedMessage;
58850             var diagnostic = ts.createDiagnosticForNodeFromMessageChain(errorTarget, messageChain);
58851             if (relatedInfo) {
58852                 ts.addRelatedInfo(diagnostic, ts.createDiagnosticForNode(errorTarget, relatedInfo));
58853             }
58854             if (ts.isCallExpression(errorTarget.parent)) {
58855                 var _b = getDiagnosticSpanForCallNode(errorTarget.parent, /* doNotIncludeArguments */ true), start = _b.start, length_7 = _b.length;
58856                 diagnostic.start = start;
58857                 diagnostic.length = length_7;
58858             }
58859             diagnostics.add(diagnostic);
58860             invocationErrorRecovery(apparentType, kind, relatedInformation ? ts.addRelatedInfo(diagnostic, relatedInformation) : diagnostic);
58861         }
58862         function invocationErrorRecovery(apparentType, kind, diagnostic) {
58863             if (!apparentType.symbol) {
58864                 return;
58865             }
58866             var importNode = getSymbolLinks(apparentType.symbol).originatingImport;
58867             // Create a diagnostic on the originating import if possible onto which we can attach a quickfix
58868             //  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
58869             if (importNode && !ts.isImportCall(importNode)) {
58870                 var sigs = getSignaturesOfType(getTypeOfSymbol(getSymbolLinks(apparentType.symbol).target), kind);
58871                 if (!sigs || !sigs.length)
58872                     return;
58873                 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));
58874             }
58875         }
58876         function resolveTaggedTemplateExpression(node, candidatesOutArray, checkMode) {
58877             var tagType = checkExpression(node.tag);
58878             var apparentType = getApparentType(tagType);
58879             if (apparentType === errorType) {
58880                 // Another error has already been reported
58881                 return resolveErrorCall(node);
58882             }
58883             var callSignatures = getSignaturesOfType(apparentType, 0 /* Call */);
58884             var numConstructSignatures = getSignaturesOfType(apparentType, 1 /* Construct */).length;
58885             if (isUntypedFunctionCall(tagType, apparentType, callSignatures.length, numConstructSignatures)) {
58886                 return resolveUntypedCall(node);
58887             }
58888             if (!callSignatures.length) {
58889                 invocationError(node.tag, apparentType, 0 /* Call */);
58890                 return resolveErrorCall(node);
58891             }
58892             return resolveCall(node, callSignatures, candidatesOutArray, checkMode, 0 /* None */);
58893         }
58894         /**
58895          * Gets the localized diagnostic head message to use for errors when resolving a decorator as a call expression.
58896          */
58897         function getDiagnosticHeadMessageForDecoratorResolution(node) {
58898             switch (node.parent.kind) {
58899                 case 245 /* ClassDeclaration */:
58900                 case 214 /* ClassExpression */:
58901                     return ts.Diagnostics.Unable_to_resolve_signature_of_class_decorator_when_called_as_an_expression;
58902                 case 156 /* Parameter */:
58903                     return ts.Diagnostics.Unable_to_resolve_signature_of_parameter_decorator_when_called_as_an_expression;
58904                 case 159 /* PropertyDeclaration */:
58905                     return ts.Diagnostics.Unable_to_resolve_signature_of_property_decorator_when_called_as_an_expression;
58906                 case 161 /* MethodDeclaration */:
58907                 case 163 /* GetAccessor */:
58908                 case 164 /* SetAccessor */:
58909                     return ts.Diagnostics.Unable_to_resolve_signature_of_method_decorator_when_called_as_an_expression;
58910                 default:
58911                     return ts.Debug.fail();
58912             }
58913         }
58914         /**
58915          * Resolves a decorator as if it were a call expression.
58916          */
58917         function resolveDecorator(node, candidatesOutArray, checkMode) {
58918             var funcType = checkExpression(node.expression);
58919             var apparentType = getApparentType(funcType);
58920             if (apparentType === errorType) {
58921                 return resolveErrorCall(node);
58922             }
58923             var callSignatures = getSignaturesOfType(apparentType, 0 /* Call */);
58924             var numConstructSignatures = getSignaturesOfType(apparentType, 1 /* Construct */).length;
58925             if (isUntypedFunctionCall(funcType, apparentType, callSignatures.length, numConstructSignatures)) {
58926                 return resolveUntypedCall(node);
58927             }
58928             if (isPotentiallyUncalledDecorator(node, callSignatures)) {
58929                 var nodeStr = ts.getTextOfNode(node.expression, /*includeTrivia*/ false);
58930                 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);
58931                 return resolveErrorCall(node);
58932             }
58933             var headMessage = getDiagnosticHeadMessageForDecoratorResolution(node);
58934             if (!callSignatures.length) {
58935                 var errorDetails = invocationErrorDetails(apparentType, 0 /* Call */);
58936                 var messageChain = ts.chainDiagnosticMessages(errorDetails.messageChain, headMessage);
58937                 var diag = ts.createDiagnosticForNodeFromMessageChain(node.expression, messageChain);
58938                 if (errorDetails.relatedMessage) {
58939                     ts.addRelatedInfo(diag, ts.createDiagnosticForNode(node.expression, errorDetails.relatedMessage));
58940                 }
58941                 diagnostics.add(diag);
58942                 invocationErrorRecovery(apparentType, 0 /* Call */, diag);
58943                 return resolveErrorCall(node);
58944             }
58945             return resolveCall(node, callSignatures, candidatesOutArray, checkMode, 0 /* None */, headMessage);
58946         }
58947         function createSignatureForJSXIntrinsic(node, result) {
58948             var namespace = getJsxNamespaceAt(node);
58949             var exports = namespace && getExportsOfSymbol(namespace);
58950             // We fake up a SFC signature for each intrinsic, however a more specific per-element signature drawn from the JSX declaration
58951             // file would probably be preferable.
58952             var typeSymbol = exports && getSymbol(exports, JsxNames.Element, 788968 /* Type */);
58953             var returnNode = typeSymbol && nodeBuilder.symbolToEntityName(typeSymbol, 788968 /* Type */, node);
58954             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 */));
58955             var parameterSymbol = createSymbol(1 /* FunctionScopedVariable */, "props");
58956             parameterSymbol.type = result;
58957             return createSignature(declaration, 
58958             /*typeParameters*/ undefined, 
58959             /*thisParameter*/ undefined, [parameterSymbol], typeSymbol ? getDeclaredTypeOfSymbol(typeSymbol) : errorType, 
58960             /*returnTypePredicate*/ undefined, 1, 0 /* None */);
58961         }
58962         function resolveJsxOpeningLikeElement(node, candidatesOutArray, checkMode) {
58963             if (isJsxIntrinsicIdentifier(node.tagName)) {
58964                 var result = getIntrinsicAttributesTypeFromJsxOpeningLikeElement(node);
58965                 var fakeSignature = createSignatureForJSXIntrinsic(node, result);
58966                 checkTypeAssignableToAndOptionallyElaborate(checkExpressionWithContextualType(node.attributes, getEffectiveFirstArgumentForJsxSignature(fakeSignature, node), /*mapper*/ undefined, 0 /* Normal */), result, node.tagName, node.attributes);
58967                 return fakeSignature;
58968             }
58969             var exprTypes = checkExpression(node.tagName);
58970             var apparentType = getApparentType(exprTypes);
58971             if (apparentType === errorType) {
58972                 return resolveErrorCall(node);
58973             }
58974             var signatures = getUninstantiatedJsxSignaturesOfType(exprTypes, node);
58975             if (isUntypedFunctionCall(exprTypes, apparentType, signatures.length, /*constructSignatures*/ 0)) {
58976                 return resolveUntypedCall(node);
58977             }
58978             if (signatures.length === 0) {
58979                 // We found no signatures at all, which is an error
58980                 error(node.tagName, ts.Diagnostics.JSX_element_type_0_does_not_have_any_construct_or_call_signatures, ts.getTextOfNode(node.tagName));
58981                 return resolveErrorCall(node);
58982             }
58983             return resolveCall(node, signatures, candidatesOutArray, checkMode, 0 /* None */);
58984         }
58985         /**
58986          * Sometimes, we have a decorator that could accept zero arguments,
58987          * but is receiving too many arguments as part of the decorator invocation.
58988          * In those cases, a user may have meant to *call* the expression before using it as a decorator.
58989          */
58990         function isPotentiallyUncalledDecorator(decorator, signatures) {
58991             return signatures.length && ts.every(signatures, function (signature) {
58992                 return signature.minArgumentCount === 0 &&
58993                     !signatureHasRestParameter(signature) &&
58994                     signature.parameters.length < getDecoratorArgumentCount(decorator, signature);
58995             });
58996         }
58997         function resolveSignature(node, candidatesOutArray, checkMode) {
58998             switch (node.kind) {
58999                 case 196 /* CallExpression */:
59000                     return resolveCallExpression(node, candidatesOutArray, checkMode);
59001                 case 197 /* NewExpression */:
59002                     return resolveNewExpression(node, candidatesOutArray, checkMode);
59003                 case 198 /* TaggedTemplateExpression */:
59004                     return resolveTaggedTemplateExpression(node, candidatesOutArray, checkMode);
59005                 case 157 /* Decorator */:
59006                     return resolveDecorator(node, candidatesOutArray, checkMode);
59007                 case 268 /* JsxOpeningElement */:
59008                 case 267 /* JsxSelfClosingElement */:
59009                     return resolveJsxOpeningLikeElement(node, candidatesOutArray, checkMode);
59010             }
59011             throw ts.Debug.assertNever(node, "Branch in 'resolveSignature' should be unreachable.");
59012         }
59013         /**
59014          * Resolve a signature of a given call-like expression.
59015          * @param node a call-like expression to try resolve a signature for
59016          * @param candidatesOutArray an array of signature to be filled in by the function. It is passed by signature help in the language service;
59017          *                           the function will fill it up with appropriate candidate signatures
59018          * @return a signature of the call-like expression or undefined if one can't be found
59019          */
59020         function getResolvedSignature(node, candidatesOutArray, checkMode) {
59021             var links = getNodeLinks(node);
59022             // If getResolvedSignature has already been called, we will have cached the resolvedSignature.
59023             // However, it is possible that either candidatesOutArray was not passed in the first time,
59024             // or that a different candidatesOutArray was passed in. Therefore, we need to redo the work
59025             // to correctly fill the candidatesOutArray.
59026             var cached = links.resolvedSignature;
59027             if (cached && cached !== resolvingSignature && !candidatesOutArray) {
59028                 return cached;
59029             }
59030             links.resolvedSignature = resolvingSignature;
59031             var result = resolveSignature(node, candidatesOutArray, checkMode || 0 /* Normal */);
59032             // When CheckMode.SkipGenericFunctions is set we use resolvingSignature to indicate that call
59033             // resolution should be deferred.
59034             if (result !== resolvingSignature) {
59035                 // If signature resolution originated in control flow type analysis (for example to compute the
59036                 // assigned type in a flow assignment) we don't cache the result as it may be based on temporary
59037                 // types from the control flow analysis.
59038                 links.resolvedSignature = flowLoopStart === flowLoopCount ? result : cached;
59039             }
59040             return result;
59041         }
59042         /**
59043          * Indicates whether a declaration can be treated as a constructor in a JavaScript
59044          * file.
59045          */
59046         function isJSConstructor(node) {
59047             if (!node || !ts.isInJSFile(node)) {
59048                 return false;
59049             }
59050             var func = ts.isFunctionDeclaration(node) || ts.isFunctionExpression(node) ? node :
59051                 ts.isVariableDeclaration(node) && node.initializer && ts.isFunctionExpression(node.initializer) ? node.initializer :
59052                     undefined;
59053             if (func) {
59054                 // If the node has a @class tag, treat it like a constructor.
59055                 if (ts.getJSDocClassTag(node))
59056                     return true;
59057                 // If the symbol of the node has members, treat it like a constructor.
59058                 var symbol = getSymbolOfNode(func);
59059                 return !!symbol && ts.hasEntries(symbol.members);
59060             }
59061             return false;
59062         }
59063         function mergeJSSymbols(target, source) {
59064             if (source) {
59065                 var links = getSymbolLinks(source);
59066                 if (!links.inferredClassSymbol || !links.inferredClassSymbol.has("" + getSymbolId(target))) {
59067                     var inferred = ts.isTransientSymbol(target) ? target : cloneSymbol(target);
59068                     inferred.exports = inferred.exports || ts.createSymbolTable();
59069                     inferred.members = inferred.members || ts.createSymbolTable();
59070                     inferred.flags |= source.flags & 32 /* Class */;
59071                     if (ts.hasEntries(source.exports)) {
59072                         mergeSymbolTable(inferred.exports, source.exports);
59073                     }
59074                     if (ts.hasEntries(source.members)) {
59075                         mergeSymbolTable(inferred.members, source.members);
59076                     }
59077                     (links.inferredClassSymbol || (links.inferredClassSymbol = ts.createMap())).set("" + getSymbolId(inferred), inferred);
59078                     return inferred;
59079                 }
59080                 return links.inferredClassSymbol.get("" + getSymbolId(target));
59081             }
59082         }
59083         function getAssignedClassSymbol(decl) {
59084             var assignmentSymbol = decl && decl.parent &&
59085                 (ts.isFunctionDeclaration(decl) && getSymbolOfNode(decl) ||
59086                     ts.isBinaryExpression(decl.parent) && getSymbolOfNode(decl.parent.left) ||
59087                     ts.isVariableDeclaration(decl.parent) && getSymbolOfNode(decl.parent));
59088             var prototype = assignmentSymbol && assignmentSymbol.exports && assignmentSymbol.exports.get("prototype");
59089             var init = prototype && prototype.valueDeclaration && getAssignedJSPrototype(prototype.valueDeclaration);
59090             return init ? getSymbolOfNode(init) : undefined;
59091         }
59092         function getAssignedJSPrototype(node) {
59093             if (!node.parent) {
59094                 return false;
59095             }
59096             var parent = node.parent;
59097             while (parent && parent.kind === 194 /* PropertyAccessExpression */) {
59098                 parent = parent.parent;
59099             }
59100             if (parent && ts.isBinaryExpression(parent) && ts.isPrototypeAccess(parent.left) && parent.operatorToken.kind === 62 /* EqualsToken */) {
59101                 var right = ts.getInitializerOfBinaryExpression(parent);
59102                 return ts.isObjectLiteralExpression(right) && right;
59103             }
59104         }
59105         /**
59106          * Syntactically and semantically checks a call or new expression.
59107          * @param node The call/new expression to be checked.
59108          * @returns On success, the expression's signature's return type. On failure, anyType.
59109          */
59110         function checkCallExpression(node, checkMode) {
59111             if (!checkGrammarTypeArguments(node, node.typeArguments))
59112                 checkGrammarArguments(node.arguments);
59113             var signature = getResolvedSignature(node, /*candidatesOutArray*/ undefined, checkMode);
59114             if (signature === resolvingSignature) {
59115                 // CheckMode.SkipGenericFunctions is enabled and this is a call to a generic function that
59116                 // returns a function type. We defer checking and return nonInferrableType.
59117                 return nonInferrableType;
59118             }
59119             if (node.expression.kind === 102 /* SuperKeyword */) {
59120                 return voidType;
59121             }
59122             if (node.kind === 197 /* NewExpression */) {
59123                 var declaration = signature.declaration;
59124                 if (declaration &&
59125                     declaration.kind !== 162 /* Constructor */ &&
59126                     declaration.kind !== 166 /* ConstructSignature */ &&
59127                     declaration.kind !== 171 /* ConstructorType */ &&
59128                     !ts.isJSDocConstructSignature(declaration) &&
59129                     !isJSConstructor(declaration)) {
59130                     // When resolved signature is a call signature (and not a construct signature) the result type is any
59131                     if (noImplicitAny) {
59132                         error(node, ts.Diagnostics.new_expression_whose_target_lacks_a_construct_signature_implicitly_has_an_any_type);
59133                     }
59134                     return anyType;
59135                 }
59136             }
59137             // In JavaScript files, calls to any identifier 'require' are treated as external module imports
59138             if (ts.isInJSFile(node) && isCommonJsRequire(node)) {
59139                 return resolveExternalModuleTypeByLiteral(node.arguments[0]);
59140             }
59141             var returnType = getReturnTypeOfSignature(signature);
59142             // Treat any call to the global 'Symbol' function that is part of a const variable or readonly property
59143             // as a fresh unique symbol literal type.
59144             if (returnType.flags & 12288 /* ESSymbolLike */ && isSymbolOrSymbolForCall(node)) {
59145                 return getESSymbolLikeTypeForNode(ts.walkUpParenthesizedExpressions(node.parent));
59146             }
59147             if (node.kind === 196 /* CallExpression */ && node.parent.kind === 226 /* ExpressionStatement */ &&
59148                 returnType.flags & 16384 /* Void */ && getTypePredicateOfSignature(signature)) {
59149                 if (!ts.isDottedName(node.expression)) {
59150                     error(node.expression, ts.Diagnostics.Assertions_require_the_call_target_to_be_an_identifier_or_qualified_name);
59151                 }
59152                 else if (!getEffectsSignature(node)) {
59153                     var diagnostic = error(node.expression, ts.Diagnostics.Assertions_require_every_name_in_the_call_target_to_be_declared_with_an_explicit_type_annotation);
59154                     getTypeOfDottedName(node.expression, diagnostic);
59155                 }
59156             }
59157             if (ts.isInJSFile(node)) {
59158                 var decl = ts.getDeclarationOfExpando(node);
59159                 if (decl) {
59160                     var jsSymbol = getSymbolOfNode(decl);
59161                     if (jsSymbol && ts.hasEntries(jsSymbol.exports)) {
59162                         var jsAssignmentType = createAnonymousType(jsSymbol, jsSymbol.exports, ts.emptyArray, ts.emptyArray, undefined, undefined);
59163                         jsAssignmentType.objectFlags |= 16384 /* JSLiteral */;
59164                         return getIntersectionType([returnType, jsAssignmentType]);
59165                     }
59166                 }
59167             }
59168             return returnType;
59169         }
59170         function isSymbolOrSymbolForCall(node) {
59171             if (!ts.isCallExpression(node))
59172                 return false;
59173             var left = node.expression;
59174             if (ts.isPropertyAccessExpression(left) && left.name.escapedText === "for") {
59175                 left = left.expression;
59176             }
59177             if (!ts.isIdentifier(left) || left.escapedText !== "Symbol") {
59178                 return false;
59179             }
59180             // make sure `Symbol` is the global symbol
59181             var globalESSymbol = getGlobalESSymbolConstructorSymbol(/*reportErrors*/ false);
59182             if (!globalESSymbol) {
59183                 return false;
59184             }
59185             return globalESSymbol === resolveName(left, "Symbol", 111551 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false);
59186         }
59187         function checkImportCallExpression(node) {
59188             // Check grammar of dynamic import
59189             if (!checkGrammarArguments(node.arguments))
59190                 checkGrammarImportCallExpression(node);
59191             if (node.arguments.length === 0) {
59192                 return createPromiseReturnType(node, anyType);
59193             }
59194             var specifier = node.arguments[0];
59195             var specifierType = checkExpressionCached(specifier);
59196             // Even though multiple arguments is grammatically incorrect, type-check extra arguments for completion
59197             for (var i = 1; i < node.arguments.length; ++i) {
59198                 checkExpressionCached(node.arguments[i]);
59199             }
59200             if (specifierType.flags & 32768 /* Undefined */ || specifierType.flags & 65536 /* Null */ || !isTypeAssignableTo(specifierType, stringType)) {
59201                 error(specifier, ts.Diagnostics.Dynamic_import_s_specifier_must_be_of_type_string_but_here_has_type_0, typeToString(specifierType));
59202             }
59203             // resolveExternalModuleName will return undefined if the moduleReferenceExpression is not a string literal
59204             var moduleSymbol = resolveExternalModuleName(node, specifier);
59205             if (moduleSymbol) {
59206                 var esModuleSymbol = resolveESModuleSymbol(moduleSymbol, specifier, /*dontRecursivelyResolve*/ true, /*suppressUsageError*/ false);
59207                 if (esModuleSymbol) {
59208                     return createPromiseReturnType(node, getTypeWithSyntheticDefaultImportType(getTypeOfSymbol(esModuleSymbol), esModuleSymbol, moduleSymbol));
59209                 }
59210             }
59211             return createPromiseReturnType(node, anyType);
59212         }
59213         function getTypeWithSyntheticDefaultImportType(type, symbol, originalSymbol) {
59214             if (allowSyntheticDefaultImports && type && type !== errorType) {
59215                 var synthType = type;
59216                 if (!synthType.syntheticType) {
59217                     var file = ts.find(originalSymbol.declarations, ts.isSourceFile);
59218                     var hasSyntheticDefault = canHaveSyntheticDefault(file, originalSymbol, /*dontResolveAlias*/ false);
59219                     if (hasSyntheticDefault) {
59220                         var memberTable = ts.createSymbolTable();
59221                         var newSymbol = createSymbol(2097152 /* Alias */, "default" /* Default */);
59222                         newSymbol.nameType = getLiteralType("default");
59223                         newSymbol.target = resolveSymbol(symbol);
59224                         memberTable.set("default" /* Default */, newSymbol);
59225                         var anonymousSymbol = createSymbol(2048 /* TypeLiteral */, "__type" /* Type */);
59226                         var defaultContainingObject = createAnonymousType(anonymousSymbol, memberTable, ts.emptyArray, ts.emptyArray, /*stringIndexInfo*/ undefined, /*numberIndexInfo*/ undefined);
59227                         anonymousSymbol.type = defaultContainingObject;
59228                         synthType.syntheticType = isValidSpreadType(type) ? getSpreadType(type, defaultContainingObject, anonymousSymbol, /*objectFlags*/ 0, /*readonly*/ false) : defaultContainingObject;
59229                     }
59230                     else {
59231                         synthType.syntheticType = type;
59232                     }
59233                 }
59234                 return synthType.syntheticType;
59235             }
59236             return type;
59237         }
59238         function isCommonJsRequire(node) {
59239             if (!ts.isRequireCall(node, /*checkArgumentIsStringLiteralLike*/ true)) {
59240                 return false;
59241             }
59242             // Make sure require is not a local function
59243             if (!ts.isIdentifier(node.expression))
59244                 return ts.Debug.fail();
59245             var resolvedRequire = resolveName(node.expression, node.expression.escapedText, 111551 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ true); // TODO: GH#18217
59246             if (resolvedRequire === requireSymbol) {
59247                 return true;
59248             }
59249             // project includes symbol named 'require' - make sure that it is ambient and local non-alias
59250             if (resolvedRequire.flags & 2097152 /* Alias */) {
59251                 return false;
59252             }
59253             var targetDeclarationKind = resolvedRequire.flags & 16 /* Function */
59254                 ? 244 /* FunctionDeclaration */
59255                 : resolvedRequire.flags & 3 /* Variable */
59256                     ? 242 /* VariableDeclaration */
59257                     : 0 /* Unknown */;
59258             if (targetDeclarationKind !== 0 /* Unknown */) {
59259                 var decl = ts.getDeclarationOfKind(resolvedRequire, targetDeclarationKind);
59260                 // function/variable declaration should be ambient
59261                 return !!decl && !!(decl.flags & 8388608 /* Ambient */);
59262             }
59263             return false;
59264         }
59265         function checkTaggedTemplateExpression(node) {
59266             if (!checkGrammarTaggedTemplateChain(node))
59267                 checkGrammarTypeArguments(node, node.typeArguments);
59268             if (languageVersion < 2 /* ES2015 */) {
59269                 checkExternalEmitHelpers(node, 131072 /* MakeTemplateObject */);
59270             }
59271             return getReturnTypeOfSignature(getResolvedSignature(node));
59272         }
59273         function checkAssertion(node) {
59274             return checkAssertionWorker(node, node.type, node.expression);
59275         }
59276         function isValidConstAssertionArgument(node) {
59277             switch (node.kind) {
59278                 case 10 /* StringLiteral */:
59279                 case 14 /* NoSubstitutionTemplateLiteral */:
59280                 case 8 /* NumericLiteral */:
59281                 case 9 /* BigIntLiteral */:
59282                 case 106 /* TrueKeyword */:
59283                 case 91 /* FalseKeyword */:
59284                 case 192 /* ArrayLiteralExpression */:
59285                 case 193 /* ObjectLiteralExpression */:
59286                     return true;
59287                 case 200 /* ParenthesizedExpression */:
59288                     return isValidConstAssertionArgument(node.expression);
59289                 case 207 /* PrefixUnaryExpression */:
59290                     var op = node.operator;
59291                     var arg = node.operand;
59292                     return op === 40 /* MinusToken */ && (arg.kind === 8 /* NumericLiteral */ || arg.kind === 9 /* BigIntLiteral */) ||
59293                         op === 39 /* PlusToken */ && arg.kind === 8 /* NumericLiteral */;
59294                 case 194 /* PropertyAccessExpression */:
59295                 case 195 /* ElementAccessExpression */:
59296                     var expr = node.expression;
59297                     if (ts.isIdentifier(expr)) {
59298                         var symbol = getSymbolAtLocation(expr);
59299                         if (symbol && symbol.flags & 2097152 /* Alias */) {
59300                             symbol = resolveAlias(symbol);
59301                         }
59302                         return !!(symbol && (symbol.flags & 384 /* Enum */) && getEnumKind(symbol) === 1 /* Literal */);
59303                     }
59304             }
59305             return false;
59306         }
59307         function checkAssertionWorker(errNode, type, expression, checkMode) {
59308             var exprType = checkExpression(expression, checkMode);
59309             if (ts.isConstTypeReference(type)) {
59310                 if (!isValidConstAssertionArgument(expression)) {
59311                     error(expression, ts.Diagnostics.A_const_assertions_can_only_be_applied_to_references_to_enum_members_or_string_number_boolean_array_or_object_literals);
59312                 }
59313                 return getRegularTypeOfLiteralType(exprType);
59314             }
59315             checkSourceElement(type);
59316             exprType = getRegularTypeOfObjectLiteral(getBaseTypeOfLiteralType(exprType));
59317             var targetType = getTypeFromTypeNode(type);
59318             if (produceDiagnostics && targetType !== errorType) {
59319                 var widenedType = getWidenedType(exprType);
59320                 if (!isTypeComparableTo(targetType, widenedType)) {
59321                     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);
59322                 }
59323             }
59324             return targetType;
59325         }
59326         function checkNonNullChain(node) {
59327             var leftType = checkExpression(node.expression);
59328             var nonOptionalType = getOptionalExpressionType(leftType, node.expression);
59329             return propagateOptionalTypeMarker(getNonNullableType(nonOptionalType), node, nonOptionalType !== leftType);
59330         }
59331         function checkNonNullAssertion(node) {
59332             return node.flags & 32 /* OptionalChain */ ? checkNonNullChain(node) :
59333                 getNonNullableType(checkExpression(node.expression));
59334         }
59335         function checkMetaProperty(node) {
59336             checkGrammarMetaProperty(node);
59337             if (node.keywordToken === 99 /* NewKeyword */) {
59338                 return checkNewTargetMetaProperty(node);
59339             }
59340             if (node.keywordToken === 96 /* ImportKeyword */) {
59341                 return checkImportMetaProperty(node);
59342             }
59343             return ts.Debug.assertNever(node.keywordToken);
59344         }
59345         function checkNewTargetMetaProperty(node) {
59346             var container = ts.getNewTargetContainer(node);
59347             if (!container) {
59348                 error(node, ts.Diagnostics.Meta_property_0_is_only_allowed_in_the_body_of_a_function_declaration_function_expression_or_constructor, "new.target");
59349                 return errorType;
59350             }
59351             else if (container.kind === 162 /* Constructor */) {
59352                 var symbol = getSymbolOfNode(container.parent);
59353                 return getTypeOfSymbol(symbol);
59354             }
59355             else {
59356                 var symbol = getSymbolOfNode(container);
59357                 return getTypeOfSymbol(symbol);
59358             }
59359         }
59360         function checkImportMetaProperty(node) {
59361             if (moduleKind !== ts.ModuleKind.ESNext && moduleKind !== ts.ModuleKind.System) {
59362                 error(node, ts.Diagnostics.The_import_meta_meta_property_is_only_allowed_when_the_module_option_is_esnext_or_system);
59363             }
59364             var file = ts.getSourceFileOfNode(node);
59365             ts.Debug.assert(!!(file.flags & 2097152 /* PossiblyContainsImportMeta */), "Containing file is missing import meta node flag.");
59366             ts.Debug.assert(!!file.externalModuleIndicator, "Containing file should be a module.");
59367             return node.name.escapedText === "meta" ? getGlobalImportMetaType() : errorType;
59368         }
59369         function getTypeOfParameter(symbol) {
59370             var type = getTypeOfSymbol(symbol);
59371             if (strictNullChecks) {
59372                 var declaration = symbol.valueDeclaration;
59373                 if (declaration && ts.hasInitializer(declaration)) {
59374                     return getOptionalType(type);
59375                 }
59376             }
59377             return type;
59378         }
59379         function getParameterNameAtPosition(signature, pos) {
59380             var paramCount = signature.parameters.length - (signatureHasRestParameter(signature) ? 1 : 0);
59381             if (pos < paramCount) {
59382                 return signature.parameters[pos].escapedName;
59383             }
59384             var restParameter = signature.parameters[paramCount] || unknownSymbol;
59385             var restType = getTypeOfSymbol(restParameter);
59386             if (isTupleType(restType)) {
59387                 var associatedNames = restType.target.associatedNames;
59388                 var index = pos - paramCount;
59389                 return associatedNames && associatedNames[index] || restParameter.escapedName + "_" + index;
59390             }
59391             return restParameter.escapedName;
59392         }
59393         function getTypeAtPosition(signature, pos) {
59394             return tryGetTypeAtPosition(signature, pos) || anyType;
59395         }
59396         function tryGetTypeAtPosition(signature, pos) {
59397             var paramCount = signature.parameters.length - (signatureHasRestParameter(signature) ? 1 : 0);
59398             if (pos < paramCount) {
59399                 return getTypeOfParameter(signature.parameters[pos]);
59400             }
59401             if (signatureHasRestParameter(signature)) {
59402                 // We want to return the value undefined for an out of bounds parameter position,
59403                 // so we need to check bounds here before calling getIndexedAccessType (which
59404                 // otherwise would return the type 'undefined').
59405                 var restType = getTypeOfSymbol(signature.parameters[paramCount]);
59406                 var index = pos - paramCount;
59407                 if (!isTupleType(restType) || restType.target.hasRestElement || index < getTypeArguments(restType).length) {
59408                     return getIndexedAccessType(restType, getLiteralType(index));
59409                 }
59410             }
59411             return undefined;
59412         }
59413         function getRestTypeAtPosition(source, pos) {
59414             var paramCount = getParameterCount(source);
59415             var restType = getEffectiveRestType(source);
59416             var nonRestCount = paramCount - (restType ? 1 : 0);
59417             if (restType && pos === nonRestCount) {
59418                 return restType;
59419             }
59420             var types = [];
59421             var names = [];
59422             for (var i = pos; i < nonRestCount; i++) {
59423                 types.push(getTypeAtPosition(source, i));
59424                 names.push(getParameterNameAtPosition(source, i));
59425             }
59426             if (restType) {
59427                 types.push(getIndexedAccessType(restType, numberType));
59428                 names.push(getParameterNameAtPosition(source, nonRestCount));
59429             }
59430             var minArgumentCount = getMinArgumentCount(source);
59431             var minLength = minArgumentCount < pos ? 0 : minArgumentCount - pos;
59432             return createTupleType(types, minLength, !!restType, /*readonly*/ false, names);
59433         }
59434         function getParameterCount(signature) {
59435             var length = signature.parameters.length;
59436             if (signatureHasRestParameter(signature)) {
59437                 var restType = getTypeOfSymbol(signature.parameters[length - 1]);
59438                 if (isTupleType(restType)) {
59439                     return length + getTypeArguments(restType).length - 1;
59440                 }
59441             }
59442             return length;
59443         }
59444         function getMinArgumentCount(signature, strongArityForUntypedJS) {
59445             if (signatureHasRestParameter(signature)) {
59446                 var restType = getTypeOfSymbol(signature.parameters[signature.parameters.length - 1]);
59447                 if (isTupleType(restType)) {
59448                     var minLength = restType.target.minLength;
59449                     if (minLength > 0) {
59450                         return signature.parameters.length - 1 + minLength;
59451                     }
59452                 }
59453             }
59454             if (!strongArityForUntypedJS && signature.flags & 16 /* IsUntypedSignatureInJSFile */) {
59455                 return 0;
59456             }
59457             return signature.minArgumentCount;
59458         }
59459         function hasEffectiveRestParameter(signature) {
59460             if (signatureHasRestParameter(signature)) {
59461                 var restType = getTypeOfSymbol(signature.parameters[signature.parameters.length - 1]);
59462                 return !isTupleType(restType) || restType.target.hasRestElement;
59463             }
59464             return false;
59465         }
59466         function getEffectiveRestType(signature) {
59467             if (signatureHasRestParameter(signature)) {
59468                 var restType = getTypeOfSymbol(signature.parameters[signature.parameters.length - 1]);
59469                 return isTupleType(restType) ? getRestArrayTypeOfTupleType(restType) : restType;
59470             }
59471             return undefined;
59472         }
59473         function getNonArrayRestType(signature) {
59474             var restType = getEffectiveRestType(signature);
59475             return restType && !isArrayType(restType) && !isTypeAny(restType) && (getReducedType(restType).flags & 131072 /* Never */) === 0 ? restType : undefined;
59476         }
59477         function getTypeOfFirstParameterOfSignature(signature) {
59478             return getTypeOfFirstParameterOfSignatureWithFallback(signature, neverType);
59479         }
59480         function getTypeOfFirstParameterOfSignatureWithFallback(signature, fallbackType) {
59481             return signature.parameters.length > 0 ? getTypeAtPosition(signature, 0) : fallbackType;
59482         }
59483         function inferFromAnnotatedParameters(signature, context, inferenceContext) {
59484             var len = signature.parameters.length - (signatureHasRestParameter(signature) ? 1 : 0);
59485             for (var i = 0; i < len; i++) {
59486                 var declaration = signature.parameters[i].valueDeclaration;
59487                 if (declaration.type) {
59488                     var typeNode = ts.getEffectiveTypeAnnotationNode(declaration);
59489                     if (typeNode) {
59490                         inferTypes(inferenceContext.inferences, getTypeFromTypeNode(typeNode), getTypeAtPosition(context, i));
59491                     }
59492                 }
59493             }
59494             var restType = getEffectiveRestType(context);
59495             if (restType && restType.flags & 262144 /* TypeParameter */) {
59496                 // The contextual signature has a generic rest parameter. We first instantiate the contextual
59497                 // signature (without fixing type parameters) and assign types to contextually typed parameters.
59498                 var instantiatedContext = instantiateSignature(context, inferenceContext.nonFixingMapper);
59499                 assignContextualParameterTypes(signature, instantiatedContext);
59500                 // We then infer from a tuple type representing the parameters that correspond to the contextual
59501                 // rest parameter.
59502                 var restPos = getParameterCount(context) - 1;
59503                 inferTypes(inferenceContext.inferences, getRestTypeAtPosition(signature, restPos), restType);
59504             }
59505         }
59506         function assignContextualParameterTypes(signature, context) {
59507             signature.typeParameters = context.typeParameters;
59508             if (context.thisParameter) {
59509                 var parameter = signature.thisParameter;
59510                 if (!parameter || parameter.valueDeclaration && !parameter.valueDeclaration.type) {
59511                     if (!parameter) {
59512                         signature.thisParameter = createSymbolWithType(context.thisParameter, /*type*/ undefined);
59513                     }
59514                     assignParameterType(signature.thisParameter, getTypeOfSymbol(context.thisParameter));
59515                 }
59516             }
59517             var len = signature.parameters.length - (signatureHasRestParameter(signature) ? 1 : 0);
59518             for (var i = 0; i < len; i++) {
59519                 var parameter = signature.parameters[i];
59520                 if (!ts.getEffectiveTypeAnnotationNode(parameter.valueDeclaration)) {
59521                     var contextualParameterType = tryGetTypeAtPosition(context, i);
59522                     assignParameterType(parameter, contextualParameterType);
59523                 }
59524             }
59525             if (signatureHasRestParameter(signature)) {
59526                 // parameter might be a transient symbol generated by use of `arguments` in the function body.
59527                 var parameter = ts.last(signature.parameters);
59528                 if (ts.isTransientSymbol(parameter) || !ts.getEffectiveTypeAnnotationNode(parameter.valueDeclaration)) {
59529                     var contextualParameterType = getRestTypeAtPosition(context, len);
59530                     assignParameterType(parameter, contextualParameterType);
59531                 }
59532             }
59533         }
59534         function assignNonContextualParameterTypes(signature) {
59535             if (signature.thisParameter) {
59536                 assignParameterType(signature.thisParameter);
59537             }
59538             for (var _i = 0, _a = signature.parameters; _i < _a.length; _i++) {
59539                 var parameter = _a[_i];
59540                 assignParameterType(parameter);
59541             }
59542         }
59543         function assignParameterType(parameter, type) {
59544             var links = getSymbolLinks(parameter);
59545             if (!links.type) {
59546                 var declaration = parameter.valueDeclaration;
59547                 links.type = type || getWidenedTypeForVariableLikeDeclaration(declaration, /*includeOptionality*/ true);
59548                 if (declaration.name.kind !== 75 /* Identifier */) {
59549                     // if inference didn't come up with anything but unknown, fall back to the binding pattern if present.
59550                     if (links.type === unknownType) {
59551                         links.type = getTypeFromBindingPattern(declaration.name);
59552                     }
59553                     assignBindingElementTypes(declaration.name);
59554                 }
59555             }
59556         }
59557         // When contextual typing assigns a type to a parameter that contains a binding pattern, we also need to push
59558         // the destructured type into the contained binding elements.
59559         function assignBindingElementTypes(pattern) {
59560             for (var _i = 0, _a = pattern.elements; _i < _a.length; _i++) {
59561                 var element = _a[_i];
59562                 if (!ts.isOmittedExpression(element)) {
59563                     if (element.name.kind === 75 /* Identifier */) {
59564                         getSymbolLinks(getSymbolOfNode(element)).type = getTypeForBindingElement(element);
59565                     }
59566                     else {
59567                         assignBindingElementTypes(element.name);
59568                     }
59569                 }
59570             }
59571         }
59572         function createPromiseType(promisedType) {
59573             // creates a `Promise<T>` type where `T` is the promisedType argument
59574             var globalPromiseType = getGlobalPromiseType(/*reportErrors*/ true);
59575             if (globalPromiseType !== emptyGenericType) {
59576                 // if the promised type is itself a promise, get the underlying type; otherwise, fallback to the promised type
59577                 promisedType = getAwaitedType(promisedType) || unknownType;
59578                 return createTypeReference(globalPromiseType, [promisedType]);
59579             }
59580             return unknownType;
59581         }
59582         function createPromiseLikeType(promisedType) {
59583             // creates a `PromiseLike<T>` type where `T` is the promisedType argument
59584             var globalPromiseLikeType = getGlobalPromiseLikeType(/*reportErrors*/ true);
59585             if (globalPromiseLikeType !== emptyGenericType) {
59586                 // if the promised type is itself a promise, get the underlying type; otherwise, fallback to the promised type
59587                 promisedType = getAwaitedType(promisedType) || unknownType;
59588                 return createTypeReference(globalPromiseLikeType, [promisedType]);
59589             }
59590             return unknownType;
59591         }
59592         function createPromiseReturnType(func, promisedType) {
59593             var promiseType = createPromiseType(promisedType);
59594             if (promiseType === unknownType) {
59595                 error(func, ts.isImportCall(func) ?
59596                     ts.Diagnostics.A_dynamic_import_call_returns_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_include_ES2015_in_your_lib_option :
59597                     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);
59598                 return errorType;
59599             }
59600             else if (!getGlobalPromiseConstructorSymbol(/*reportErrors*/ true)) {
59601                 error(func, ts.isImportCall(func) ?
59602                     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 :
59603                     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);
59604             }
59605             return promiseType;
59606         }
59607         function getReturnTypeFromBody(func, checkMode) {
59608             if (!func.body) {
59609                 return errorType;
59610             }
59611             var functionFlags = ts.getFunctionFlags(func);
59612             var isAsync = (functionFlags & 2 /* Async */) !== 0;
59613             var isGenerator = (functionFlags & 1 /* Generator */) !== 0;
59614             var returnType;
59615             var yieldType;
59616             var nextType;
59617             var fallbackReturnType = voidType;
59618             if (func.body.kind !== 223 /* Block */) { // Async or normal arrow function
59619                 returnType = checkExpressionCached(func.body, checkMode && checkMode & ~8 /* SkipGenericFunctions */);
59620                 if (isAsync) {
59621                     // From within an async function you can return either a non-promise value or a promise. Any
59622                     // Promise/A+ compatible implementation will always assimilate any foreign promise, so the
59623                     // return type of the body should be unwrapped to its awaited type, which we will wrap in
59624                     // the native Promise<T> type later in this function.
59625                     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);
59626                 }
59627             }
59628             else if (isGenerator) { // Generator or AsyncGenerator function
59629                 var returnTypes = checkAndAggregateReturnExpressionTypes(func, checkMode);
59630                 if (!returnTypes) {
59631                     fallbackReturnType = neverType;
59632                 }
59633                 else if (returnTypes.length > 0) {
59634                     returnType = getUnionType(returnTypes, 2 /* Subtype */);
59635                 }
59636                 var _a = checkAndAggregateYieldOperandTypes(func, checkMode), yieldTypes = _a.yieldTypes, nextTypes = _a.nextTypes;
59637                 yieldType = ts.some(yieldTypes) ? getUnionType(yieldTypes, 2 /* Subtype */) : undefined;
59638                 nextType = ts.some(nextTypes) ? getIntersectionType(nextTypes) : undefined;
59639             }
59640             else { // Async or normal function
59641                 var types = checkAndAggregateReturnExpressionTypes(func, checkMode);
59642                 if (!types) {
59643                     // For an async function, the return type will not be never, but rather a Promise for never.
59644                     return functionFlags & 2 /* Async */
59645                         ? createPromiseReturnType(func, neverType) // Async function
59646                         : neverType; // Normal function
59647                 }
59648                 if (types.length === 0) {
59649                     // For an async function, the return type will not be void, but rather a Promise for void.
59650                     return functionFlags & 2 /* Async */
59651                         ? createPromiseReturnType(func, voidType) // Async function
59652                         : voidType; // Normal function
59653                 }
59654                 // Return a union of the return expression types.
59655                 returnType = getUnionType(types, 2 /* Subtype */);
59656             }
59657             if (returnType || yieldType || nextType) {
59658                 if (yieldType)
59659                     reportErrorsFromWidening(func, yieldType, 3 /* GeneratorYield */);
59660                 if (returnType)
59661                     reportErrorsFromWidening(func, returnType, 1 /* FunctionReturn */);
59662                 if (nextType)
59663                     reportErrorsFromWidening(func, nextType, 2 /* GeneratorNext */);
59664                 if (returnType && isUnitType(returnType) ||
59665                     yieldType && isUnitType(yieldType) ||
59666                     nextType && isUnitType(nextType)) {
59667                     var contextualSignature = getContextualSignatureForFunctionLikeDeclaration(func);
59668                     var contextualType = !contextualSignature ? undefined :
59669                         contextualSignature === getSignatureFromDeclaration(func) ? isGenerator ? undefined : returnType :
59670                             instantiateContextualType(getReturnTypeOfSignature(contextualSignature), func);
59671                     if (isGenerator) {
59672                         yieldType = getWidenedLiteralLikeTypeForContextualIterationTypeIfNeeded(yieldType, contextualType, 0 /* Yield */, isAsync);
59673                         returnType = getWidenedLiteralLikeTypeForContextualIterationTypeIfNeeded(returnType, contextualType, 1 /* Return */, isAsync);
59674                         nextType = getWidenedLiteralLikeTypeForContextualIterationTypeIfNeeded(nextType, contextualType, 2 /* Next */, isAsync);
59675                     }
59676                     else {
59677                         returnType = getWidenedLiteralLikeTypeForContextualReturnTypeIfNeeded(returnType, contextualType, isAsync);
59678                     }
59679                 }
59680                 if (yieldType)
59681                     yieldType = getWidenedType(yieldType);
59682                 if (returnType)
59683                     returnType = getWidenedType(returnType);
59684                 if (nextType)
59685                     nextType = getWidenedType(nextType);
59686             }
59687             if (isGenerator) {
59688                 return createGeneratorReturnType(yieldType || neverType, returnType || fallbackReturnType, nextType || getContextualIterationType(2 /* Next */, func) || unknownType, isAsync);
59689             }
59690             else {
59691                 // From within an async function you can return either a non-promise value or a promise. Any
59692                 // Promise/A+ compatible implementation will always assimilate any foreign promise, so the
59693                 // return type of the body is awaited type of the body, wrapped in a native Promise<T> type.
59694                 return isAsync
59695                     ? createPromiseType(returnType || fallbackReturnType)
59696                     : returnType || fallbackReturnType;
59697             }
59698         }
59699         function createGeneratorReturnType(yieldType, returnType, nextType, isAsyncGenerator) {
59700             var resolver = isAsyncGenerator ? asyncIterationTypesResolver : syncIterationTypesResolver;
59701             var globalGeneratorType = resolver.getGlobalGeneratorType(/*reportErrors*/ false);
59702             yieldType = resolver.resolveIterationType(yieldType, /*errorNode*/ undefined) || unknownType;
59703             returnType = resolver.resolveIterationType(returnType, /*errorNode*/ undefined) || unknownType;
59704             nextType = resolver.resolveIterationType(nextType, /*errorNode*/ undefined) || unknownType;
59705             if (globalGeneratorType === emptyGenericType) {
59706                 // Fall back to the global IterableIterator if returnType is assignable to the expected return iteration
59707                 // type of IterableIterator, and the expected next iteration type of IterableIterator is assignable to
59708                 // nextType.
59709                 var globalType = resolver.getGlobalIterableIteratorType(/*reportErrors*/ false);
59710                 var iterationTypes = globalType !== emptyGenericType ? getIterationTypesOfGlobalIterableType(globalType, resolver) : undefined;
59711                 var iterableIteratorReturnType = iterationTypes ? iterationTypes.returnType : anyType;
59712                 var iterableIteratorNextType = iterationTypes ? iterationTypes.nextType : undefinedType;
59713                 if (isTypeAssignableTo(returnType, iterableIteratorReturnType) &&
59714                     isTypeAssignableTo(iterableIteratorNextType, nextType)) {
59715                     if (globalType !== emptyGenericType) {
59716                         return createTypeFromGenericGlobalType(globalType, [yieldType]);
59717                     }
59718                     // The global IterableIterator type doesn't exist, so report an error
59719                     resolver.getGlobalIterableIteratorType(/*reportErrors*/ true);
59720                     return emptyObjectType;
59721                 }
59722                 // The global Generator type doesn't exist, so report an error
59723                 resolver.getGlobalGeneratorType(/*reportErrors*/ true);
59724                 return emptyObjectType;
59725             }
59726             return createTypeFromGenericGlobalType(globalGeneratorType, [yieldType, returnType, nextType]);
59727         }
59728         function checkAndAggregateYieldOperandTypes(func, checkMode) {
59729             var yieldTypes = [];
59730             var nextTypes = [];
59731             var isAsync = (ts.getFunctionFlags(func) & 2 /* Async */) !== 0;
59732             ts.forEachYieldExpression(func.body, function (yieldExpression) {
59733                 var yieldExpressionType = yieldExpression.expression ? checkExpression(yieldExpression.expression, checkMode) : undefinedWideningType;
59734                 ts.pushIfUnique(yieldTypes, getYieldedTypeOfYieldExpression(yieldExpression, yieldExpressionType, anyType, isAsync));
59735                 var nextType;
59736                 if (yieldExpression.asteriskToken) {
59737                     var iterationTypes = getIterationTypesOfIterable(yieldExpressionType, isAsync ? 19 /* AsyncYieldStar */ : 17 /* YieldStar */, yieldExpression.expression);
59738                     nextType = iterationTypes && iterationTypes.nextType;
59739                 }
59740                 else {
59741                     nextType = getContextualType(yieldExpression);
59742                 }
59743                 if (nextType)
59744                     ts.pushIfUnique(nextTypes, nextType);
59745             });
59746             return { yieldTypes: yieldTypes, nextTypes: nextTypes };
59747         }
59748         function getYieldedTypeOfYieldExpression(node, expressionType, sentType, isAsync) {
59749             var errorNode = node.expression || node;
59750             // A `yield*` expression effectively yields everything that its operand yields
59751             var yieldedType = node.asteriskToken ? checkIteratedTypeOrElementType(isAsync ? 19 /* AsyncYieldStar */ : 17 /* YieldStar */, expressionType, sentType, errorNode) : expressionType;
59752             return !isAsync ? yieldedType : getAwaitedType(yieldedType, errorNode, node.asteriskToken
59753                 ? 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
59754                 : ts.Diagnostics.Type_of_yield_operand_in_an_async_generator_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member);
59755         }
59756         /**
59757          * Collect the TypeFacts learned from a typeof switch with
59758          * total clauses `witnesses`, and the active clause ranging
59759          * from `start` to `end`. Parameter `hasDefault` denotes
59760          * whether the active clause contains a default clause.
59761          */
59762         function getFactsFromTypeofSwitch(start, end, witnesses, hasDefault) {
59763             var facts = 0 /* None */;
59764             // When in the default we only collect inequality facts
59765             // because default is 'in theory' a set of infinite
59766             // equalities.
59767             if (hasDefault) {
59768                 // Value is not equal to any types after the active clause.
59769                 for (var i = end; i < witnesses.length; i++) {
59770                     facts |= typeofNEFacts.get(witnesses[i]) || 32768 /* TypeofNEHostObject */;
59771                 }
59772                 // Remove inequalities for types that appear in the
59773                 // active clause because they appear before other
59774                 // types collected so far.
59775                 for (var i = start; i < end; i++) {
59776                     facts &= ~(typeofNEFacts.get(witnesses[i]) || 0);
59777                 }
59778                 // Add inequalities for types before the active clause unconditionally.
59779                 for (var i = 0; i < start; i++) {
59780                     facts |= typeofNEFacts.get(witnesses[i]) || 32768 /* TypeofNEHostObject */;
59781                 }
59782             }
59783             // When in an active clause without default the set of
59784             // equalities is finite.
59785             else {
59786                 // Add equalities for all types in the active clause.
59787                 for (var i = start; i < end; i++) {
59788                     facts |= typeofEQFacts.get(witnesses[i]) || 128 /* TypeofEQHostObject */;
59789                 }
59790                 // Remove equalities for types that appear before the
59791                 // active clause.
59792                 for (var i = 0; i < start; i++) {
59793                     facts &= ~(typeofEQFacts.get(witnesses[i]) || 0);
59794                 }
59795             }
59796             return facts;
59797         }
59798         function isExhaustiveSwitchStatement(node) {
59799             var links = getNodeLinks(node);
59800             return links.isExhaustive !== undefined ? links.isExhaustive : (links.isExhaustive = computeExhaustiveSwitchStatement(node));
59801         }
59802         function computeExhaustiveSwitchStatement(node) {
59803             if (node.expression.kind === 204 /* TypeOfExpression */) {
59804                 var operandType = getTypeOfExpression(node.expression.expression);
59805                 var witnesses = getSwitchClauseTypeOfWitnesses(node, /*retainDefault*/ false);
59806                 // notEqualFacts states that the type of the switched value is not equal to every type in the switch.
59807                 var notEqualFacts_1 = getFactsFromTypeofSwitch(0, 0, witnesses, /*hasDefault*/ true);
59808                 var type_3 = getBaseConstraintOfType(operandType) || operandType;
59809                 return !!(filterType(type_3, function (t) { return (getTypeFacts(t) & notEqualFacts_1) === notEqualFacts_1; }).flags & 131072 /* Never */);
59810             }
59811             var type = getTypeOfExpression(node.expression);
59812             if (!isLiteralType(type)) {
59813                 return false;
59814             }
59815             var switchTypes = getSwitchClauseTypes(node);
59816             if (!switchTypes.length || ts.some(switchTypes, isNeitherUnitTypeNorNever)) {
59817                 return false;
59818             }
59819             return eachTypeContainedIn(mapType(type, getRegularTypeOfLiteralType), switchTypes);
59820         }
59821         function functionHasImplicitReturn(func) {
59822             return func.endFlowNode && isReachableFlowNode(func.endFlowNode);
59823         }
59824         /** NOTE: Return value of `[]` means a different thing than `undefined`. `[]` means func returns `void`, `undefined` means it returns `never`. */
59825         function checkAndAggregateReturnExpressionTypes(func, checkMode) {
59826             var functionFlags = ts.getFunctionFlags(func);
59827             var aggregatedTypes = [];
59828             var hasReturnWithNoExpression = functionHasImplicitReturn(func);
59829             var hasReturnOfTypeNever = false;
59830             ts.forEachReturnStatement(func.body, function (returnStatement) {
59831                 var expr = returnStatement.expression;
59832                 if (expr) {
59833                     var type = checkExpressionCached(expr, checkMode && checkMode & ~8 /* SkipGenericFunctions */);
59834                     if (functionFlags & 2 /* Async */) {
59835                         // From within an async function you can return either a non-promise value or a promise. Any
59836                         // Promise/A+ compatible implementation will always assimilate any foreign promise, so the
59837                         // return type of the body should be unwrapped to its awaited type, which should be wrapped in
59838                         // the native Promise<T> type by the caller.
59839                         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);
59840                     }
59841                     if (type.flags & 131072 /* Never */) {
59842                         hasReturnOfTypeNever = true;
59843                     }
59844                     ts.pushIfUnique(aggregatedTypes, type);
59845                 }
59846                 else {
59847                     hasReturnWithNoExpression = true;
59848                 }
59849             });
59850             if (aggregatedTypes.length === 0 && !hasReturnWithNoExpression && (hasReturnOfTypeNever || mayReturnNever(func))) {
59851                 return undefined;
59852             }
59853             if (strictNullChecks && aggregatedTypes.length && hasReturnWithNoExpression &&
59854                 !(isJSConstructor(func) && aggregatedTypes.some(function (t) { return t.symbol === func.symbol; }))) {
59855                 // Javascript "callable constructors", containing eg `if (!(this instanceof A)) return new A()` should not add undefined
59856                 ts.pushIfUnique(aggregatedTypes, undefinedType);
59857             }
59858             return aggregatedTypes;
59859         }
59860         function mayReturnNever(func) {
59861             switch (func.kind) {
59862                 case 201 /* FunctionExpression */:
59863                 case 202 /* ArrowFunction */:
59864                     return true;
59865                 case 161 /* MethodDeclaration */:
59866                     return func.parent.kind === 193 /* ObjectLiteralExpression */;
59867                 default:
59868                     return false;
59869             }
59870         }
59871         /**
59872          * TypeScript Specification 1.0 (6.3) - July 2014
59873          *   An explicitly typed function whose return type isn't the Void type,
59874          *   the Any type, or a union type containing the Void or Any type as a constituent
59875          *   must have at least one return statement somewhere in its body.
59876          *   An exception to this rule is if the function implementation consists of a single 'throw' statement.
59877          *
59878          * @param returnType - return type of the function, can be undefined if return type is not explicitly specified
59879          */
59880         function checkAllCodePathsInNonVoidFunctionReturnOrThrow(func, returnType) {
59881             if (!produceDiagnostics) {
59882                 return;
59883             }
59884             var functionFlags = ts.getFunctionFlags(func);
59885             var type = returnType && unwrapReturnType(returnType, functionFlags);
59886             // Functions with with an explicitly specified 'void' or 'any' return type don't need any return expressions.
59887             if (type && maybeTypeOfKind(type, 1 /* Any */ | 16384 /* Void */)) {
59888                 return;
59889             }
59890             // If all we have is a function signature, or an arrow function with an expression body, then there is nothing to check.
59891             // also if HasImplicitReturn flag is not set this means that all codepaths in function body end with return or throw
59892             if (func.kind === 160 /* MethodSignature */ || ts.nodeIsMissing(func.body) || func.body.kind !== 223 /* Block */ || !functionHasImplicitReturn(func)) {
59893                 return;
59894             }
59895             var hasExplicitReturn = func.flags & 512 /* HasExplicitReturn */;
59896             if (type && type.flags & 131072 /* Never */) {
59897                 error(ts.getEffectiveReturnTypeNode(func), ts.Diagnostics.A_function_returning_never_cannot_have_a_reachable_end_point);
59898             }
59899             else if (type && !hasExplicitReturn) {
59900                 // minimal check: function has syntactic return type annotation and no explicit return statements in the body
59901                 // this function does not conform to the specification.
59902                 // NOTE: having returnType !== undefined is a precondition for entering this branch so func.type will always be present
59903                 error(ts.getEffectiveReturnTypeNode(func), ts.Diagnostics.A_function_whose_declared_type_is_neither_void_nor_any_must_return_a_value);
59904             }
59905             else if (type && strictNullChecks && !isTypeAssignableTo(undefinedType, type)) {
59906                 error(ts.getEffectiveReturnTypeNode(func) || func, ts.Diagnostics.Function_lacks_ending_return_statement_and_return_type_does_not_include_undefined);
59907             }
59908             else if (compilerOptions.noImplicitReturns) {
59909                 if (!type) {
59910                     // If return type annotation is omitted check if function has any explicit return statements.
59911                     // If it does not have any - its inferred return type is void - don't do any checks.
59912                     // Otherwise get inferred return type from function body and report error only if it is not void / anytype
59913                     if (!hasExplicitReturn) {
59914                         return;
59915                     }
59916                     var inferredReturnType = getReturnTypeOfSignature(getSignatureFromDeclaration(func));
59917                     if (isUnwrappedReturnTypeVoidOrAny(func, inferredReturnType)) {
59918                         return;
59919                     }
59920                 }
59921                 error(ts.getEffectiveReturnTypeNode(func) || func, ts.Diagnostics.Not_all_code_paths_return_a_value);
59922             }
59923         }
59924         function checkFunctionExpressionOrObjectLiteralMethod(node, checkMode) {
59925             ts.Debug.assert(node.kind !== 161 /* MethodDeclaration */ || ts.isObjectLiteralMethod(node));
59926             checkNodeDeferred(node);
59927             // The identityMapper object is used to indicate that function expressions are wildcards
59928             if (checkMode && checkMode & 4 /* SkipContextSensitive */ && isContextSensitive(node)) {
59929                 // Skip parameters, return signature with return type that retains noncontextual parts so inferences can still be drawn in an early stage
59930                 if (!ts.getEffectiveReturnTypeNode(node) && !hasContextSensitiveParameters(node)) {
59931                     // Return plain anyFunctionType if there is no possibility we'll make inferences from the return type
59932                     var contextualSignature = getContextualSignature(node);
59933                     if (contextualSignature && couldContainTypeVariables(getReturnTypeOfSignature(contextualSignature))) {
59934                         var links = getNodeLinks(node);
59935                         if (links.contextFreeType) {
59936                             return links.contextFreeType;
59937                         }
59938                         var returnType = getReturnTypeFromBody(node, checkMode);
59939                         var returnOnlySignature = createSignature(undefined, undefined, undefined, ts.emptyArray, returnType, /*resolvedTypePredicate*/ undefined, 0, 0 /* None */);
59940                         var returnOnlyType = createAnonymousType(node.symbol, emptySymbols, [returnOnlySignature], ts.emptyArray, undefined, undefined);
59941                         returnOnlyType.objectFlags |= 2097152 /* NonInferrableType */;
59942                         return links.contextFreeType = returnOnlyType;
59943                     }
59944                 }
59945                 return anyFunctionType;
59946             }
59947             // Grammar checking
59948             var hasGrammarError = checkGrammarFunctionLikeDeclaration(node);
59949             if (!hasGrammarError && node.kind === 201 /* FunctionExpression */) {
59950                 checkGrammarForGenerator(node);
59951             }
59952             contextuallyCheckFunctionExpressionOrObjectLiteralMethod(node, checkMode);
59953             return getTypeOfSymbol(getSymbolOfNode(node));
59954         }
59955         function contextuallyCheckFunctionExpressionOrObjectLiteralMethod(node, checkMode) {
59956             var links = getNodeLinks(node);
59957             // Check if function expression is contextually typed and assign parameter types if so.
59958             if (!(links.flags & 1024 /* ContextChecked */)) {
59959                 var contextualSignature = getContextualSignature(node);
59960                 // If a type check is started at a function expression that is an argument of a function call, obtaining the
59961                 // contextual type may recursively get back to here during overload resolution of the call. If so, we will have
59962                 // already assigned contextual types.
59963                 if (!(links.flags & 1024 /* ContextChecked */)) {
59964                     links.flags |= 1024 /* ContextChecked */;
59965                     var signature = ts.firstOrUndefined(getSignaturesOfType(getTypeOfSymbol(getSymbolOfNode(node)), 0 /* Call */));
59966                     if (!signature) {
59967                         return;
59968                     }
59969                     if (isContextSensitive(node)) {
59970                         if (contextualSignature) {
59971                             var inferenceContext = getInferenceContext(node);
59972                             if (checkMode && checkMode & 2 /* Inferential */) {
59973                                 inferFromAnnotatedParameters(signature, contextualSignature, inferenceContext);
59974                             }
59975                             var instantiatedContextualSignature = inferenceContext ?
59976                                 instantiateSignature(contextualSignature, inferenceContext.mapper) : contextualSignature;
59977                             assignContextualParameterTypes(signature, instantiatedContextualSignature);
59978                         }
59979                         else {
59980                             // Force resolution of all parameter types such that the absence of a contextual type is consistently reflected.
59981                             assignNonContextualParameterTypes(signature);
59982                         }
59983                     }
59984                     if (contextualSignature && !getReturnTypeFromAnnotation(node) && !signature.resolvedReturnType) {
59985                         var returnType = getReturnTypeFromBody(node, checkMode);
59986                         if (!signature.resolvedReturnType) {
59987                             signature.resolvedReturnType = returnType;
59988                         }
59989                     }
59990                     checkSignatureDeclaration(node);
59991                 }
59992             }
59993         }
59994         function checkFunctionExpressionOrObjectLiteralMethodDeferred(node) {
59995             ts.Debug.assert(node.kind !== 161 /* MethodDeclaration */ || ts.isObjectLiteralMethod(node));
59996             var functionFlags = ts.getFunctionFlags(node);
59997             var returnType = getReturnTypeFromAnnotation(node);
59998             checkAllCodePathsInNonVoidFunctionReturnOrThrow(node, returnType);
59999             if (node.body) {
60000                 if (!ts.getEffectiveReturnTypeNode(node)) {
60001                     // There are some checks that are only performed in getReturnTypeFromBody, that may produce errors
60002                     // we need. An example is the noImplicitAny errors resulting from widening the return expression
60003                     // of a function. Because checking of function expression bodies is deferred, there was never an
60004                     // appropriate time to do this during the main walk of the file (see the comment at the top of
60005                     // checkFunctionExpressionBodies). So it must be done now.
60006                     getReturnTypeOfSignature(getSignatureFromDeclaration(node));
60007                 }
60008                 if (node.body.kind === 223 /* Block */) {
60009                     checkSourceElement(node.body);
60010                 }
60011                 else {
60012                     // From within an async function you can return either a non-promise value or a promise. Any
60013                     // Promise/A+ compatible implementation will always assimilate any foreign promise, so we
60014                     // should not be checking assignability of a promise to the return type. Instead, we need to
60015                     // check assignability of the awaited type of the expression body against the promised type of
60016                     // its return type annotation.
60017                     var exprType = checkExpression(node.body);
60018                     var returnOrPromisedType = returnType && unwrapReturnType(returnType, functionFlags);
60019                     if (returnOrPromisedType) {
60020                         if ((functionFlags & 3 /* AsyncGenerator */) === 2 /* Async */) { // Async function
60021                             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);
60022                             checkTypeAssignableToAndOptionallyElaborate(awaitedType, returnOrPromisedType, node.body, node.body);
60023                         }
60024                         else { // Normal function
60025                             checkTypeAssignableToAndOptionallyElaborate(exprType, returnOrPromisedType, node.body, node.body);
60026                         }
60027                     }
60028                 }
60029             }
60030         }
60031         function checkArithmeticOperandType(operand, type, diagnostic, isAwaitValid) {
60032             if (isAwaitValid === void 0) { isAwaitValid = false; }
60033             if (!isTypeAssignableTo(type, numberOrBigIntType)) {
60034                 var awaitedType = isAwaitValid && getAwaitedTypeOfPromise(type);
60035                 errorAndMaybeSuggestAwait(operand, !!awaitedType && isTypeAssignableTo(awaitedType, numberOrBigIntType), diagnostic);
60036                 return false;
60037             }
60038             return true;
60039         }
60040         function isReadonlyAssignmentDeclaration(d) {
60041             if (!ts.isCallExpression(d)) {
60042                 return false;
60043             }
60044             if (!ts.isBindableObjectDefinePropertyCall(d)) {
60045                 return false;
60046             }
60047             var objectLitType = checkExpressionCached(d.arguments[2]);
60048             var valueType = getTypeOfPropertyOfType(objectLitType, "value");
60049             if (valueType) {
60050                 var writableProp = getPropertyOfType(objectLitType, "writable");
60051                 var writableType = writableProp && getTypeOfSymbol(writableProp);
60052                 if (!writableType || writableType === falseType || writableType === regularFalseType) {
60053                     return true;
60054                 }
60055                 // We include this definition whereupon we walk back and check the type at the declaration because
60056                 // The usual definition of `Object.defineProperty` will _not_ cause literal types to be preserved in the
60057                 // argument types, should the type be contextualized by the call itself.
60058                 if (writableProp && writableProp.valueDeclaration && ts.isPropertyAssignment(writableProp.valueDeclaration)) {
60059                     var initializer = writableProp.valueDeclaration.initializer;
60060                     var rawOriginalType = checkExpression(initializer);
60061                     if (rawOriginalType === falseType || rawOriginalType === regularFalseType) {
60062                         return true;
60063                     }
60064                 }
60065                 return false;
60066             }
60067             var setProp = getPropertyOfType(objectLitType, "set");
60068             return !setProp;
60069         }
60070         function isReadonlySymbol(symbol) {
60071             // The following symbols are considered read-only:
60072             // Properties with a 'readonly' modifier
60073             // Variables declared with 'const'
60074             // Get accessors without matching set accessors
60075             // Enum members
60076             // Object.defineProperty assignments with writable false or no setter
60077             // Unions and intersections of the above (unions and intersections eagerly set isReadonly on creation)
60078             return !!(ts.getCheckFlags(symbol) & 8 /* Readonly */ ||
60079                 symbol.flags & 4 /* Property */ && ts.getDeclarationModifierFlagsFromSymbol(symbol) & 64 /* Readonly */ ||
60080                 symbol.flags & 3 /* Variable */ && getDeclarationNodeFlagsFromSymbol(symbol) & 2 /* Const */ ||
60081                 symbol.flags & 98304 /* Accessor */ && !(symbol.flags & 65536 /* SetAccessor */) ||
60082                 symbol.flags & 8 /* EnumMember */ ||
60083                 ts.some(symbol.declarations, isReadonlyAssignmentDeclaration));
60084         }
60085         function isAssignmentToReadonlyEntity(expr, symbol, assignmentKind) {
60086             var _a, _b;
60087             if (assignmentKind === 0 /* None */) {
60088                 // no assigment means it doesn't matter whether the entity is readonly
60089                 return false;
60090             }
60091             if (isReadonlySymbol(symbol)) {
60092                 // Allow assignments to readonly properties within constructors of the same class declaration.
60093                 if (symbol.flags & 4 /* Property */ &&
60094                     ts.isAccessExpression(expr) &&
60095                     expr.expression.kind === 104 /* ThisKeyword */) {
60096                     // Look for if this is the constructor for the class that `symbol` is a property of.
60097                     var ctor = ts.getContainingFunction(expr);
60098                     if (!(ctor && ctor.kind === 162 /* Constructor */)) {
60099                         return true;
60100                     }
60101                     if (symbol.valueDeclaration) {
60102                         var isAssignmentDeclaration_1 = ts.isBinaryExpression(symbol.valueDeclaration);
60103                         var isLocalPropertyDeclaration = ctor.parent === symbol.valueDeclaration.parent;
60104                         var isLocalParameterProperty = ctor === symbol.valueDeclaration.parent;
60105                         var isLocalThisPropertyAssignment = isAssignmentDeclaration_1 && ((_a = symbol.parent) === null || _a === void 0 ? void 0 : _a.valueDeclaration) === ctor.parent;
60106                         var isLocalThisPropertyAssignmentConstructorFunction = isAssignmentDeclaration_1 && ((_b = symbol.parent) === null || _b === void 0 ? void 0 : _b.valueDeclaration) === ctor;
60107                         var isWriteableSymbol = isLocalPropertyDeclaration
60108                             || isLocalParameterProperty
60109                             || isLocalThisPropertyAssignment
60110                             || isLocalThisPropertyAssignmentConstructorFunction;
60111                         return !isWriteableSymbol;
60112                     }
60113                 }
60114                 return true;
60115             }
60116             if (ts.isAccessExpression(expr)) {
60117                 // references through namespace import should be readonly
60118                 var node = ts.skipParentheses(expr.expression);
60119                 if (node.kind === 75 /* Identifier */) {
60120                     var symbol_2 = getNodeLinks(node).resolvedSymbol;
60121                     if (symbol_2.flags & 2097152 /* Alias */) {
60122                         var declaration = getDeclarationOfAliasSymbol(symbol_2);
60123                         return !!declaration && declaration.kind === 256 /* NamespaceImport */;
60124                     }
60125                 }
60126             }
60127             return false;
60128         }
60129         function checkReferenceExpression(expr, invalidReferenceMessage, invalidOptionalChainMessage) {
60130             // References are combinations of identifiers, parentheses, and property accesses.
60131             var node = ts.skipOuterExpressions(expr, 6 /* Assertions */ | 1 /* Parentheses */);
60132             if (node.kind !== 75 /* Identifier */ && !ts.isAccessExpression(node)) {
60133                 error(expr, invalidReferenceMessage);
60134                 return false;
60135             }
60136             if (node.flags & 32 /* OptionalChain */) {
60137                 error(expr, invalidOptionalChainMessage);
60138                 return false;
60139             }
60140             return true;
60141         }
60142         function checkDeleteExpression(node) {
60143             checkExpression(node.expression);
60144             var expr = ts.skipParentheses(node.expression);
60145             if (!ts.isAccessExpression(expr)) {
60146                 error(expr, ts.Diagnostics.The_operand_of_a_delete_operator_must_be_a_property_reference);
60147                 return booleanType;
60148             }
60149             // eslint-disable-next-line
60150             if (expr.kind === 194 /* PropertyAccessExpression */ && ts.isPrivateIdentifier(expr.name)) {
60151                 error(expr, ts.Diagnostics.The_operand_of_a_delete_operator_cannot_be_a_private_identifier);
60152             }
60153             var links = getNodeLinks(expr);
60154             var symbol = getExportSymbolOfValueSymbolIfExported(links.resolvedSymbol);
60155             if (symbol && isReadonlySymbol(symbol)) {
60156                 error(expr, ts.Diagnostics.The_operand_of_a_delete_operator_cannot_be_a_read_only_property);
60157             }
60158             return booleanType;
60159         }
60160         function checkTypeOfExpression(node) {
60161             checkExpression(node.expression);
60162             return typeofType;
60163         }
60164         function checkVoidExpression(node) {
60165             checkExpression(node.expression);
60166             return undefinedWideningType;
60167         }
60168         function isTopLevelAwait(node) {
60169             var container = ts.getThisContainer(node, /*includeArrowFunctions*/ true);
60170             return ts.isSourceFile(container);
60171         }
60172         function checkAwaitExpression(node) {
60173             // Grammar checking
60174             if (produceDiagnostics) {
60175                 if (!(node.flags & 32768 /* AwaitContext */)) {
60176                     if (isTopLevelAwait(node)) {
60177                         var sourceFile = ts.getSourceFileOfNode(node);
60178                         if (!hasParseDiagnostics(sourceFile)) {
60179                             var span = void 0;
60180                             if (!ts.isEffectiveExternalModule(sourceFile, compilerOptions)) {
60181                                 if (!span)
60182                                     span = ts.getSpanOfTokenAtPosition(sourceFile, node.pos);
60183                                 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);
60184                                 diagnostics.add(diagnostic);
60185                             }
60186                             if ((moduleKind !== ts.ModuleKind.ESNext && moduleKind !== ts.ModuleKind.System) || languageVersion < 4 /* ES2017 */) {
60187                                 span = ts.getSpanOfTokenAtPosition(sourceFile, node.pos);
60188                                 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);
60189                                 diagnostics.add(diagnostic);
60190                             }
60191                         }
60192                     }
60193                     else {
60194                         // use of 'await' in non-async function
60195                         var sourceFile = ts.getSourceFileOfNode(node);
60196                         if (!hasParseDiagnostics(sourceFile)) {
60197                             var span = ts.getSpanOfTokenAtPosition(sourceFile, node.pos);
60198                             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);
60199                             var func = ts.getContainingFunction(node);
60200                             if (func && func.kind !== 162 /* Constructor */ && (ts.getFunctionFlags(func) & 2 /* Async */) === 0) {
60201                                 var relatedInfo = ts.createDiagnosticForNode(func, ts.Diagnostics.Did_you_mean_to_mark_this_function_as_async);
60202                                 ts.addRelatedInfo(diagnostic, relatedInfo);
60203                             }
60204                             diagnostics.add(diagnostic);
60205                         }
60206                     }
60207                 }
60208                 if (isInParameterInitializerBeforeContainingFunction(node)) {
60209                     error(node, ts.Diagnostics.await_expressions_cannot_be_used_in_a_parameter_initializer);
60210                 }
60211             }
60212             var operandType = checkExpression(node.expression);
60213             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);
60214             if (awaitedType === operandType && awaitedType !== errorType && !(operandType.flags & 3 /* AnyOrUnknown */)) {
60215                 addErrorOrSuggestion(/*isError*/ false, ts.createDiagnosticForNode(node, ts.Diagnostics.await_has_no_effect_on_the_type_of_this_expression));
60216             }
60217             return awaitedType;
60218         }
60219         function checkPrefixUnaryExpression(node) {
60220             var operandType = checkExpression(node.operand);
60221             if (operandType === silentNeverType) {
60222                 return silentNeverType;
60223             }
60224             switch (node.operand.kind) {
60225                 case 8 /* NumericLiteral */:
60226                     switch (node.operator) {
60227                         case 40 /* MinusToken */:
60228                             return getFreshTypeOfLiteralType(getLiteralType(-node.operand.text));
60229                         case 39 /* PlusToken */:
60230                             return getFreshTypeOfLiteralType(getLiteralType(+node.operand.text));
60231                     }
60232                     break;
60233                 case 9 /* BigIntLiteral */:
60234                     if (node.operator === 40 /* MinusToken */) {
60235                         return getFreshTypeOfLiteralType(getLiteralType({
60236                             negative: true,
60237                             base10Value: ts.parsePseudoBigInt(node.operand.text)
60238                         }));
60239                     }
60240             }
60241             switch (node.operator) {
60242                 case 39 /* PlusToken */:
60243                 case 40 /* MinusToken */:
60244                 case 54 /* TildeToken */:
60245                     checkNonNullType(operandType, node.operand);
60246                     if (maybeTypeOfKind(operandType, 12288 /* ESSymbolLike */)) {
60247                         error(node.operand, ts.Diagnostics.The_0_operator_cannot_be_applied_to_type_symbol, ts.tokenToString(node.operator));
60248                     }
60249                     if (node.operator === 39 /* PlusToken */) {
60250                         if (maybeTypeOfKind(operandType, 2112 /* BigIntLike */)) {
60251                             error(node.operand, ts.Diagnostics.Operator_0_cannot_be_applied_to_type_1, ts.tokenToString(node.operator), typeToString(getBaseTypeOfLiteralType(operandType)));
60252                         }
60253                         return numberType;
60254                     }
60255                     return getUnaryResultType(operandType);
60256                 case 53 /* ExclamationToken */:
60257                     checkTruthinessExpression(node.operand);
60258                     var facts = getTypeFacts(operandType) & (4194304 /* Truthy */ | 8388608 /* Falsy */);
60259                     return facts === 4194304 /* Truthy */ ? falseType :
60260                         facts === 8388608 /* Falsy */ ? trueType :
60261                             booleanType;
60262                 case 45 /* PlusPlusToken */:
60263                 case 46 /* MinusMinusToken */:
60264                     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);
60265                     if (ok) {
60266                         // run check only if former checks succeeded to avoid reporting cascading errors
60267                         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);
60268                     }
60269                     return getUnaryResultType(operandType);
60270             }
60271             return errorType;
60272         }
60273         function checkPostfixUnaryExpression(node) {
60274             var operandType = checkExpression(node.operand);
60275             if (operandType === silentNeverType) {
60276                 return silentNeverType;
60277             }
60278             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);
60279             if (ok) {
60280                 // run check only if former checks succeeded to avoid reporting cascading errors
60281                 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);
60282             }
60283             return getUnaryResultType(operandType);
60284         }
60285         function getUnaryResultType(operandType) {
60286             if (maybeTypeOfKind(operandType, 2112 /* BigIntLike */)) {
60287                 return isTypeAssignableToKind(operandType, 3 /* AnyOrUnknown */) || maybeTypeOfKind(operandType, 296 /* NumberLike */)
60288                     ? numberOrBigIntType
60289                     : bigintType;
60290             }
60291             // If it's not a bigint type, implicit coercion will result in a number
60292             return numberType;
60293         }
60294         // Return true if type might be of the given kind. A union or intersection type might be of a given
60295         // kind if at least one constituent type is of the given kind.
60296         function maybeTypeOfKind(type, kind) {
60297             if (type.flags & kind) {
60298                 return true;
60299             }
60300             if (type.flags & 3145728 /* UnionOrIntersection */) {
60301                 var types = type.types;
60302                 for (var _i = 0, types_19 = types; _i < types_19.length; _i++) {
60303                     var t = types_19[_i];
60304                     if (maybeTypeOfKind(t, kind)) {
60305                         return true;
60306                     }
60307                 }
60308             }
60309             return false;
60310         }
60311         function isTypeAssignableToKind(source, kind, strict) {
60312             if (source.flags & kind) {
60313                 return true;
60314             }
60315             if (strict && source.flags & (3 /* AnyOrUnknown */ | 16384 /* Void */ | 32768 /* Undefined */ | 65536 /* Null */)) {
60316                 return false;
60317             }
60318             return !!(kind & 296 /* NumberLike */) && isTypeAssignableTo(source, numberType) ||
60319                 !!(kind & 2112 /* BigIntLike */) && isTypeAssignableTo(source, bigintType) ||
60320                 !!(kind & 132 /* StringLike */) && isTypeAssignableTo(source, stringType) ||
60321                 !!(kind & 528 /* BooleanLike */) && isTypeAssignableTo(source, booleanType) ||
60322                 !!(kind & 16384 /* Void */) && isTypeAssignableTo(source, voidType) ||
60323                 !!(kind & 131072 /* Never */) && isTypeAssignableTo(source, neverType) ||
60324                 !!(kind & 65536 /* Null */) && isTypeAssignableTo(source, nullType) ||
60325                 !!(kind & 32768 /* Undefined */) && isTypeAssignableTo(source, undefinedType) ||
60326                 !!(kind & 4096 /* ESSymbol */) && isTypeAssignableTo(source, esSymbolType) ||
60327                 !!(kind & 67108864 /* NonPrimitive */) && isTypeAssignableTo(source, nonPrimitiveType);
60328         }
60329         function allTypesAssignableToKind(source, kind, strict) {
60330             return source.flags & 1048576 /* Union */ ?
60331                 ts.every(source.types, function (subType) { return allTypesAssignableToKind(subType, kind, strict); }) :
60332                 isTypeAssignableToKind(source, kind, strict);
60333         }
60334         function isConstEnumObjectType(type) {
60335             return !!(ts.getObjectFlags(type) & 16 /* Anonymous */) && !!type.symbol && isConstEnumSymbol(type.symbol);
60336         }
60337         function isConstEnumSymbol(symbol) {
60338             return (symbol.flags & 128 /* ConstEnum */) !== 0;
60339         }
60340         function checkInstanceOfExpression(left, right, leftType, rightType) {
60341             if (leftType === silentNeverType || rightType === silentNeverType) {
60342                 return silentNeverType;
60343             }
60344             // TypeScript 1.0 spec (April 2014): 4.15.4
60345             // The instanceof operator requires the left operand to be of type Any, an object type, or a type parameter type,
60346             // and the right operand to be of type Any, a subtype of the 'Function' interface type, or have a call or construct signature.
60347             // The result is always of the Boolean primitive type.
60348             // NOTE: do not raise error if leftType is unknown as related error was already reported
60349             if (!isTypeAny(leftType) &&
60350                 allTypesAssignableToKind(leftType, 131068 /* Primitive */)) {
60351                 error(left, ts.Diagnostics.The_left_hand_side_of_an_instanceof_expression_must_be_of_type_any_an_object_type_or_a_type_parameter);
60352             }
60353             // NOTE: do not raise error if right is unknown as related error was already reported
60354             if (!(isTypeAny(rightType) || typeHasCallOrConstructSignatures(rightType) || isTypeSubtypeOf(rightType, globalFunctionType))) {
60355                 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);
60356             }
60357             return booleanType;
60358         }
60359         function checkInExpression(left, right, leftType, rightType) {
60360             if (leftType === silentNeverType || rightType === silentNeverType) {
60361                 return silentNeverType;
60362             }
60363             leftType = checkNonNullType(leftType, left);
60364             rightType = checkNonNullType(rightType, right);
60365             // TypeScript 1.0 spec (April 2014): 4.15.5
60366             // The in operator requires the left operand to be of type Any, the String primitive type, or the Number primitive type,
60367             // and the right operand to be of type Any, an object type, or a type parameter type.
60368             // The result is always of the Boolean primitive type.
60369             if (!(isTypeComparableTo(leftType, stringType) || isTypeAssignableToKind(leftType, 296 /* NumberLike */ | 12288 /* ESSymbolLike */))) {
60370                 error(left, ts.Diagnostics.The_left_hand_side_of_an_in_expression_must_be_of_type_any_string_number_or_symbol);
60371             }
60372             if (!allTypesAssignableToKind(rightType, 67108864 /* NonPrimitive */ | 58982400 /* InstantiableNonPrimitive */)) {
60373                 error(right, ts.Diagnostics.The_right_hand_side_of_an_in_expression_must_be_of_type_any_an_object_type_or_a_type_parameter);
60374             }
60375             return booleanType;
60376         }
60377         function checkObjectLiteralAssignment(node, sourceType, rightIsThis) {
60378             var properties = node.properties;
60379             if (strictNullChecks && properties.length === 0) {
60380                 return checkNonNullType(sourceType, node);
60381             }
60382             for (var i = 0; i < properties.length; i++) {
60383                 checkObjectLiteralDestructuringPropertyAssignment(node, sourceType, i, properties, rightIsThis);
60384             }
60385             return sourceType;
60386         }
60387         /** Note: If property cannot be a SpreadAssignment, then allProperties does not need to be provided */
60388         function checkObjectLiteralDestructuringPropertyAssignment(node, objectLiteralType, propertyIndex, allProperties, rightIsThis) {
60389             if (rightIsThis === void 0) { rightIsThis = false; }
60390             var properties = node.properties;
60391             var property = properties[propertyIndex];
60392             if (property.kind === 281 /* PropertyAssignment */ || property.kind === 282 /* ShorthandPropertyAssignment */) {
60393                 var name = property.name;
60394                 var exprType = getLiteralTypeFromPropertyName(name);
60395                 if (isTypeUsableAsPropertyName(exprType)) {
60396                     var text = getPropertyNameFromType(exprType);
60397                     var prop = getPropertyOfType(objectLiteralType, text);
60398                     if (prop) {
60399                         markPropertyAsReferenced(prop, property, rightIsThis);
60400                         checkPropertyAccessibility(property, /*isSuper*/ false, objectLiteralType, prop);
60401                     }
60402                 }
60403                 var elementType = getIndexedAccessType(objectLiteralType, exprType, name);
60404                 var type = getFlowTypeOfDestructuring(property, elementType);
60405                 return checkDestructuringAssignment(property.kind === 282 /* ShorthandPropertyAssignment */ ? property : property.initializer, type);
60406             }
60407             else if (property.kind === 283 /* SpreadAssignment */) {
60408                 if (propertyIndex < properties.length - 1) {
60409                     error(property, ts.Diagnostics.A_rest_element_must_be_last_in_a_destructuring_pattern);
60410                 }
60411                 else {
60412                     if (languageVersion < 99 /* ESNext */) {
60413                         checkExternalEmitHelpers(property, 4 /* Rest */);
60414                     }
60415                     var nonRestNames = [];
60416                     if (allProperties) {
60417                         for (var _i = 0, allProperties_1 = allProperties; _i < allProperties_1.length; _i++) {
60418                             var otherProperty = allProperties_1[_i];
60419                             if (!ts.isSpreadAssignment(otherProperty)) {
60420                                 nonRestNames.push(otherProperty.name);
60421                             }
60422                         }
60423                     }
60424                     var type = getRestType(objectLiteralType, nonRestNames, objectLiteralType.symbol);
60425                     checkGrammarForDisallowedTrailingComma(allProperties, ts.Diagnostics.A_rest_parameter_or_binding_pattern_may_not_have_a_trailing_comma);
60426                     return checkDestructuringAssignment(property.expression, type);
60427                 }
60428             }
60429             else {
60430                 error(property, ts.Diagnostics.Property_assignment_expected);
60431             }
60432         }
60433         function checkArrayLiteralAssignment(node, sourceType, checkMode) {
60434             var elements = node.elements;
60435             if (languageVersion < 2 /* ES2015 */ && compilerOptions.downlevelIteration) {
60436                 checkExternalEmitHelpers(node, 512 /* Read */);
60437             }
60438             // This elementType will be used if the specific property corresponding to this index is not
60439             // present (aka the tuple element property). This call also checks that the parentType is in
60440             // fact an iterable or array (depending on target language).
60441             var elementType = checkIteratedTypeOrElementType(65 /* Destructuring */, sourceType, undefinedType, node) || errorType;
60442             for (var i = 0; i < elements.length; i++) {
60443                 checkArrayLiteralDestructuringElementAssignment(node, sourceType, i, elementType, checkMode);
60444             }
60445             return sourceType;
60446         }
60447         function checkArrayLiteralDestructuringElementAssignment(node, sourceType, elementIndex, elementType, checkMode) {
60448             var elements = node.elements;
60449             var element = elements[elementIndex];
60450             if (element.kind !== 215 /* OmittedExpression */) {
60451                 if (element.kind !== 213 /* SpreadElement */) {
60452                     var indexType = getLiteralType(elementIndex);
60453                     if (isArrayLikeType(sourceType)) {
60454                         // We create a synthetic expression so that getIndexedAccessType doesn't get confused
60455                         // when the element is a SyntaxKind.ElementAccessExpression.
60456                         var accessFlags = hasDefaultValue(element) ? 8 /* NoTupleBoundsCheck */ : 0;
60457                         var elementType_2 = getIndexedAccessTypeOrUndefined(sourceType, indexType, createSyntheticExpression(element, indexType), accessFlags) || errorType;
60458                         var assignedType = hasDefaultValue(element) ? getTypeWithFacts(elementType_2, 524288 /* NEUndefined */) : elementType_2;
60459                         var type = getFlowTypeOfDestructuring(element, assignedType);
60460                         return checkDestructuringAssignment(element, type, checkMode);
60461                     }
60462                     return checkDestructuringAssignment(element, elementType, checkMode);
60463                 }
60464                 if (elementIndex < elements.length - 1) {
60465                     error(element, ts.Diagnostics.A_rest_element_must_be_last_in_a_destructuring_pattern);
60466                 }
60467                 else {
60468                     var restExpression = element.expression;
60469                     if (restExpression.kind === 209 /* BinaryExpression */ && restExpression.operatorToken.kind === 62 /* EqualsToken */) {
60470                         error(restExpression.operatorToken, ts.Diagnostics.A_rest_element_cannot_have_an_initializer);
60471                     }
60472                     else {
60473                         checkGrammarForDisallowedTrailingComma(node.elements, ts.Diagnostics.A_rest_parameter_or_binding_pattern_may_not_have_a_trailing_comma);
60474                         var type = everyType(sourceType, isTupleType) ?
60475                             mapType(sourceType, function (t) { return sliceTupleType(t, elementIndex); }) :
60476                             createArrayType(elementType);
60477                         return checkDestructuringAssignment(restExpression, type, checkMode);
60478                     }
60479                 }
60480             }
60481             return undefined;
60482         }
60483         function checkDestructuringAssignment(exprOrAssignment, sourceType, checkMode, rightIsThis) {
60484             var target;
60485             if (exprOrAssignment.kind === 282 /* ShorthandPropertyAssignment */) {
60486                 var prop = exprOrAssignment;
60487                 if (prop.objectAssignmentInitializer) {
60488                     // In strict null checking mode, if a default value of a non-undefined type is specified, remove
60489                     // undefined from the final type.
60490                     if (strictNullChecks &&
60491                         !(getFalsyFlags(checkExpression(prop.objectAssignmentInitializer)) & 32768 /* Undefined */)) {
60492                         sourceType = getTypeWithFacts(sourceType, 524288 /* NEUndefined */);
60493                     }
60494                     checkBinaryLikeExpression(prop.name, prop.equalsToken, prop.objectAssignmentInitializer, checkMode);
60495                 }
60496                 target = exprOrAssignment.name;
60497             }
60498             else {
60499                 target = exprOrAssignment;
60500             }
60501             if (target.kind === 209 /* BinaryExpression */ && target.operatorToken.kind === 62 /* EqualsToken */) {
60502                 checkBinaryExpression(target, checkMode);
60503                 target = target.left;
60504             }
60505             if (target.kind === 193 /* ObjectLiteralExpression */) {
60506                 return checkObjectLiteralAssignment(target, sourceType, rightIsThis);
60507             }
60508             if (target.kind === 192 /* ArrayLiteralExpression */) {
60509                 return checkArrayLiteralAssignment(target, sourceType, checkMode);
60510             }
60511             return checkReferenceAssignment(target, sourceType, checkMode);
60512         }
60513         function checkReferenceAssignment(target, sourceType, checkMode) {
60514             var targetType = checkExpression(target, checkMode);
60515             var error = target.parent.kind === 283 /* SpreadAssignment */ ?
60516                 ts.Diagnostics.The_target_of_an_object_rest_assignment_must_be_a_variable_or_a_property_access :
60517                 ts.Diagnostics.The_left_hand_side_of_an_assignment_expression_must_be_a_variable_or_a_property_access;
60518             var optionalError = target.parent.kind === 283 /* SpreadAssignment */ ?
60519                 ts.Diagnostics.The_target_of_an_object_rest_assignment_may_not_be_an_optional_property_access :
60520                 ts.Diagnostics.The_left_hand_side_of_an_assignment_expression_may_not_be_an_optional_property_access;
60521             if (checkReferenceExpression(target, error, optionalError)) {
60522                 checkTypeAssignableToAndOptionallyElaborate(sourceType, targetType, target, target);
60523             }
60524             if (ts.isPrivateIdentifierPropertyAccessExpression(target)) {
60525                 checkExternalEmitHelpers(target.parent, 524288 /* ClassPrivateFieldSet */);
60526             }
60527             return sourceType;
60528         }
60529         /**
60530          * This is a *shallow* check: An expression is side-effect-free if the
60531          * evaluation of the expression *itself* cannot produce side effects.
60532          * For example, x++ / 3 is side-effect free because the / operator
60533          * does not have side effects.
60534          * The intent is to "smell test" an expression for correctness in positions where
60535          * its value is discarded (e.g. the left side of the comma operator).
60536          */
60537         function isSideEffectFree(node) {
60538             node = ts.skipParentheses(node);
60539             switch (node.kind) {
60540                 case 75 /* Identifier */:
60541                 case 10 /* StringLiteral */:
60542                 case 13 /* RegularExpressionLiteral */:
60543                 case 198 /* TaggedTemplateExpression */:
60544                 case 211 /* TemplateExpression */:
60545                 case 14 /* NoSubstitutionTemplateLiteral */:
60546                 case 8 /* NumericLiteral */:
60547                 case 9 /* BigIntLiteral */:
60548                 case 106 /* TrueKeyword */:
60549                 case 91 /* FalseKeyword */:
60550                 case 100 /* NullKeyword */:
60551                 case 146 /* UndefinedKeyword */:
60552                 case 201 /* FunctionExpression */:
60553                 case 214 /* ClassExpression */:
60554                 case 202 /* ArrowFunction */:
60555                 case 192 /* ArrayLiteralExpression */:
60556                 case 193 /* ObjectLiteralExpression */:
60557                 case 204 /* TypeOfExpression */:
60558                 case 218 /* NonNullExpression */:
60559                 case 267 /* JsxSelfClosingElement */:
60560                 case 266 /* JsxElement */:
60561                     return true;
60562                 case 210 /* ConditionalExpression */:
60563                     return isSideEffectFree(node.whenTrue) &&
60564                         isSideEffectFree(node.whenFalse);
60565                 case 209 /* BinaryExpression */:
60566                     if (ts.isAssignmentOperator(node.operatorToken.kind)) {
60567                         return false;
60568                     }
60569                     return isSideEffectFree(node.left) &&
60570                         isSideEffectFree(node.right);
60571                 case 207 /* PrefixUnaryExpression */:
60572                 case 208 /* PostfixUnaryExpression */:
60573                     // Unary operators ~, !, +, and - have no side effects.
60574                     // The rest do.
60575                     switch (node.operator) {
60576                         case 53 /* ExclamationToken */:
60577                         case 39 /* PlusToken */:
60578                         case 40 /* MinusToken */:
60579                         case 54 /* TildeToken */:
60580                             return true;
60581                     }
60582                     return false;
60583                 // Some forms listed here for clarity
60584                 case 205 /* VoidExpression */: // Explicit opt-out
60585                 case 199 /* TypeAssertionExpression */: // Not SEF, but can produce useful type warnings
60586                 case 217 /* AsExpression */: // Not SEF, but can produce useful type warnings
60587                 default:
60588                     return false;
60589             }
60590         }
60591         function isTypeEqualityComparableTo(source, target) {
60592             return (target.flags & 98304 /* Nullable */) !== 0 || isTypeComparableTo(source, target);
60593         }
60594         var CheckBinaryExpressionState;
60595         (function (CheckBinaryExpressionState) {
60596             CheckBinaryExpressionState[CheckBinaryExpressionState["MaybeCheckLeft"] = 0] = "MaybeCheckLeft";
60597             CheckBinaryExpressionState[CheckBinaryExpressionState["CheckRight"] = 1] = "CheckRight";
60598             CheckBinaryExpressionState[CheckBinaryExpressionState["FinishCheck"] = 2] = "FinishCheck";
60599         })(CheckBinaryExpressionState || (CheckBinaryExpressionState = {}));
60600         function checkBinaryExpression(node, checkMode) {
60601             var workStacks = {
60602                 expr: [node],
60603                 state: [0 /* MaybeCheckLeft */],
60604                 leftType: [undefined]
60605             };
60606             var stackIndex = 0;
60607             var lastResult;
60608             while (stackIndex >= 0) {
60609                 node = workStacks.expr[stackIndex];
60610                 switch (workStacks.state[stackIndex]) {
60611                     case 0 /* MaybeCheckLeft */: {
60612                         if (ts.isInJSFile(node) && ts.getAssignedExpandoInitializer(node)) {
60613                             finishInvocation(checkExpression(node.right, checkMode));
60614                             break;
60615                         }
60616                         checkGrammarNullishCoalesceWithLogicalExpression(node);
60617                         var operator = node.operatorToken.kind;
60618                         if (operator === 62 /* EqualsToken */ && (node.left.kind === 193 /* ObjectLiteralExpression */ || node.left.kind === 192 /* ArrayLiteralExpression */)) {
60619                             finishInvocation(checkDestructuringAssignment(node.left, checkExpression(node.right, checkMode), checkMode, node.right.kind === 104 /* ThisKeyword */));
60620                             break;
60621                         }
60622                         advanceState(1 /* CheckRight */);
60623                         maybeCheckExpression(node.left);
60624                         break;
60625                     }
60626                     case 1 /* CheckRight */: {
60627                         var leftType = lastResult;
60628                         workStacks.leftType[stackIndex] = leftType;
60629                         var operator = node.operatorToken.kind;
60630                         if (operator === 55 /* AmpersandAmpersandToken */ || operator === 56 /* BarBarToken */ || operator === 60 /* QuestionQuestionToken */) {
60631                             checkTruthinessOfType(leftType, node.left);
60632                         }
60633                         advanceState(2 /* FinishCheck */);
60634                         maybeCheckExpression(node.right);
60635                         break;
60636                     }
60637                     case 2 /* FinishCheck */: {
60638                         var leftType = workStacks.leftType[stackIndex];
60639                         var rightType = lastResult;
60640                         finishInvocation(checkBinaryLikeExpressionWorker(node.left, node.operatorToken, node.right, leftType, rightType, node));
60641                         break;
60642                     }
60643                     default: return ts.Debug.fail("Invalid state " + workStacks.state[stackIndex] + " for checkBinaryExpression");
60644                 }
60645             }
60646             return lastResult;
60647             function finishInvocation(result) {
60648                 lastResult = result;
60649                 stackIndex--;
60650             }
60651             /**
60652              * Note that `advanceState` sets the _current_ head state, and that `maybeCheckExpression` potentially pushes on a new
60653              * head state; so `advanceState` must be called before any `maybeCheckExpression` during a state's execution.
60654              */
60655             function advanceState(nextState) {
60656                 workStacks.state[stackIndex] = nextState;
60657             }
60658             function maybeCheckExpression(node) {
60659                 if (ts.isBinaryExpression(node)) {
60660                     stackIndex++;
60661                     workStacks.expr[stackIndex] = node;
60662                     workStacks.state[stackIndex] = 0 /* MaybeCheckLeft */;
60663                     workStacks.leftType[stackIndex] = undefined;
60664                 }
60665                 else {
60666                     lastResult = checkExpression(node, checkMode);
60667                 }
60668             }
60669         }
60670         function checkGrammarNullishCoalesceWithLogicalExpression(node) {
60671             var left = node.left, operatorToken = node.operatorToken, right = node.right;
60672             if (operatorToken.kind === 60 /* QuestionQuestionToken */) {
60673                 if (ts.isBinaryExpression(left) && (left.operatorToken.kind === 56 /* BarBarToken */ || left.operatorToken.kind === 55 /* AmpersandAmpersandToken */)) {
60674                     grammarErrorOnNode(left, ts.Diagnostics._0_and_1_operations_cannot_be_mixed_without_parentheses, ts.tokenToString(left.operatorToken.kind), ts.tokenToString(operatorToken.kind));
60675                 }
60676                 if (ts.isBinaryExpression(right) && (right.operatorToken.kind === 56 /* BarBarToken */ || right.operatorToken.kind === 55 /* AmpersandAmpersandToken */)) {
60677                     grammarErrorOnNode(right, ts.Diagnostics._0_and_1_operations_cannot_be_mixed_without_parentheses, ts.tokenToString(right.operatorToken.kind), ts.tokenToString(operatorToken.kind));
60678                 }
60679             }
60680         }
60681         // Note that this and `checkBinaryExpression` above should behave mostly the same, except this elides some
60682         // expression-wide checks and does not use a work stack to fold nested binary expressions into the same callstack frame
60683         function checkBinaryLikeExpression(left, operatorToken, right, checkMode, errorNode) {
60684             var operator = operatorToken.kind;
60685             if (operator === 62 /* EqualsToken */ && (left.kind === 193 /* ObjectLiteralExpression */ || left.kind === 192 /* ArrayLiteralExpression */)) {
60686                 return checkDestructuringAssignment(left, checkExpression(right, checkMode), checkMode, right.kind === 104 /* ThisKeyword */);
60687             }
60688             var leftType;
60689             if (operator === 55 /* AmpersandAmpersandToken */ || operator === 56 /* BarBarToken */ || operator === 60 /* QuestionQuestionToken */) {
60690                 leftType = checkTruthinessExpression(left, checkMode);
60691             }
60692             else {
60693                 leftType = checkExpression(left, checkMode);
60694             }
60695             var rightType = checkExpression(right, checkMode);
60696             return checkBinaryLikeExpressionWorker(left, operatorToken, right, leftType, rightType, errorNode);
60697         }
60698         function checkBinaryLikeExpressionWorker(left, operatorToken, right, leftType, rightType, errorNode) {
60699             var operator = operatorToken.kind;
60700             switch (operator) {
60701                 case 41 /* AsteriskToken */:
60702                 case 42 /* AsteriskAsteriskToken */:
60703                 case 65 /* AsteriskEqualsToken */:
60704                 case 66 /* AsteriskAsteriskEqualsToken */:
60705                 case 43 /* SlashToken */:
60706                 case 67 /* SlashEqualsToken */:
60707                 case 44 /* PercentToken */:
60708                 case 68 /* PercentEqualsToken */:
60709                 case 40 /* MinusToken */:
60710                 case 64 /* MinusEqualsToken */:
60711                 case 47 /* LessThanLessThanToken */:
60712                 case 69 /* LessThanLessThanEqualsToken */:
60713                 case 48 /* GreaterThanGreaterThanToken */:
60714                 case 70 /* GreaterThanGreaterThanEqualsToken */:
60715                 case 49 /* GreaterThanGreaterThanGreaterThanToken */:
60716                 case 71 /* GreaterThanGreaterThanGreaterThanEqualsToken */:
60717                 case 51 /* BarToken */:
60718                 case 73 /* BarEqualsToken */:
60719                 case 52 /* CaretToken */:
60720                 case 74 /* CaretEqualsToken */:
60721                 case 50 /* AmpersandToken */:
60722                 case 72 /* AmpersandEqualsToken */:
60723                     if (leftType === silentNeverType || rightType === silentNeverType) {
60724                         return silentNeverType;
60725                     }
60726                     leftType = checkNonNullType(leftType, left);
60727                     rightType = checkNonNullType(rightType, right);
60728                     var suggestedOperator = void 0;
60729                     // if a user tries to apply a bitwise operator to 2 boolean operands
60730                     // try and return them a helpful suggestion
60731                     if ((leftType.flags & 528 /* BooleanLike */) &&
60732                         (rightType.flags & 528 /* BooleanLike */) &&
60733                         (suggestedOperator = getSuggestedBooleanOperator(operatorToken.kind)) !== undefined) {
60734                         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));
60735                         return numberType;
60736                     }
60737                     else {
60738                         // otherwise just check each operand separately and report errors as normal
60739                         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);
60740                         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);
60741                         var resultType_1;
60742                         // If both are any or unknown, allow operation; assume it will resolve to number
60743                         if ((isTypeAssignableToKind(leftType, 3 /* AnyOrUnknown */) && isTypeAssignableToKind(rightType, 3 /* AnyOrUnknown */)) ||
60744                             // Or, if neither could be bigint, implicit coercion results in a number result
60745                             !(maybeTypeOfKind(leftType, 2112 /* BigIntLike */) || maybeTypeOfKind(rightType, 2112 /* BigIntLike */))) {
60746                             resultType_1 = numberType;
60747                         }
60748                         // At least one is assignable to bigint, so check that both are
60749                         else if (bothAreBigIntLike(leftType, rightType)) {
60750                             switch (operator) {
60751                                 case 49 /* GreaterThanGreaterThanGreaterThanToken */:
60752                                 case 71 /* GreaterThanGreaterThanGreaterThanEqualsToken */:
60753                                     reportOperatorError();
60754                             }
60755                             resultType_1 = bigintType;
60756                         }
60757                         // Exactly one of leftType/rightType is assignable to bigint
60758                         else {
60759                             reportOperatorError(bothAreBigIntLike);
60760                             resultType_1 = errorType;
60761                         }
60762                         if (leftOk && rightOk) {
60763                             checkAssignmentOperator(resultType_1);
60764                         }
60765                         return resultType_1;
60766                     }
60767                 case 39 /* PlusToken */:
60768                 case 63 /* PlusEqualsToken */:
60769                     if (leftType === silentNeverType || rightType === silentNeverType) {
60770                         return silentNeverType;
60771                     }
60772                     if (!isTypeAssignableToKind(leftType, 132 /* StringLike */) && !isTypeAssignableToKind(rightType, 132 /* StringLike */)) {
60773                         leftType = checkNonNullType(leftType, left);
60774                         rightType = checkNonNullType(rightType, right);
60775                     }
60776                     var resultType = void 0;
60777                     if (isTypeAssignableToKind(leftType, 296 /* NumberLike */, /*strict*/ true) && isTypeAssignableToKind(rightType, 296 /* NumberLike */, /*strict*/ true)) {
60778                         // Operands of an enum type are treated as having the primitive type Number.
60779                         // If both operands are of the Number primitive type, the result is of the Number primitive type.
60780                         resultType = numberType;
60781                     }
60782                     else if (isTypeAssignableToKind(leftType, 2112 /* BigIntLike */, /*strict*/ true) && isTypeAssignableToKind(rightType, 2112 /* BigIntLike */, /*strict*/ true)) {
60783                         // If both operands are of the BigInt primitive type, the result is of the BigInt primitive type.
60784                         resultType = bigintType;
60785                     }
60786                     else if (isTypeAssignableToKind(leftType, 132 /* StringLike */, /*strict*/ true) || isTypeAssignableToKind(rightType, 132 /* StringLike */, /*strict*/ true)) {
60787                         // If one or both operands are of the String primitive type, the result is of the String primitive type.
60788                         resultType = stringType;
60789                     }
60790                     else if (isTypeAny(leftType) || isTypeAny(rightType)) {
60791                         // Otherwise, the result is of type Any.
60792                         // NOTE: unknown type here denotes error type. Old compiler treated this case as any type so do we.
60793                         resultType = leftType === errorType || rightType === errorType ? errorType : anyType;
60794                     }
60795                     // Symbols are not allowed at all in arithmetic expressions
60796                     if (resultType && !checkForDisallowedESSymbolOperand(operator)) {
60797                         return resultType;
60798                     }
60799                     if (!resultType) {
60800                         // Types that have a reasonably good chance of being a valid operand type.
60801                         // If both types have an awaited type of one of these, we'll assume the user
60802                         // might be missing an await without doing an exhaustive check that inserting
60803                         // await(s) will actually be a completely valid binary expression.
60804                         var closeEnoughKind_1 = 296 /* NumberLike */ | 2112 /* BigIntLike */ | 132 /* StringLike */ | 3 /* AnyOrUnknown */;
60805                         reportOperatorError(function (left, right) {
60806                             return isTypeAssignableToKind(left, closeEnoughKind_1) &&
60807                                 isTypeAssignableToKind(right, closeEnoughKind_1);
60808                         });
60809                         return anyType;
60810                     }
60811                     if (operator === 63 /* PlusEqualsToken */) {
60812                         checkAssignmentOperator(resultType);
60813                     }
60814                     return resultType;
60815                 case 29 /* LessThanToken */:
60816                 case 31 /* GreaterThanToken */:
60817                 case 32 /* LessThanEqualsToken */:
60818                 case 33 /* GreaterThanEqualsToken */:
60819                     if (checkForDisallowedESSymbolOperand(operator)) {
60820                         leftType = getBaseTypeOfLiteralType(checkNonNullType(leftType, left));
60821                         rightType = getBaseTypeOfLiteralType(checkNonNullType(rightType, right));
60822                         reportOperatorErrorUnless(function (left, right) {
60823                             return isTypeComparableTo(left, right) || isTypeComparableTo(right, left) || (isTypeAssignableTo(left, numberOrBigIntType) && isTypeAssignableTo(right, numberOrBigIntType));
60824                         });
60825                     }
60826                     return booleanType;
60827                 case 34 /* EqualsEqualsToken */:
60828                 case 35 /* ExclamationEqualsToken */:
60829                 case 36 /* EqualsEqualsEqualsToken */:
60830                 case 37 /* ExclamationEqualsEqualsToken */:
60831                     reportOperatorErrorUnless(function (left, right) { return isTypeEqualityComparableTo(left, right) || isTypeEqualityComparableTo(right, left); });
60832                     return booleanType;
60833                 case 98 /* InstanceOfKeyword */:
60834                     return checkInstanceOfExpression(left, right, leftType, rightType);
60835                 case 97 /* InKeyword */:
60836                     return checkInExpression(left, right, leftType, rightType);
60837                 case 55 /* AmpersandAmpersandToken */:
60838                     return getTypeFacts(leftType) & 4194304 /* Truthy */ ?
60839                         getUnionType([extractDefinitelyFalsyTypes(strictNullChecks ? leftType : getBaseTypeOfLiteralType(rightType)), rightType]) :
60840                         leftType;
60841                 case 56 /* BarBarToken */:
60842                     return getTypeFacts(leftType) & 8388608 /* Falsy */ ?
60843                         getUnionType([removeDefinitelyFalsyTypes(leftType), rightType], 2 /* Subtype */) :
60844                         leftType;
60845                 case 60 /* QuestionQuestionToken */:
60846                     return getTypeFacts(leftType) & 262144 /* EQUndefinedOrNull */ ?
60847                         getUnionType([getNonNullableType(leftType), rightType], 2 /* Subtype */) :
60848                         leftType;
60849                 case 62 /* EqualsToken */:
60850                     var declKind = ts.isBinaryExpression(left.parent) ? ts.getAssignmentDeclarationKind(left.parent) : 0 /* None */;
60851                     checkAssignmentDeclaration(declKind, rightType);
60852                     if (isAssignmentDeclaration(declKind)) {
60853                         if (!(rightType.flags & 524288 /* Object */) ||
60854                             declKind !== 2 /* ModuleExports */ &&
60855                                 declKind !== 6 /* Prototype */ &&
60856                                 !isEmptyObjectType(rightType) &&
60857                                 !isFunctionObjectType(rightType) &&
60858                                 !(ts.getObjectFlags(rightType) & 1 /* Class */)) {
60859                             // don't check assignability of module.exports=, C.prototype=, or expando types because they will necessarily be incomplete
60860                             checkAssignmentOperator(rightType);
60861                         }
60862                         return leftType;
60863                     }
60864                     else {
60865                         checkAssignmentOperator(rightType);
60866                         return getRegularTypeOfObjectLiteral(rightType);
60867                     }
60868                 case 27 /* CommaToken */:
60869                     if (!compilerOptions.allowUnreachableCode && isSideEffectFree(left) && !isEvalNode(right)) {
60870                         error(left, ts.Diagnostics.Left_side_of_comma_operator_is_unused_and_has_no_side_effects);
60871                     }
60872                     return rightType;
60873                 default:
60874                     return ts.Debug.fail();
60875             }
60876             function bothAreBigIntLike(left, right) {
60877                 return isTypeAssignableToKind(left, 2112 /* BigIntLike */) && isTypeAssignableToKind(right, 2112 /* BigIntLike */);
60878             }
60879             function checkAssignmentDeclaration(kind, rightType) {
60880                 if (kind === 2 /* ModuleExports */) {
60881                     for (var _i = 0, _a = getPropertiesOfObjectType(rightType); _i < _a.length; _i++) {
60882                         var prop = _a[_i];
60883                         var propType = getTypeOfSymbol(prop);
60884                         if (propType.symbol && propType.symbol.flags & 32 /* Class */) {
60885                             var name = prop.escapedName;
60886                             var symbol = resolveName(prop.valueDeclaration, name, 788968 /* Type */, undefined, name, /*isUse*/ false);
60887                             if (symbol && symbol.declarations.some(ts.isJSDocTypedefTag)) {
60888                                 addDuplicateDeclarationErrorsForSymbols(symbol, ts.Diagnostics.Duplicate_identifier_0, ts.unescapeLeadingUnderscores(name), prop);
60889                                 addDuplicateDeclarationErrorsForSymbols(prop, ts.Diagnostics.Duplicate_identifier_0, ts.unescapeLeadingUnderscores(name), symbol);
60890                             }
60891                         }
60892                     }
60893                 }
60894             }
60895             function isEvalNode(node) {
60896                 return node.kind === 75 /* Identifier */ && node.escapedText === "eval";
60897             }
60898             // Return true if there was no error, false if there was an error.
60899             function checkForDisallowedESSymbolOperand(operator) {
60900                 var offendingSymbolOperand = maybeTypeOfKind(leftType, 12288 /* ESSymbolLike */) ? left :
60901                     maybeTypeOfKind(rightType, 12288 /* ESSymbolLike */) ? right :
60902                         undefined;
60903                 if (offendingSymbolOperand) {
60904                     error(offendingSymbolOperand, ts.Diagnostics.The_0_operator_cannot_be_applied_to_type_symbol, ts.tokenToString(operator));
60905                     return false;
60906                 }
60907                 return true;
60908             }
60909             function getSuggestedBooleanOperator(operator) {
60910                 switch (operator) {
60911                     case 51 /* BarToken */:
60912                     case 73 /* BarEqualsToken */:
60913                         return 56 /* BarBarToken */;
60914                     case 52 /* CaretToken */:
60915                     case 74 /* CaretEqualsToken */:
60916                         return 37 /* ExclamationEqualsEqualsToken */;
60917                     case 50 /* AmpersandToken */:
60918                     case 72 /* AmpersandEqualsToken */:
60919                         return 55 /* AmpersandAmpersandToken */;
60920                     default:
60921                         return undefined;
60922                 }
60923             }
60924             function checkAssignmentOperator(valueType) {
60925                 if (produceDiagnostics && ts.isAssignmentOperator(operator)) {
60926                     // TypeScript 1.0 spec (April 2014): 4.17
60927                     // An assignment of the form
60928                     //    VarExpr = ValueExpr
60929                     // requires VarExpr to be classified as a reference
60930                     // A compound assignment furthermore requires VarExpr to be classified as a reference (section 4.1)
60931                     // and the type of the non-compound operation to be assignable to the type of VarExpr.
60932                     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)
60933                         && (!ts.isIdentifier(left) || ts.unescapeLeadingUnderscores(left.escapedText) !== "exports")) {
60934                         // to avoid cascading errors check assignability only if 'isReference' check succeeded and no errors were reported
60935                         checkTypeAssignableToAndOptionallyElaborate(valueType, leftType, left, right);
60936                     }
60937                 }
60938             }
60939             function isAssignmentDeclaration(kind) {
60940                 switch (kind) {
60941                     case 2 /* ModuleExports */:
60942                         return true;
60943                     case 1 /* ExportsProperty */:
60944                     case 5 /* Property */:
60945                     case 6 /* Prototype */:
60946                     case 3 /* PrototypeProperty */:
60947                     case 4 /* ThisProperty */:
60948                         var symbol = getSymbolOfNode(left);
60949                         var init = ts.getAssignedExpandoInitializer(right);
60950                         return init && ts.isObjectLiteralExpression(init) &&
60951                             symbol && ts.hasEntries(symbol.exports);
60952                     default:
60953                         return false;
60954                 }
60955             }
60956             /**
60957              * Returns true if an error is reported
60958              */
60959             function reportOperatorErrorUnless(typesAreCompatible) {
60960                 if (!typesAreCompatible(leftType, rightType)) {
60961                     reportOperatorError(typesAreCompatible);
60962                     return true;
60963                 }
60964                 return false;
60965             }
60966             function reportOperatorError(isRelated) {
60967                 var _a;
60968                 var wouldWorkWithAwait = false;
60969                 var errNode = errorNode || operatorToken;
60970                 if (isRelated) {
60971                     var awaitedLeftType = getAwaitedType(leftType);
60972                     var awaitedRightType = getAwaitedType(rightType);
60973                     wouldWorkWithAwait = !(awaitedLeftType === leftType && awaitedRightType === rightType)
60974                         && !!(awaitedLeftType && awaitedRightType)
60975                         && isRelated(awaitedLeftType, awaitedRightType);
60976                 }
60977                 var effectiveLeft = leftType;
60978                 var effectiveRight = rightType;
60979                 if (!wouldWorkWithAwait && isRelated) {
60980                     _a = getBaseTypesIfUnrelated(leftType, rightType, isRelated), effectiveLeft = _a[0], effectiveRight = _a[1];
60981                 }
60982                 var _b = getTypeNamesForErrorDisplay(effectiveLeft, effectiveRight), leftStr = _b[0], rightStr = _b[1];
60983                 if (!tryGiveBetterPrimaryError(errNode, wouldWorkWithAwait, leftStr, rightStr)) {
60984                     errorAndMaybeSuggestAwait(errNode, wouldWorkWithAwait, ts.Diagnostics.Operator_0_cannot_be_applied_to_types_1_and_2, ts.tokenToString(operatorToken.kind), leftStr, rightStr);
60985                 }
60986             }
60987             function tryGiveBetterPrimaryError(errNode, maybeMissingAwait, leftStr, rightStr) {
60988                 var typeName;
60989                 switch (operatorToken.kind) {
60990                     case 36 /* EqualsEqualsEqualsToken */:
60991                     case 34 /* EqualsEqualsToken */:
60992                         typeName = "false";
60993                         break;
60994                     case 37 /* ExclamationEqualsEqualsToken */:
60995                     case 35 /* ExclamationEqualsToken */:
60996                         typeName = "true";
60997                 }
60998                 if (typeName) {
60999                     return errorAndMaybeSuggestAwait(errNode, maybeMissingAwait, ts.Diagnostics.This_condition_will_always_return_0_since_the_types_1_and_2_have_no_overlap, typeName, leftStr, rightStr);
61000                 }
61001                 return undefined;
61002             }
61003         }
61004         function getBaseTypesIfUnrelated(leftType, rightType, isRelated) {
61005             var effectiveLeft = leftType;
61006             var effectiveRight = rightType;
61007             var leftBase = getBaseTypeOfLiteralType(leftType);
61008             var rightBase = getBaseTypeOfLiteralType(rightType);
61009             if (!isRelated(leftBase, rightBase)) {
61010                 effectiveLeft = leftBase;
61011                 effectiveRight = rightBase;
61012             }
61013             return [effectiveLeft, effectiveRight];
61014         }
61015         function checkYieldExpression(node) {
61016             // Grammar checking
61017             if (produceDiagnostics) {
61018                 if (!(node.flags & 8192 /* YieldContext */)) {
61019                     grammarErrorOnFirstToken(node, ts.Diagnostics.A_yield_expression_is_only_allowed_in_a_generator_body);
61020                 }
61021                 if (isInParameterInitializerBeforeContainingFunction(node)) {
61022                     error(node, ts.Diagnostics.yield_expressions_cannot_be_used_in_a_parameter_initializer);
61023                 }
61024             }
61025             var func = ts.getContainingFunction(node);
61026             if (!func)
61027                 return anyType;
61028             var functionFlags = ts.getFunctionFlags(func);
61029             if (!(functionFlags & 1 /* Generator */)) {
61030                 // If the user's code is syntactically correct, the func should always have a star. After all, we are in a yield context.
61031                 return anyType;
61032             }
61033             var isAsync = (functionFlags & 2 /* Async */) !== 0;
61034             if (node.asteriskToken) {
61035                 // Async generator functions prior to ESNext require the __await, __asyncDelegator,
61036                 // and __asyncValues helpers
61037                 if (isAsync && languageVersion < 99 /* ESNext */) {
61038                     checkExternalEmitHelpers(node, 53248 /* AsyncDelegatorIncludes */);
61039                 }
61040                 // Generator functions prior to ES2015 require the __values helper
61041                 if (!isAsync && languageVersion < 2 /* ES2015 */ && compilerOptions.downlevelIteration) {
61042                     checkExternalEmitHelpers(node, 256 /* Values */);
61043                 }
61044             }
61045             // There is no point in doing an assignability check if the function
61046             // has no explicit return type because the return type is directly computed
61047             // from the yield expressions.
61048             var returnType = getReturnTypeFromAnnotation(func);
61049             var iterationTypes = returnType && getIterationTypesOfGeneratorFunctionReturnType(returnType, isAsync);
61050             var signatureYieldType = iterationTypes && iterationTypes.yieldType || anyType;
61051             var signatureNextType = iterationTypes && iterationTypes.nextType || anyType;
61052             var resolvedSignatureNextType = isAsync ? getAwaitedType(signatureNextType) || anyType : signatureNextType;
61053             var yieldExpressionType = node.expression ? checkExpression(node.expression) : undefinedWideningType;
61054             var yieldedType = getYieldedTypeOfYieldExpression(node, yieldExpressionType, resolvedSignatureNextType, isAsync);
61055             if (returnType && yieldedType) {
61056                 checkTypeAssignableToAndOptionallyElaborate(yieldedType, signatureYieldType, node.expression || node, node.expression);
61057             }
61058             if (node.asteriskToken) {
61059                 var use = isAsync ? 19 /* AsyncYieldStar */ : 17 /* YieldStar */;
61060                 return getIterationTypeOfIterable(use, 1 /* Return */, yieldExpressionType, node.expression)
61061                     || anyType;
61062             }
61063             else if (returnType) {
61064                 return getIterationTypeOfGeneratorFunctionReturnType(2 /* Next */, returnType, isAsync)
61065                     || anyType;
61066             }
61067             return getContextualIterationType(2 /* Next */, func) || anyType;
61068         }
61069         function checkConditionalExpression(node, checkMode) {
61070             var type = checkTruthinessExpression(node.condition);
61071             checkTestingKnownTruthyCallableType(node.condition, node.whenTrue, type);
61072             var type1 = checkExpression(node.whenTrue, checkMode);
61073             var type2 = checkExpression(node.whenFalse, checkMode);
61074             return getUnionType([type1, type2], 2 /* Subtype */);
61075         }
61076         function checkTemplateExpression(node) {
61077             // We just want to check each expressions, but we are unconcerned with
61078             // the type of each expression, as any value may be coerced into a string.
61079             // It is worth asking whether this is what we really want though.
61080             // A place where we actually *are* concerned with the expressions' types are
61081             // in tagged templates.
61082             ts.forEach(node.templateSpans, function (templateSpan) {
61083                 if (maybeTypeOfKind(checkExpression(templateSpan.expression), 12288 /* ESSymbolLike */)) {
61084                     error(templateSpan.expression, ts.Diagnostics.Implicit_conversion_of_a_symbol_to_a_string_will_fail_at_runtime_Consider_wrapping_this_expression_in_String);
61085                 }
61086             });
61087             return stringType;
61088         }
61089         function getContextNode(node) {
61090             if (node.kind === 274 /* JsxAttributes */ && !ts.isJsxSelfClosingElement(node.parent)) {
61091                 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)
61092             }
61093             return node;
61094         }
61095         function checkExpressionWithContextualType(node, contextualType, inferenceContext, checkMode) {
61096             var context = getContextNode(node);
61097             var saveContextualType = context.contextualType;
61098             var saveInferenceContext = context.inferenceContext;
61099             try {
61100                 context.contextualType = contextualType;
61101                 context.inferenceContext = inferenceContext;
61102                 var type = checkExpression(node, checkMode | 1 /* Contextual */ | (inferenceContext ? 2 /* Inferential */ : 0));
61103                 // We strip literal freshness when an appropriate contextual type is present such that contextually typed
61104                 // literals always preserve their literal types (otherwise they might widen during type inference). An alternative
61105                 // here would be to not mark contextually typed literals as fresh in the first place.
61106                 var result = maybeTypeOfKind(type, 2944 /* Literal */) && isLiteralOfContextualType(type, instantiateContextualType(contextualType, node)) ?
61107                     getRegularTypeOfLiteralType(type) : type;
61108                 return result;
61109             }
61110             finally {
61111                 // In the event our operation is canceled or some other exception occurs, reset the contextual type
61112                 // so that we do not accidentally hold onto an instance of the checker, as a Type created in the services layer
61113                 // may hold onto the checker that created it.
61114                 context.contextualType = saveContextualType;
61115                 context.inferenceContext = saveInferenceContext;
61116             }
61117         }
61118         function checkExpressionCached(node, checkMode) {
61119             var links = getNodeLinks(node);
61120             if (!links.resolvedType) {
61121                 if (checkMode && checkMode !== 0 /* Normal */) {
61122                     return checkExpression(node, checkMode);
61123                 }
61124                 // When computing a type that we're going to cache, we need to ignore any ongoing control flow
61125                 // analysis because variables may have transient types in indeterminable states. Moving flowLoopStart
61126                 // to the top of the stack ensures all transient types are computed from a known point.
61127                 var saveFlowLoopStart = flowLoopStart;
61128                 var saveFlowTypeCache = flowTypeCache;
61129                 flowLoopStart = flowLoopCount;
61130                 flowTypeCache = undefined;
61131                 links.resolvedType = checkExpression(node, checkMode);
61132                 flowTypeCache = saveFlowTypeCache;
61133                 flowLoopStart = saveFlowLoopStart;
61134             }
61135             return links.resolvedType;
61136         }
61137         function isTypeAssertion(node) {
61138             node = ts.skipParentheses(node);
61139             return node.kind === 199 /* TypeAssertionExpression */ || node.kind === 217 /* AsExpression */;
61140         }
61141         function checkDeclarationInitializer(declaration, contextualType) {
61142             var initializer = ts.getEffectiveInitializer(declaration);
61143             var type = getQuickTypeOfExpression(initializer) ||
61144                 (contextualType ? checkExpressionWithContextualType(initializer, contextualType, /*inferenceContext*/ undefined, 0 /* Normal */) : checkExpressionCached(initializer));
61145             return ts.isParameter(declaration) && declaration.name.kind === 190 /* ArrayBindingPattern */ &&
61146                 isTupleType(type) && !type.target.hasRestElement && getTypeReferenceArity(type) < declaration.name.elements.length ?
61147                 padTupleType(type, declaration.name) : type;
61148         }
61149         function padTupleType(type, pattern) {
61150             var patternElements = pattern.elements;
61151             var arity = getTypeReferenceArity(type);
61152             var elementTypes = arity ? getTypeArguments(type).slice() : [];
61153             for (var i = arity; i < patternElements.length; i++) {
61154                 var e = patternElements[i];
61155                 if (i < patternElements.length - 1 || !(e.kind === 191 /* BindingElement */ && e.dotDotDotToken)) {
61156                     elementTypes.push(!ts.isOmittedExpression(e) && hasDefaultValue(e) ? getTypeFromBindingElement(e, /*includePatternInType*/ false, /*reportErrors*/ false) : anyType);
61157                     if (!ts.isOmittedExpression(e) && !hasDefaultValue(e)) {
61158                         reportImplicitAny(e, anyType);
61159                     }
61160                 }
61161             }
61162             return createTupleType(elementTypes, type.target.minLength, /*hasRestElement*/ false, type.target.readonly);
61163         }
61164         function widenTypeInferredFromInitializer(declaration, type) {
61165             var widened = ts.getCombinedNodeFlags(declaration) & 2 /* Const */ || ts.isDeclarationReadonly(declaration) ? type : getWidenedLiteralType(type);
61166             if (ts.isInJSFile(declaration)) {
61167                 if (widened.flags & 98304 /* Nullable */) {
61168                     reportImplicitAny(declaration, anyType);
61169                     return anyType;
61170                 }
61171                 else if (isEmptyArrayLiteralType(widened)) {
61172                     reportImplicitAny(declaration, anyArrayType);
61173                     return anyArrayType;
61174                 }
61175             }
61176             return widened;
61177         }
61178         function isLiteralOfContextualType(candidateType, contextualType) {
61179             if (contextualType) {
61180                 if (contextualType.flags & 3145728 /* UnionOrIntersection */) {
61181                     var types = contextualType.types;
61182                     return ts.some(types, function (t) { return isLiteralOfContextualType(candidateType, t); });
61183                 }
61184                 if (contextualType.flags & 58982400 /* InstantiableNonPrimitive */) {
61185                     // If the contextual type is a type variable constrained to a primitive type, consider
61186                     // this a literal context for literals of that primitive type. For example, given a
61187                     // type parameter 'T extends string', infer string literal types for T.
61188                     var constraint = getBaseConstraintOfType(contextualType) || unknownType;
61189                     return maybeTypeOfKind(constraint, 4 /* String */) && maybeTypeOfKind(candidateType, 128 /* StringLiteral */) ||
61190                         maybeTypeOfKind(constraint, 8 /* Number */) && maybeTypeOfKind(candidateType, 256 /* NumberLiteral */) ||
61191                         maybeTypeOfKind(constraint, 64 /* BigInt */) && maybeTypeOfKind(candidateType, 2048 /* BigIntLiteral */) ||
61192                         maybeTypeOfKind(constraint, 4096 /* ESSymbol */) && maybeTypeOfKind(candidateType, 8192 /* UniqueESSymbol */) ||
61193                         isLiteralOfContextualType(candidateType, constraint);
61194                 }
61195                 // If the contextual type is a literal of a particular primitive type, we consider this a
61196                 // literal context for all literals of that primitive type.
61197                 return !!(contextualType.flags & (128 /* StringLiteral */ | 4194304 /* Index */) && maybeTypeOfKind(candidateType, 128 /* StringLiteral */) ||
61198                     contextualType.flags & 256 /* NumberLiteral */ && maybeTypeOfKind(candidateType, 256 /* NumberLiteral */) ||
61199                     contextualType.flags & 2048 /* BigIntLiteral */ && maybeTypeOfKind(candidateType, 2048 /* BigIntLiteral */) ||
61200                     contextualType.flags & 512 /* BooleanLiteral */ && maybeTypeOfKind(candidateType, 512 /* BooleanLiteral */) ||
61201                     contextualType.flags & 8192 /* UniqueESSymbol */ && maybeTypeOfKind(candidateType, 8192 /* UniqueESSymbol */));
61202             }
61203             return false;
61204         }
61205         function isConstContext(node) {
61206             var parent = node.parent;
61207             return ts.isAssertionExpression(parent) && ts.isConstTypeReference(parent.type) ||
61208                 (ts.isParenthesizedExpression(parent) || ts.isArrayLiteralExpression(parent) || ts.isSpreadElement(parent)) && isConstContext(parent) ||
61209                 (ts.isPropertyAssignment(parent) || ts.isShorthandPropertyAssignment(parent)) && isConstContext(parent.parent);
61210         }
61211         function checkExpressionForMutableLocation(node, checkMode, contextualType, forceTuple) {
61212             var type = checkExpression(node, checkMode, forceTuple);
61213             return isConstContext(node) ? getRegularTypeOfLiteralType(type) :
61214                 isTypeAssertion(node) ? type :
61215                     getWidenedLiteralLikeTypeForContextualType(type, instantiateContextualType(arguments.length === 2 ? getContextualType(node) : contextualType, node));
61216         }
61217         function checkPropertyAssignment(node, checkMode) {
61218             // Do not use hasDynamicName here, because that returns false for well known symbols.
61219             // We want to perform checkComputedPropertyName for all computed properties, including
61220             // well known symbols.
61221             if (node.name.kind === 154 /* ComputedPropertyName */) {
61222                 checkComputedPropertyName(node.name);
61223             }
61224             return checkExpressionForMutableLocation(node.initializer, checkMode);
61225         }
61226         function checkObjectLiteralMethod(node, checkMode) {
61227             // Grammar checking
61228             checkGrammarMethod(node);
61229             // Do not use hasDynamicName here, because that returns false for well known symbols.
61230             // We want to perform checkComputedPropertyName for all computed properties, including
61231             // well known symbols.
61232             if (node.name.kind === 154 /* ComputedPropertyName */) {
61233                 checkComputedPropertyName(node.name);
61234             }
61235             var uninstantiatedType = checkFunctionExpressionOrObjectLiteralMethod(node, checkMode);
61236             return instantiateTypeWithSingleGenericCallSignature(node, uninstantiatedType, checkMode);
61237         }
61238         function instantiateTypeWithSingleGenericCallSignature(node, type, checkMode) {
61239             if (checkMode && checkMode & (2 /* Inferential */ | 8 /* SkipGenericFunctions */)) {
61240                 var callSignature = getSingleSignature(type, 0 /* Call */, /*allowMembers*/ true);
61241                 var constructSignature = getSingleSignature(type, 1 /* Construct */, /*allowMembers*/ true);
61242                 var signature = callSignature || constructSignature;
61243                 if (signature && signature.typeParameters) {
61244                     var contextualType = getApparentTypeOfContextualType(node, 2 /* NoConstraints */);
61245                     if (contextualType) {
61246                         var contextualSignature = getSingleSignature(getNonNullableType(contextualType), callSignature ? 0 /* Call */ : 1 /* Construct */, /*allowMembers*/ false);
61247                         if (contextualSignature && !contextualSignature.typeParameters) {
61248                             if (checkMode & 8 /* SkipGenericFunctions */) {
61249                                 skippedGenericFunction(node, checkMode);
61250                                 return anyFunctionType;
61251                             }
61252                             var context = getInferenceContext(node);
61253                             // We have an expression that is an argument of a generic function for which we are performing
61254                             // type argument inference. The expression is of a function type with a single generic call
61255                             // signature and a contextual function type with a single non-generic call signature. Now check
61256                             // if the outer function returns a function type with a single non-generic call signature and
61257                             // if some of the outer function type parameters have no inferences so far. If so, we can
61258                             // potentially add inferred type parameters to the outer function return type.
61259                             var returnType = context.signature && getReturnTypeOfSignature(context.signature);
61260                             var returnSignature = returnType && getSingleCallOrConstructSignature(returnType);
61261                             if (returnSignature && !returnSignature.typeParameters && !ts.every(context.inferences, hasInferenceCandidates)) {
61262                                 // Instantiate the signature with its own type parameters as type arguments, possibly
61263                                 // renaming the type parameters to ensure they have unique names.
61264                                 var uniqueTypeParameters = getUniqueTypeParameters(context, signature.typeParameters);
61265                                 var instantiatedSignature = getSignatureInstantiationWithoutFillingInTypeArguments(signature, uniqueTypeParameters);
61266                                 // Infer from the parameters of the instantiated signature to the parameters of the
61267                                 // contextual signature starting with an empty set of inference candidates.
61268                                 var inferences_3 = ts.map(context.inferences, function (info) { return createInferenceInfo(info.typeParameter); });
61269                                 applyToParameterTypes(instantiatedSignature, contextualSignature, function (source, target) {
61270                                     inferTypes(inferences_3, source, target, /*priority*/ 0, /*contravariant*/ true);
61271                                 });
61272                                 if (ts.some(inferences_3, hasInferenceCandidates)) {
61273                                     // We have inference candidates, indicating that one or more type parameters are referenced
61274                                     // in the parameter types of the contextual signature. Now also infer from the return type.
61275                                     applyToReturnTypes(instantiatedSignature, contextualSignature, function (source, target) {
61276                                         inferTypes(inferences_3, source, target);
61277                                     });
61278                                     // If the type parameters for which we produced candidates do not have any inferences yet,
61279                                     // we adopt the new inference candidates and add the type parameters of the expression type
61280                                     // to the set of inferred type parameters for the outer function return type.
61281                                     if (!hasOverlappingInferences(context.inferences, inferences_3)) {
61282                                         mergeInferences(context.inferences, inferences_3);
61283                                         context.inferredTypeParameters = ts.concatenate(context.inferredTypeParameters, uniqueTypeParameters);
61284                                         return getOrCreateTypeFromSignature(instantiatedSignature);
61285                                     }
61286                                 }
61287                             }
61288                             return getOrCreateTypeFromSignature(instantiateSignatureInContextOf(signature, contextualSignature, context));
61289                         }
61290                     }
61291                 }
61292             }
61293             return type;
61294         }
61295         function skippedGenericFunction(node, checkMode) {
61296             if (checkMode & 2 /* Inferential */) {
61297                 // We have skipped a generic function during inferential typing. Obtain the inference context and
61298                 // indicate this has occurred such that we know a second pass of inference is be needed.
61299                 var context = getInferenceContext(node);
61300                 context.flags |= 4 /* SkippedGenericFunction */;
61301             }
61302         }
61303         function hasInferenceCandidates(info) {
61304             return !!(info.candidates || info.contraCandidates);
61305         }
61306         function hasOverlappingInferences(a, b) {
61307             for (var i = 0; i < a.length; i++) {
61308                 if (hasInferenceCandidates(a[i]) && hasInferenceCandidates(b[i])) {
61309                     return true;
61310                 }
61311             }
61312             return false;
61313         }
61314         function mergeInferences(target, source) {
61315             for (var i = 0; i < target.length; i++) {
61316                 if (!hasInferenceCandidates(target[i]) && hasInferenceCandidates(source[i])) {
61317                     target[i] = source[i];
61318                 }
61319             }
61320         }
61321         function getUniqueTypeParameters(context, typeParameters) {
61322             var result = [];
61323             var oldTypeParameters;
61324             var newTypeParameters;
61325             for (var _i = 0, typeParameters_2 = typeParameters; _i < typeParameters_2.length; _i++) {
61326                 var tp = typeParameters_2[_i];
61327                 var name = tp.symbol.escapedName;
61328                 if (hasTypeParameterByName(context.inferredTypeParameters, name) || hasTypeParameterByName(result, name)) {
61329                     var newName = getUniqueTypeParameterName(ts.concatenate(context.inferredTypeParameters, result), name);
61330                     var symbol = createSymbol(262144 /* TypeParameter */, newName);
61331                     var newTypeParameter = createTypeParameter(symbol);
61332                     newTypeParameter.target = tp;
61333                     oldTypeParameters = ts.append(oldTypeParameters, tp);
61334                     newTypeParameters = ts.append(newTypeParameters, newTypeParameter);
61335                     result.push(newTypeParameter);
61336                 }
61337                 else {
61338                     result.push(tp);
61339                 }
61340             }
61341             if (newTypeParameters) {
61342                 var mapper = createTypeMapper(oldTypeParameters, newTypeParameters);
61343                 for (var _a = 0, newTypeParameters_1 = newTypeParameters; _a < newTypeParameters_1.length; _a++) {
61344                     var tp = newTypeParameters_1[_a];
61345                     tp.mapper = mapper;
61346                 }
61347             }
61348             return result;
61349         }
61350         function hasTypeParameterByName(typeParameters, name) {
61351             return ts.some(typeParameters, function (tp) { return tp.symbol.escapedName === name; });
61352         }
61353         function getUniqueTypeParameterName(typeParameters, baseName) {
61354             var len = baseName.length;
61355             while (len > 1 && baseName.charCodeAt(len - 1) >= 48 /* _0 */ && baseName.charCodeAt(len - 1) <= 57 /* _9 */)
61356                 len--;
61357             var s = baseName.slice(0, len);
61358             for (var index = 1; true; index++) {
61359                 var augmentedName = (s + index);
61360                 if (!hasTypeParameterByName(typeParameters, augmentedName)) {
61361                     return augmentedName;
61362                 }
61363             }
61364         }
61365         function getReturnTypeOfSingleNonGenericCallSignature(funcType) {
61366             var signature = getSingleCallSignature(funcType);
61367             if (signature && !signature.typeParameters) {
61368                 return getReturnTypeOfSignature(signature);
61369             }
61370         }
61371         function getReturnTypeOfSingleNonGenericSignatureOfCallChain(expr) {
61372             var funcType = checkExpression(expr.expression);
61373             var nonOptionalType = getOptionalExpressionType(funcType, expr.expression);
61374             var returnType = getReturnTypeOfSingleNonGenericCallSignature(funcType);
61375             return returnType && propagateOptionalTypeMarker(returnType, expr, nonOptionalType !== funcType);
61376         }
61377         /**
61378          * Returns the type of an expression. Unlike checkExpression, this function is simply concerned
61379          * with computing the type and may not fully check all contained sub-expressions for errors.
61380          */
61381         function getTypeOfExpression(node) {
61382             // Don't bother caching types that require no flow analysis and are quick to compute.
61383             var quickType = getQuickTypeOfExpression(node);
61384             if (quickType) {
61385                 return quickType;
61386             }
61387             // If a type has been cached for the node, return it.
61388             if (node.flags & 67108864 /* TypeCached */ && flowTypeCache) {
61389                 var cachedType = flowTypeCache[getNodeId(node)];
61390                 if (cachedType) {
61391                     return cachedType;
61392                 }
61393             }
61394             var startInvocationCount = flowInvocationCount;
61395             var type = checkExpression(node);
61396             // If control flow analysis was required to determine the type, it is worth caching.
61397             if (flowInvocationCount !== startInvocationCount) {
61398                 var cache = flowTypeCache || (flowTypeCache = []);
61399                 cache[getNodeId(node)] = type;
61400                 node.flags |= 67108864 /* TypeCached */;
61401             }
61402             return type;
61403         }
61404         function getQuickTypeOfExpression(node) {
61405             var expr = ts.skipParentheses(node);
61406             // Optimize for the common case of a call to a function with a single non-generic call
61407             // signature where we can just fetch the return type without checking the arguments.
61408             if (ts.isCallExpression(expr) && expr.expression.kind !== 102 /* SuperKeyword */ && !ts.isRequireCall(expr, /*checkArgumentIsStringLiteralLike*/ true) && !isSymbolOrSymbolForCall(expr)) {
61409                 var type = ts.isCallChain(expr) ? getReturnTypeOfSingleNonGenericSignatureOfCallChain(expr) :
61410                     getReturnTypeOfSingleNonGenericCallSignature(checkNonNullExpression(expr.expression));
61411                 if (type) {
61412                     return type;
61413                 }
61414             }
61415             else if (ts.isAssertionExpression(expr) && !ts.isConstTypeReference(expr.type)) {
61416                 return getTypeFromTypeNode(expr.type);
61417             }
61418             else if (node.kind === 8 /* NumericLiteral */ || node.kind === 10 /* StringLiteral */ ||
61419                 node.kind === 106 /* TrueKeyword */ || node.kind === 91 /* FalseKeyword */) {
61420                 return checkExpression(node);
61421             }
61422             return undefined;
61423         }
61424         /**
61425          * Returns the type of an expression. Unlike checkExpression, this function is simply concerned
61426          * with computing the type and may not fully check all contained sub-expressions for errors.
61427          * It is intended for uses where you know there is no contextual type,
61428          * and requesting the contextual type might cause a circularity or other bad behaviour.
61429          * It sets the contextual type of the node to any before calling getTypeOfExpression.
61430          */
61431         function getContextFreeTypeOfExpression(node) {
61432             var links = getNodeLinks(node);
61433             if (links.contextFreeType) {
61434                 return links.contextFreeType;
61435             }
61436             var saveContextualType = node.contextualType;
61437             node.contextualType = anyType;
61438             try {
61439                 var type = links.contextFreeType = checkExpression(node, 4 /* SkipContextSensitive */);
61440                 return type;
61441             }
61442             finally {
61443                 // In the event our operation is canceled or some other exception occurs, reset the contextual type
61444                 // so that we do not accidentally hold onto an instance of the checker, as a Type created in the services layer
61445                 // may hold onto the checker that created it.
61446                 node.contextualType = saveContextualType;
61447             }
61448         }
61449         function checkExpression(node, checkMode, forceTuple) {
61450             var saveCurrentNode = currentNode;
61451             currentNode = node;
61452             instantiationCount = 0;
61453             var uninstantiatedType = checkExpressionWorker(node, checkMode, forceTuple);
61454             var type = instantiateTypeWithSingleGenericCallSignature(node, uninstantiatedType, checkMode);
61455             if (isConstEnumObjectType(type)) {
61456                 checkConstEnumAccess(node, type);
61457             }
61458             currentNode = saveCurrentNode;
61459             return type;
61460         }
61461         function checkConstEnumAccess(node, type) {
61462             // enum object type for const enums are only permitted in:
61463             // - 'left' in property access
61464             // - 'object' in indexed access
61465             // - target in rhs of import statement
61466             var ok = (node.parent.kind === 194 /* PropertyAccessExpression */ && node.parent.expression === node) ||
61467                 (node.parent.kind === 195 /* ElementAccessExpression */ && node.parent.expression === node) ||
61468                 ((node.kind === 75 /* Identifier */ || node.kind === 153 /* QualifiedName */) && isInRightSideOfImportOrExportAssignment(node) ||
61469                     (node.parent.kind === 172 /* TypeQuery */ && node.parent.exprName === node)) ||
61470                 (node.parent.kind === 263 /* ExportSpecifier */); // We allow reexporting const enums
61471             if (!ok) {
61472                 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);
61473             }
61474             if (compilerOptions.isolatedModules) {
61475                 ts.Debug.assert(!!(type.symbol.flags & 128 /* ConstEnum */));
61476                 var constEnumDeclaration = type.symbol.valueDeclaration;
61477                 if (constEnumDeclaration.flags & 8388608 /* Ambient */) {
61478                     error(node, ts.Diagnostics.Cannot_access_ambient_const_enums_when_the_isolatedModules_flag_is_provided);
61479                 }
61480             }
61481         }
61482         function checkParenthesizedExpression(node, checkMode) {
61483             var tag = ts.isInJSFile(node) ? ts.getJSDocTypeTag(node) : undefined;
61484             if (tag) {
61485                 return checkAssertionWorker(tag, tag.typeExpression.type, node.expression, checkMode);
61486             }
61487             return checkExpression(node.expression, checkMode);
61488         }
61489         function checkExpressionWorker(node, checkMode, forceTuple) {
61490             var kind = node.kind;
61491             if (cancellationToken) {
61492                 // Only bother checking on a few construct kinds.  We don't want to be excessively
61493                 // hitting the cancellation token on every node we check.
61494                 switch (kind) {
61495                     case 214 /* ClassExpression */:
61496                     case 201 /* FunctionExpression */:
61497                     case 202 /* ArrowFunction */:
61498                         cancellationToken.throwIfCancellationRequested();
61499                 }
61500             }
61501             switch (kind) {
61502                 case 75 /* Identifier */:
61503                     return checkIdentifier(node);
61504                 case 104 /* ThisKeyword */:
61505                     return checkThisExpression(node);
61506                 case 102 /* SuperKeyword */:
61507                     return checkSuperExpression(node);
61508                 case 100 /* NullKeyword */:
61509                     return nullWideningType;
61510                 case 14 /* NoSubstitutionTemplateLiteral */:
61511                 case 10 /* StringLiteral */:
61512                     return getFreshTypeOfLiteralType(getLiteralType(node.text));
61513                 case 8 /* NumericLiteral */:
61514                     checkGrammarNumericLiteral(node);
61515                     return getFreshTypeOfLiteralType(getLiteralType(+node.text));
61516                 case 9 /* BigIntLiteral */:
61517                     checkGrammarBigIntLiteral(node);
61518                     return getFreshTypeOfLiteralType(getBigIntLiteralType(node));
61519                 case 106 /* TrueKeyword */:
61520                     return trueType;
61521                 case 91 /* FalseKeyword */:
61522                     return falseType;
61523                 case 211 /* TemplateExpression */:
61524                     return checkTemplateExpression(node);
61525                 case 13 /* RegularExpressionLiteral */:
61526                     return globalRegExpType;
61527                 case 192 /* ArrayLiteralExpression */:
61528                     return checkArrayLiteral(node, checkMode, forceTuple);
61529                 case 193 /* ObjectLiteralExpression */:
61530                     return checkObjectLiteral(node, checkMode);
61531                 case 194 /* PropertyAccessExpression */:
61532                     return checkPropertyAccessExpression(node);
61533                 case 153 /* QualifiedName */:
61534                     return checkQualifiedName(node);
61535                 case 195 /* ElementAccessExpression */:
61536                     return checkIndexedAccess(node);
61537                 case 196 /* CallExpression */:
61538                     if (node.expression.kind === 96 /* ImportKeyword */) {
61539                         return checkImportCallExpression(node);
61540                     }
61541                 // falls through
61542                 case 197 /* NewExpression */:
61543                     return checkCallExpression(node, checkMode);
61544                 case 198 /* TaggedTemplateExpression */:
61545                     return checkTaggedTemplateExpression(node);
61546                 case 200 /* ParenthesizedExpression */:
61547                     return checkParenthesizedExpression(node, checkMode);
61548                 case 214 /* ClassExpression */:
61549                     return checkClassExpression(node);
61550                 case 201 /* FunctionExpression */:
61551                 case 202 /* ArrowFunction */:
61552                     return checkFunctionExpressionOrObjectLiteralMethod(node, checkMode);
61553                 case 204 /* TypeOfExpression */:
61554                     return checkTypeOfExpression(node);
61555                 case 199 /* TypeAssertionExpression */:
61556                 case 217 /* AsExpression */:
61557                     return checkAssertion(node);
61558                 case 218 /* NonNullExpression */:
61559                     return checkNonNullAssertion(node);
61560                 case 219 /* MetaProperty */:
61561                     return checkMetaProperty(node);
61562                 case 203 /* DeleteExpression */:
61563                     return checkDeleteExpression(node);
61564                 case 205 /* VoidExpression */:
61565                     return checkVoidExpression(node);
61566                 case 206 /* AwaitExpression */:
61567                     return checkAwaitExpression(node);
61568                 case 207 /* PrefixUnaryExpression */:
61569                     return checkPrefixUnaryExpression(node);
61570                 case 208 /* PostfixUnaryExpression */:
61571                     return checkPostfixUnaryExpression(node);
61572                 case 209 /* BinaryExpression */:
61573                     return checkBinaryExpression(node, checkMode);
61574                 case 210 /* ConditionalExpression */:
61575                     return checkConditionalExpression(node, checkMode);
61576                 case 213 /* SpreadElement */:
61577                     return checkSpreadExpression(node, checkMode);
61578                 case 215 /* OmittedExpression */:
61579                     return undefinedWideningType;
61580                 case 212 /* YieldExpression */:
61581                     return checkYieldExpression(node);
61582                 case 220 /* SyntheticExpression */:
61583                     return node.type;
61584                 case 276 /* JsxExpression */:
61585                     return checkJsxExpression(node, checkMode);
61586                 case 266 /* JsxElement */:
61587                     return checkJsxElement(node, checkMode);
61588                 case 267 /* JsxSelfClosingElement */:
61589                     return checkJsxSelfClosingElement(node, checkMode);
61590                 case 270 /* JsxFragment */:
61591                     return checkJsxFragment(node);
61592                 case 274 /* JsxAttributes */:
61593                     return checkJsxAttributes(node, checkMode);
61594                 case 268 /* JsxOpeningElement */:
61595                     ts.Debug.fail("Shouldn't ever directly check a JsxOpeningElement");
61596             }
61597             return errorType;
61598         }
61599         // DECLARATION AND STATEMENT TYPE CHECKING
61600         function checkTypeParameter(node) {
61601             // Grammar Checking
61602             if (node.expression) {
61603                 grammarErrorOnFirstToken(node.expression, ts.Diagnostics.Type_expected);
61604             }
61605             checkSourceElement(node.constraint);
61606             checkSourceElement(node.default);
61607             var typeParameter = getDeclaredTypeOfTypeParameter(getSymbolOfNode(node));
61608             // Resolve base constraint to reveal circularity errors
61609             getBaseConstraintOfType(typeParameter);
61610             if (!hasNonCircularTypeParameterDefault(typeParameter)) {
61611                 error(node.default, ts.Diagnostics.Type_parameter_0_has_a_circular_default, typeToString(typeParameter));
61612             }
61613             var constraintType = getConstraintOfTypeParameter(typeParameter);
61614             var defaultType = getDefaultFromTypeParameter(typeParameter);
61615             if (constraintType && defaultType) {
61616                 checkTypeAssignableTo(defaultType, getTypeWithThisArgument(instantiateType(constraintType, makeUnaryTypeMapper(typeParameter, defaultType)), defaultType), node.default, ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1);
61617             }
61618             if (produceDiagnostics) {
61619                 checkTypeNameIsReserved(node.name, ts.Diagnostics.Type_parameter_name_cannot_be_0);
61620             }
61621         }
61622         function checkParameter(node) {
61623             // Grammar checking
61624             // It is a SyntaxError if the Identifier "eval" or the Identifier "arguments" occurs as the
61625             // Identifier in a PropertySetParameterList of a PropertyAssignment that is contained in strict code
61626             // or if its FunctionBody is strict code(11.1.5).
61627             checkGrammarDecoratorsAndModifiers(node);
61628             checkVariableLikeDeclaration(node);
61629             var func = ts.getContainingFunction(node);
61630             if (ts.hasModifier(node, 92 /* ParameterPropertyModifier */)) {
61631                 if (!(func.kind === 162 /* Constructor */ && ts.nodeIsPresent(func.body))) {
61632                     error(node, ts.Diagnostics.A_parameter_property_is_only_allowed_in_a_constructor_implementation);
61633                 }
61634                 if (func.kind === 162 /* Constructor */ && ts.isIdentifier(node.name) && node.name.escapedText === "constructor") {
61635                     error(node.name, ts.Diagnostics.constructor_cannot_be_used_as_a_parameter_property_name);
61636                 }
61637             }
61638             if (node.questionToken && ts.isBindingPattern(node.name) && func.body) {
61639                 error(node, ts.Diagnostics.A_binding_pattern_parameter_cannot_be_optional_in_an_implementation_signature);
61640             }
61641             if (node.name && ts.isIdentifier(node.name) && (node.name.escapedText === "this" || node.name.escapedText === "new")) {
61642                 if (func.parameters.indexOf(node) !== 0) {
61643                     error(node, ts.Diagnostics.A_0_parameter_must_be_the_first_parameter, node.name.escapedText);
61644                 }
61645                 if (func.kind === 162 /* Constructor */ || func.kind === 166 /* ConstructSignature */ || func.kind === 171 /* ConstructorType */) {
61646                     error(node, ts.Diagnostics.A_constructor_cannot_have_a_this_parameter);
61647                 }
61648                 if (func.kind === 202 /* ArrowFunction */) {
61649                     error(node, ts.Diagnostics.An_arrow_function_cannot_have_a_this_parameter);
61650                 }
61651                 if (func.kind === 163 /* GetAccessor */ || func.kind === 164 /* SetAccessor */) {
61652                     error(node, ts.Diagnostics.get_and_set_accessors_cannot_declare_this_parameters);
61653                 }
61654             }
61655             // Only check rest parameter type if it's not a binding pattern. Since binding patterns are
61656             // not allowed in a rest parameter, we already have an error from checkGrammarParameterList.
61657             if (node.dotDotDotToken && !ts.isBindingPattern(node.name) && !isTypeAssignableTo(getReducedType(getTypeOfSymbol(node.symbol)), anyReadonlyArrayType)) {
61658                 error(node, ts.Diagnostics.A_rest_parameter_must_be_of_an_array_type);
61659             }
61660         }
61661         function checkTypePredicate(node) {
61662             var parent = getTypePredicateParent(node);
61663             if (!parent) {
61664                 // The parent must not be valid.
61665                 error(node, ts.Diagnostics.A_type_predicate_is_only_allowed_in_return_type_position_for_functions_and_methods);
61666                 return;
61667             }
61668             var signature = getSignatureFromDeclaration(parent);
61669             var typePredicate = getTypePredicateOfSignature(signature);
61670             if (!typePredicate) {
61671                 return;
61672             }
61673             checkSourceElement(node.type);
61674             var parameterName = node.parameterName;
61675             if (typePredicate.kind === 0 /* This */ || typePredicate.kind === 2 /* AssertsThis */) {
61676                 getTypeFromThisTypeNode(parameterName);
61677             }
61678             else {
61679                 if (typePredicate.parameterIndex >= 0) {
61680                     if (signatureHasRestParameter(signature) && typePredicate.parameterIndex === signature.parameters.length - 1) {
61681                         error(parameterName, ts.Diagnostics.A_type_predicate_cannot_reference_a_rest_parameter);
61682                     }
61683                     else {
61684                         if (typePredicate.type) {
61685                             var leadingError = function () { return ts.chainDiagnosticMessages(/*details*/ undefined, ts.Diagnostics.A_type_predicate_s_type_must_be_assignable_to_its_parameter_s_type); };
61686                             checkTypeAssignableTo(typePredicate.type, getTypeOfSymbol(signature.parameters[typePredicate.parameterIndex]), node.type, 
61687                             /*headMessage*/ undefined, leadingError);
61688                         }
61689                     }
61690                 }
61691                 else if (parameterName) {
61692                     var hasReportedError = false;
61693                     for (var _i = 0, _a = parent.parameters; _i < _a.length; _i++) {
61694                         var name = _a[_i].name;
61695                         if (ts.isBindingPattern(name) &&
61696                             checkIfTypePredicateVariableIsDeclaredInBindingPattern(name, parameterName, typePredicate.parameterName)) {
61697                             hasReportedError = true;
61698                             break;
61699                         }
61700                     }
61701                     if (!hasReportedError) {
61702                         error(node.parameterName, ts.Diagnostics.Cannot_find_parameter_0, typePredicate.parameterName);
61703                     }
61704                 }
61705             }
61706         }
61707         function getTypePredicateParent(node) {
61708             switch (node.parent.kind) {
61709                 case 202 /* ArrowFunction */:
61710                 case 165 /* CallSignature */:
61711                 case 244 /* FunctionDeclaration */:
61712                 case 201 /* FunctionExpression */:
61713                 case 170 /* FunctionType */:
61714                 case 161 /* MethodDeclaration */:
61715                 case 160 /* MethodSignature */:
61716                     var parent = node.parent;
61717                     if (node === parent.type) {
61718                         return parent;
61719                     }
61720             }
61721         }
61722         function checkIfTypePredicateVariableIsDeclaredInBindingPattern(pattern, predicateVariableNode, predicateVariableName) {
61723             for (var _i = 0, _a = pattern.elements; _i < _a.length; _i++) {
61724                 var element = _a[_i];
61725                 if (ts.isOmittedExpression(element)) {
61726                     continue;
61727                 }
61728                 var name = element.name;
61729                 if (name.kind === 75 /* Identifier */ && name.escapedText === predicateVariableName) {
61730                     error(predicateVariableNode, ts.Diagnostics.A_type_predicate_cannot_reference_element_0_in_a_binding_pattern, predicateVariableName);
61731                     return true;
61732                 }
61733                 else if (name.kind === 190 /* ArrayBindingPattern */ || name.kind === 189 /* ObjectBindingPattern */) {
61734                     if (checkIfTypePredicateVariableIsDeclaredInBindingPattern(name, predicateVariableNode, predicateVariableName)) {
61735                         return true;
61736                     }
61737                 }
61738             }
61739         }
61740         function checkSignatureDeclaration(node) {
61741             // Grammar checking
61742             if (node.kind === 167 /* IndexSignature */) {
61743                 checkGrammarIndexSignature(node);
61744             }
61745             // TODO (yuisu): Remove this check in else-if when SyntaxKind.Construct is moved and ambient context is handled
61746             else if (node.kind === 170 /* FunctionType */ || node.kind === 244 /* FunctionDeclaration */ || node.kind === 171 /* ConstructorType */ ||
61747                 node.kind === 165 /* CallSignature */ || node.kind === 162 /* Constructor */ ||
61748                 node.kind === 166 /* ConstructSignature */) {
61749                 checkGrammarFunctionLikeDeclaration(node);
61750             }
61751             var functionFlags = ts.getFunctionFlags(node);
61752             if (!(functionFlags & 4 /* Invalid */)) {
61753                 // Async generators prior to ESNext require the __await and __asyncGenerator helpers
61754                 if ((functionFlags & 3 /* AsyncGenerator */) === 3 /* AsyncGenerator */ && languageVersion < 99 /* ESNext */) {
61755                     checkExternalEmitHelpers(node, 12288 /* AsyncGeneratorIncludes */);
61756                 }
61757                 // Async functions prior to ES2017 require the __awaiter helper
61758                 if ((functionFlags & 3 /* AsyncGenerator */) === 2 /* Async */ && languageVersion < 4 /* ES2017 */) {
61759                     checkExternalEmitHelpers(node, 64 /* Awaiter */);
61760                 }
61761                 // Generator functions, Async functions, and Async Generator functions prior to
61762                 // ES2015 require the __generator helper
61763                 if ((functionFlags & 3 /* AsyncGenerator */) !== 0 /* Normal */ && languageVersion < 2 /* ES2015 */) {
61764                     checkExternalEmitHelpers(node, 128 /* Generator */);
61765                 }
61766             }
61767             checkTypeParameters(node.typeParameters);
61768             ts.forEach(node.parameters, checkParameter);
61769             // TODO(rbuckton): Should we start checking JSDoc types?
61770             if (node.type) {
61771                 checkSourceElement(node.type);
61772             }
61773             if (produceDiagnostics) {
61774                 checkCollisionWithArgumentsInGeneratedCode(node);
61775                 var returnTypeNode = ts.getEffectiveReturnTypeNode(node);
61776                 if (noImplicitAny && !returnTypeNode) {
61777                     switch (node.kind) {
61778                         case 166 /* ConstructSignature */:
61779                             error(node, ts.Diagnostics.Construct_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type);
61780                             break;
61781                         case 165 /* CallSignature */:
61782                             error(node, ts.Diagnostics.Call_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type);
61783                             break;
61784                     }
61785                 }
61786                 if (returnTypeNode) {
61787                     var functionFlags_1 = ts.getFunctionFlags(node);
61788                     if ((functionFlags_1 & (4 /* Invalid */ | 1 /* Generator */)) === 1 /* Generator */) {
61789                         var returnType = getTypeFromTypeNode(returnTypeNode);
61790                         if (returnType === voidType) {
61791                             error(returnTypeNode, ts.Diagnostics.A_generator_cannot_have_a_void_type_annotation);
61792                         }
61793                         else {
61794                             // Naively, one could check that Generator<any, any, any> is assignable to the return type annotation.
61795                             // However, that would not catch the error in the following case.
61796                             //
61797                             //    interface BadGenerator extends Iterable<number>, Iterator<string> { }
61798                             //    function* g(): BadGenerator { } // Iterable and Iterator have different types!
61799                             //
61800                             var generatorYieldType = getIterationTypeOfGeneratorFunctionReturnType(0 /* Yield */, returnType, (functionFlags_1 & 2 /* Async */) !== 0) || anyType;
61801                             var generatorReturnType = getIterationTypeOfGeneratorFunctionReturnType(1 /* Return */, returnType, (functionFlags_1 & 2 /* Async */) !== 0) || generatorYieldType;
61802                             var generatorNextType = getIterationTypeOfGeneratorFunctionReturnType(2 /* Next */, returnType, (functionFlags_1 & 2 /* Async */) !== 0) || unknownType;
61803                             var generatorInstantiation = createGeneratorReturnType(generatorYieldType, generatorReturnType, generatorNextType, !!(functionFlags_1 & 2 /* Async */));
61804                             checkTypeAssignableTo(generatorInstantiation, returnType, returnTypeNode);
61805                         }
61806                     }
61807                     else if ((functionFlags_1 & 3 /* AsyncGenerator */) === 2 /* Async */) {
61808                         checkAsyncFunctionReturnType(node, returnTypeNode);
61809                     }
61810                 }
61811                 if (node.kind !== 167 /* IndexSignature */ && node.kind !== 300 /* JSDocFunctionType */) {
61812                     registerForUnusedIdentifiersCheck(node);
61813                 }
61814             }
61815         }
61816         function checkClassForDuplicateDeclarations(node) {
61817             var instanceNames = ts.createUnderscoreEscapedMap();
61818             var staticNames = ts.createUnderscoreEscapedMap();
61819             // instance and static private identifiers share the same scope
61820             var privateIdentifiers = ts.createUnderscoreEscapedMap();
61821             for (var _i = 0, _a = node.members; _i < _a.length; _i++) {
61822                 var member = _a[_i];
61823                 if (member.kind === 162 /* Constructor */) {
61824                     for (var _b = 0, _c = member.parameters; _b < _c.length; _b++) {
61825                         var param = _c[_b];
61826                         if (ts.isParameterPropertyDeclaration(param, member) && !ts.isBindingPattern(param.name)) {
61827                             addName(instanceNames, param.name, param.name.escapedText, 3 /* GetOrSetAccessor */);
61828                         }
61829                     }
61830                 }
61831                 else {
61832                     var isStatic = ts.hasModifier(member, 32 /* Static */);
61833                     var name = member.name;
61834                     if (!name) {
61835                         return;
61836                     }
61837                     var names = ts.isPrivateIdentifier(name) ? privateIdentifiers :
61838                         isStatic ? staticNames :
61839                             instanceNames;
61840                     var memberName = name && ts.getPropertyNameForPropertyNameNode(name);
61841                     if (memberName) {
61842                         switch (member.kind) {
61843                             case 163 /* GetAccessor */:
61844                                 addName(names, name, memberName, 1 /* GetAccessor */);
61845                                 break;
61846                             case 164 /* SetAccessor */:
61847                                 addName(names, name, memberName, 2 /* SetAccessor */);
61848                                 break;
61849                             case 159 /* PropertyDeclaration */:
61850                                 addName(names, name, memberName, 3 /* GetOrSetAccessor */);
61851                                 break;
61852                             case 161 /* MethodDeclaration */:
61853                                 addName(names, name, memberName, 8 /* Method */);
61854                                 break;
61855                         }
61856                     }
61857                 }
61858             }
61859             function addName(names, location, name, meaning) {
61860                 var prev = names.get(name);
61861                 if (prev) {
61862                     if (prev & 8 /* Method */) {
61863                         if (meaning !== 8 /* Method */) {
61864                             error(location, ts.Diagnostics.Duplicate_identifier_0, ts.getTextOfNode(location));
61865                         }
61866                     }
61867                     else if (prev & meaning) {
61868                         error(location, ts.Diagnostics.Duplicate_identifier_0, ts.getTextOfNode(location));
61869                     }
61870                     else {
61871                         names.set(name, prev | meaning);
61872                     }
61873                 }
61874                 else {
61875                     names.set(name, meaning);
61876                 }
61877             }
61878         }
61879         /**
61880          * Static members being set on a constructor function may conflict with built-in properties
61881          * of Function. Esp. in ECMAScript 5 there are non-configurable and non-writable
61882          * built-in properties. This check issues a transpile error when a class has a static
61883          * member with the same name as a non-writable built-in property.
61884          *
61885          * @see http://www.ecma-international.org/ecma-262/5.1/#sec-15.3.3
61886          * @see http://www.ecma-international.org/ecma-262/5.1/#sec-15.3.5
61887          * @see http://www.ecma-international.org/ecma-262/6.0/#sec-properties-of-the-function-constructor
61888          * @see http://www.ecma-international.org/ecma-262/6.0/#sec-function-instances
61889          */
61890         function checkClassForStaticPropertyNameConflicts(node) {
61891             for (var _i = 0, _a = node.members; _i < _a.length; _i++) {
61892                 var member = _a[_i];
61893                 var memberNameNode = member.name;
61894                 var isStatic = ts.hasModifier(member, 32 /* Static */);
61895                 if (isStatic && memberNameNode) {
61896                     var memberName = ts.getPropertyNameForPropertyNameNode(memberNameNode);
61897                     switch (memberName) {
61898                         case "name":
61899                         case "length":
61900                         case "caller":
61901                         case "arguments":
61902                         case "prototype":
61903                             var message = ts.Diagnostics.Static_property_0_conflicts_with_built_in_property_Function_0_of_constructor_function_1;
61904                             var className = getNameOfSymbolAsWritten(getSymbolOfNode(node));
61905                             error(memberNameNode, message, memberName, className);
61906                             break;
61907                     }
61908                 }
61909             }
61910         }
61911         function checkObjectTypeForDuplicateDeclarations(node) {
61912             var names = ts.createMap();
61913             for (var _i = 0, _a = node.members; _i < _a.length; _i++) {
61914                 var member = _a[_i];
61915                 if (member.kind === 158 /* PropertySignature */) {
61916                     var memberName = void 0;
61917                     var name = member.name;
61918                     switch (name.kind) {
61919                         case 10 /* StringLiteral */:
61920                         case 8 /* NumericLiteral */:
61921                             memberName = name.text;
61922                             break;
61923                         case 75 /* Identifier */:
61924                             memberName = ts.idText(name);
61925                             break;
61926                         default:
61927                             continue;
61928                     }
61929                     if (names.get(memberName)) {
61930                         error(ts.getNameOfDeclaration(member.symbol.valueDeclaration), ts.Diagnostics.Duplicate_identifier_0, memberName);
61931                         error(member.name, ts.Diagnostics.Duplicate_identifier_0, memberName);
61932                     }
61933                     else {
61934                         names.set(memberName, true);
61935                     }
61936                 }
61937             }
61938         }
61939         function checkTypeForDuplicateIndexSignatures(node) {
61940             if (node.kind === 246 /* InterfaceDeclaration */) {
61941                 var nodeSymbol = getSymbolOfNode(node);
61942                 // in case of merging interface declaration it is possible that we'll enter this check procedure several times for every declaration
61943                 // to prevent this run check only for the first declaration of a given kind
61944                 if (nodeSymbol.declarations.length > 0 && nodeSymbol.declarations[0] !== node) {
61945                     return;
61946                 }
61947             }
61948             // TypeScript 1.0 spec (April 2014)
61949             // 3.7.4: An object type can contain at most one string index signature and one numeric index signature.
61950             // 8.5: A class declaration can have at most one string index member declaration and one numeric index member declaration
61951             var indexSymbol = getIndexSymbol(getSymbolOfNode(node));
61952             if (indexSymbol) {
61953                 var seenNumericIndexer = false;
61954                 var seenStringIndexer = false;
61955                 for (var _i = 0, _a = indexSymbol.declarations; _i < _a.length; _i++) {
61956                     var decl = _a[_i];
61957                     var declaration = decl;
61958                     if (declaration.parameters.length === 1 && declaration.parameters[0].type) {
61959                         switch (declaration.parameters[0].type.kind) {
61960                             case 143 /* StringKeyword */:
61961                                 if (!seenStringIndexer) {
61962                                     seenStringIndexer = true;
61963                                 }
61964                                 else {
61965                                     error(declaration, ts.Diagnostics.Duplicate_string_index_signature);
61966                                 }
61967                                 break;
61968                             case 140 /* NumberKeyword */:
61969                                 if (!seenNumericIndexer) {
61970                                     seenNumericIndexer = true;
61971                                 }
61972                                 else {
61973                                     error(declaration, ts.Diagnostics.Duplicate_number_index_signature);
61974                                 }
61975                                 break;
61976                         }
61977                     }
61978                 }
61979             }
61980         }
61981         function checkPropertyDeclaration(node) {
61982             // Grammar checking
61983             if (!checkGrammarDecoratorsAndModifiers(node) && !checkGrammarProperty(node))
61984                 checkGrammarComputedPropertyName(node.name);
61985             checkVariableLikeDeclaration(node);
61986             // Private class fields transformation relies on WeakMaps.
61987             if (ts.isPrivateIdentifier(node.name) && languageVersion < 99 /* ESNext */) {
61988                 for (var lexicalScope = ts.getEnclosingBlockScopeContainer(node); !!lexicalScope; lexicalScope = ts.getEnclosingBlockScopeContainer(lexicalScope)) {
61989                     getNodeLinks(lexicalScope).flags |= 67108864 /* ContainsClassWithPrivateIdentifiers */;
61990                 }
61991             }
61992         }
61993         function checkPropertySignature(node) {
61994             if (ts.isPrivateIdentifier(node.name)) {
61995                 error(node, ts.Diagnostics.Private_identifiers_are_not_allowed_outside_class_bodies);
61996             }
61997             return checkPropertyDeclaration(node);
61998         }
61999         function checkMethodDeclaration(node) {
62000             // Grammar checking
62001             if (!checkGrammarMethod(node))
62002                 checkGrammarComputedPropertyName(node.name);
62003             if (ts.isPrivateIdentifier(node.name)) {
62004                 error(node, ts.Diagnostics.A_method_cannot_be_named_with_a_private_identifier);
62005             }
62006             // Grammar checking for modifiers is done inside the function checkGrammarFunctionLikeDeclaration
62007             checkFunctionOrMethodDeclaration(node);
62008             // Abstract methods cannot have an implementation.
62009             // Extra checks are to avoid reporting multiple errors relating to the "abstractness" of the node.
62010             if (ts.hasModifier(node, 128 /* Abstract */) && node.kind === 161 /* MethodDeclaration */ && node.body) {
62011                 error(node, ts.Diagnostics.Method_0_cannot_have_an_implementation_because_it_is_marked_abstract, ts.declarationNameToString(node.name));
62012             }
62013         }
62014         function checkConstructorDeclaration(node) {
62015             // Grammar check on signature of constructor and modifier of the constructor is done in checkSignatureDeclaration function.
62016             checkSignatureDeclaration(node);
62017             // Grammar check for checking only related to constructorDeclaration
62018             if (!checkGrammarConstructorTypeParameters(node))
62019                 checkGrammarConstructorTypeAnnotation(node);
62020             checkSourceElement(node.body);
62021             var symbol = getSymbolOfNode(node);
62022             var firstDeclaration = ts.getDeclarationOfKind(symbol, node.kind);
62023             // Only type check the symbol once
62024             if (node === firstDeclaration) {
62025                 checkFunctionOrConstructorSymbol(symbol);
62026             }
62027             // exit early in the case of signature - super checks are not relevant to them
62028             if (ts.nodeIsMissing(node.body)) {
62029                 return;
62030             }
62031             if (!produceDiagnostics) {
62032                 return;
62033             }
62034             function isInstancePropertyWithInitializerOrPrivateIdentifierProperty(n) {
62035                 if (ts.isPrivateIdentifierPropertyDeclaration(n)) {
62036                     return true;
62037                 }
62038                 return n.kind === 159 /* PropertyDeclaration */ &&
62039                     !ts.hasModifier(n, 32 /* Static */) &&
62040                     !!n.initializer;
62041             }
62042             // TS 1.0 spec (April 2014): 8.3.2
62043             // Constructors of classes with no extends clause may not contain super calls, whereas
62044             // constructors of derived classes must contain at least one super call somewhere in their function body.
62045             var containingClassDecl = node.parent;
62046             if (ts.getClassExtendsHeritageElement(containingClassDecl)) {
62047                 captureLexicalThis(node.parent, containingClassDecl);
62048                 var classExtendsNull = classDeclarationExtendsNull(containingClassDecl);
62049                 var superCall = getSuperCallInConstructor(node);
62050                 if (superCall) {
62051                     if (classExtendsNull) {
62052                         error(superCall, ts.Diagnostics.A_constructor_cannot_contain_a_super_call_when_its_class_extends_null);
62053                     }
62054                     // The first statement in the body of a constructor (excluding prologue directives) must be a super call
62055                     // if both of the following are true:
62056                     // - The containing class is a derived class.
62057                     // - The constructor declares parameter properties
62058                     //   or the containing class declares instance member variables with initializers.
62059                     var superCallShouldBeFirst = (compilerOptions.target !== 99 /* ESNext */ || !compilerOptions.useDefineForClassFields) &&
62060                         (ts.some(node.parent.members, isInstancePropertyWithInitializerOrPrivateIdentifierProperty) ||
62061                             ts.some(node.parameters, function (p) { return ts.hasModifier(p, 92 /* ParameterPropertyModifier */); }));
62062                     // Skip past any prologue directives to find the first statement
62063                     // to ensure that it was a super call.
62064                     if (superCallShouldBeFirst) {
62065                         var statements = node.body.statements;
62066                         var superCallStatement = void 0;
62067                         for (var _i = 0, statements_3 = statements; _i < statements_3.length; _i++) {
62068                             var statement = statements_3[_i];
62069                             if (statement.kind === 226 /* ExpressionStatement */ && ts.isSuperCall(statement.expression)) {
62070                                 superCallStatement = statement;
62071                                 break;
62072                             }
62073                             if (!ts.isPrologueDirective(statement)) {
62074                                 break;
62075                             }
62076                         }
62077                         if (!superCallStatement) {
62078                             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);
62079                         }
62080                     }
62081                 }
62082                 else if (!classExtendsNull) {
62083                     error(node, ts.Diagnostics.Constructors_for_derived_classes_must_contain_a_super_call);
62084                 }
62085             }
62086         }
62087         function checkAccessorDeclaration(node) {
62088             if (produceDiagnostics) {
62089                 // Grammar checking accessors
62090                 if (!checkGrammarFunctionLikeDeclaration(node) && !checkGrammarAccessor(node))
62091                     checkGrammarComputedPropertyName(node.name);
62092                 checkDecorators(node);
62093                 checkSignatureDeclaration(node);
62094                 if (node.kind === 163 /* GetAccessor */) {
62095                     if (!(node.flags & 8388608 /* Ambient */) && ts.nodeIsPresent(node.body) && (node.flags & 256 /* HasImplicitReturn */)) {
62096                         if (!(node.flags & 512 /* HasExplicitReturn */)) {
62097                             error(node.name, ts.Diagnostics.A_get_accessor_must_return_a_value);
62098                         }
62099                     }
62100                 }
62101                 // Do not use hasDynamicName here, because that returns false for well known symbols.
62102                 // We want to perform checkComputedPropertyName for all computed properties, including
62103                 // well known symbols.
62104                 if (node.name.kind === 154 /* ComputedPropertyName */) {
62105                     checkComputedPropertyName(node.name);
62106                 }
62107                 if (ts.isPrivateIdentifier(node.name)) {
62108                     error(node.name, ts.Diagnostics.An_accessor_cannot_be_named_with_a_private_identifier);
62109                 }
62110                 if (!hasNonBindableDynamicName(node)) {
62111                     // TypeScript 1.0 spec (April 2014): 8.4.3
62112                     // Accessors for the same member name must specify the same accessibility.
62113                     var otherKind = node.kind === 163 /* GetAccessor */ ? 164 /* SetAccessor */ : 163 /* GetAccessor */;
62114                     var otherAccessor = ts.getDeclarationOfKind(getSymbolOfNode(node), otherKind);
62115                     if (otherAccessor) {
62116                         var nodeFlags = ts.getModifierFlags(node);
62117                         var otherFlags = ts.getModifierFlags(otherAccessor);
62118                         if ((nodeFlags & 28 /* AccessibilityModifier */) !== (otherFlags & 28 /* AccessibilityModifier */)) {
62119                             error(node.name, ts.Diagnostics.Getter_and_setter_accessors_do_not_agree_in_visibility);
62120                         }
62121                         if ((nodeFlags & 128 /* Abstract */) !== (otherFlags & 128 /* Abstract */)) {
62122                             error(node.name, ts.Diagnostics.Accessors_must_both_be_abstract_or_non_abstract);
62123                         }
62124                         // TypeScript 1.0 spec (April 2014): 4.5
62125                         // If both accessors include type annotations, the specified types must be identical.
62126                         checkAccessorDeclarationTypesIdentical(node, otherAccessor, getAnnotatedAccessorType, ts.Diagnostics.get_and_set_accessor_must_have_the_same_type);
62127                         checkAccessorDeclarationTypesIdentical(node, otherAccessor, getThisTypeOfDeclaration, ts.Diagnostics.get_and_set_accessor_must_have_the_same_this_type);
62128                     }
62129                 }
62130                 var returnType = getTypeOfAccessors(getSymbolOfNode(node));
62131                 if (node.kind === 163 /* GetAccessor */) {
62132                     checkAllCodePathsInNonVoidFunctionReturnOrThrow(node, returnType);
62133                 }
62134             }
62135             checkSourceElement(node.body);
62136         }
62137         function checkAccessorDeclarationTypesIdentical(first, second, getAnnotatedType, message) {
62138             var firstType = getAnnotatedType(first);
62139             var secondType = getAnnotatedType(second);
62140             if (firstType && secondType && !isTypeIdenticalTo(firstType, secondType)) {
62141                 error(first, message);
62142             }
62143         }
62144         function checkMissingDeclaration(node) {
62145             checkDecorators(node);
62146         }
62147         function getEffectiveTypeArguments(node, typeParameters) {
62148             return fillMissingTypeArguments(ts.map(node.typeArguments, getTypeFromTypeNode), typeParameters, getMinTypeArgumentCount(typeParameters), ts.isInJSFile(node));
62149         }
62150         function checkTypeArgumentConstraints(node, typeParameters) {
62151             var typeArguments;
62152             var mapper;
62153             var result = true;
62154             for (var i = 0; i < typeParameters.length; i++) {
62155                 var constraint = getConstraintOfTypeParameter(typeParameters[i]);
62156                 if (constraint) {
62157                     if (!typeArguments) {
62158                         typeArguments = getEffectiveTypeArguments(node, typeParameters);
62159                         mapper = createTypeMapper(typeParameters, typeArguments);
62160                     }
62161                     result = result && checkTypeAssignableTo(typeArguments[i], instantiateType(constraint, mapper), node.typeArguments[i], ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1);
62162                 }
62163             }
62164             return result;
62165         }
62166         function getTypeParametersForTypeReference(node) {
62167             var type = getTypeFromTypeReference(node);
62168             if (type !== errorType) {
62169                 var symbol = getNodeLinks(node).resolvedSymbol;
62170                 if (symbol) {
62171                     return symbol.flags & 524288 /* TypeAlias */ && getSymbolLinks(symbol).typeParameters ||
62172                         (ts.getObjectFlags(type) & 4 /* Reference */ ? type.target.localTypeParameters : undefined);
62173                 }
62174             }
62175             return undefined;
62176         }
62177         function checkTypeReferenceNode(node) {
62178             checkGrammarTypeArguments(node, node.typeArguments);
62179             if (node.kind === 169 /* TypeReference */ && node.typeName.jsdocDotPos !== undefined && !ts.isInJSFile(node) && !ts.isInJSDoc(node)) {
62180                 grammarErrorAtPos(node, node.typeName.jsdocDotPos, 1, ts.Diagnostics.JSDoc_types_can_only_be_used_inside_documentation_comments);
62181             }
62182             ts.forEach(node.typeArguments, checkSourceElement);
62183             var type = getTypeFromTypeReference(node);
62184             if (type !== errorType) {
62185                 if (node.typeArguments && produceDiagnostics) {
62186                     var typeParameters = getTypeParametersForTypeReference(node);
62187                     if (typeParameters) {
62188                         checkTypeArgumentConstraints(node, typeParameters);
62189                     }
62190                 }
62191                 if (type.flags & 32 /* Enum */ && getNodeLinks(node).resolvedSymbol.flags & 8 /* EnumMember */) {
62192                     error(node, ts.Diagnostics.Enum_type_0_has_members_with_initializers_that_are_not_literals, typeToString(type));
62193                 }
62194             }
62195         }
62196         function getTypeArgumentConstraint(node) {
62197             var typeReferenceNode = ts.tryCast(node.parent, ts.isTypeReferenceType);
62198             if (!typeReferenceNode)
62199                 return undefined;
62200             var typeParameters = getTypeParametersForTypeReference(typeReferenceNode); // TODO: GH#18217
62201             var constraint = getConstraintOfTypeParameter(typeParameters[typeReferenceNode.typeArguments.indexOf(node)]);
62202             return constraint && instantiateType(constraint, createTypeMapper(typeParameters, getEffectiveTypeArguments(typeReferenceNode, typeParameters)));
62203         }
62204         function checkTypeQuery(node) {
62205             getTypeFromTypeQueryNode(node);
62206         }
62207         function checkTypeLiteral(node) {
62208             ts.forEach(node.members, checkSourceElement);
62209             if (produceDiagnostics) {
62210                 var type = getTypeFromTypeLiteralOrFunctionOrConstructorTypeNode(node);
62211                 checkIndexConstraints(type);
62212                 checkTypeForDuplicateIndexSignatures(node);
62213                 checkObjectTypeForDuplicateDeclarations(node);
62214             }
62215         }
62216         function checkArrayType(node) {
62217             checkSourceElement(node.elementType);
62218         }
62219         function checkTupleType(node) {
62220             var elementTypes = node.elementTypes;
62221             var seenOptionalElement = false;
62222             for (var i = 0; i < elementTypes.length; i++) {
62223                 var e = elementTypes[i];
62224                 if (e.kind === 177 /* RestType */) {
62225                     if (i !== elementTypes.length - 1) {
62226                         grammarErrorOnNode(e, ts.Diagnostics.A_rest_element_must_be_last_in_a_tuple_type);
62227                         break;
62228                     }
62229                     if (!isArrayType(getTypeFromTypeNode(e.type))) {
62230                         error(e, ts.Diagnostics.A_rest_element_type_must_be_an_array_type);
62231                     }
62232                 }
62233                 else if (e.kind === 176 /* OptionalType */) {
62234                     seenOptionalElement = true;
62235                 }
62236                 else if (seenOptionalElement) {
62237                     grammarErrorOnNode(e, ts.Diagnostics.A_required_element_cannot_follow_an_optional_element);
62238                     break;
62239                 }
62240             }
62241             ts.forEach(node.elementTypes, checkSourceElement);
62242         }
62243         function checkUnionOrIntersectionType(node) {
62244             ts.forEach(node.types, checkSourceElement);
62245         }
62246         function checkIndexedAccessIndexType(type, accessNode) {
62247             if (!(type.flags & 8388608 /* IndexedAccess */)) {
62248                 return type;
62249             }
62250             // Check if the index type is assignable to 'keyof T' for the object type.
62251             var objectType = type.objectType;
62252             var indexType = type.indexType;
62253             if (isTypeAssignableTo(indexType, getIndexType(objectType, /*stringsOnly*/ false))) {
62254                 if (accessNode.kind === 195 /* ElementAccessExpression */ && ts.isAssignmentTarget(accessNode) &&
62255                     ts.getObjectFlags(objectType) & 32 /* Mapped */ && getMappedTypeModifiers(objectType) & 1 /* IncludeReadonly */) {
62256                     error(accessNode, ts.Diagnostics.Index_signature_in_type_0_only_permits_reading, typeToString(objectType));
62257                 }
62258                 return type;
62259             }
62260             // Check if we're indexing with a numeric type and if either object or index types
62261             // is a generic type with a constraint that has a numeric index signature.
62262             var apparentObjectType = getApparentType(objectType);
62263             if (getIndexInfoOfType(apparentObjectType, 1 /* Number */) && isTypeAssignableToKind(indexType, 296 /* NumberLike */)) {
62264                 return type;
62265             }
62266             if (isGenericObjectType(objectType)) {
62267                 var propertyName_1 = getPropertyNameFromIndex(indexType, accessNode);
62268                 if (propertyName_1) {
62269                     var propertySymbol = forEachType(apparentObjectType, function (t) { return getPropertyOfType(t, propertyName_1); });
62270                     if (propertySymbol && ts.getDeclarationModifierFlagsFromSymbol(propertySymbol) & 24 /* NonPublicAccessibilityModifier */) {
62271                         error(accessNode, ts.Diagnostics.Private_or_protected_member_0_cannot_be_accessed_on_a_type_parameter, ts.unescapeLeadingUnderscores(propertyName_1));
62272                         return errorType;
62273                     }
62274                 }
62275             }
62276             error(accessNode, ts.Diagnostics.Type_0_cannot_be_used_to_index_type_1, typeToString(indexType), typeToString(objectType));
62277             return errorType;
62278         }
62279         function checkIndexedAccessType(node) {
62280             checkSourceElement(node.objectType);
62281             checkSourceElement(node.indexType);
62282             checkIndexedAccessIndexType(getTypeFromIndexedAccessTypeNode(node), node);
62283         }
62284         function checkMappedType(node) {
62285             checkSourceElement(node.typeParameter);
62286             checkSourceElement(node.type);
62287             if (!node.type) {
62288                 reportImplicitAny(node, anyType);
62289             }
62290             var type = getTypeFromMappedTypeNode(node);
62291             var constraintType = getConstraintTypeFromMappedType(type);
62292             checkTypeAssignableTo(constraintType, keyofConstraintType, ts.getEffectiveConstraintOfTypeParameter(node.typeParameter));
62293         }
62294         function checkThisType(node) {
62295             getTypeFromThisTypeNode(node);
62296         }
62297         function checkTypeOperator(node) {
62298             checkGrammarTypeOperatorNode(node);
62299             checkSourceElement(node.type);
62300         }
62301         function checkConditionalType(node) {
62302             ts.forEachChild(node, checkSourceElement);
62303         }
62304         function checkInferType(node) {
62305             if (!ts.findAncestor(node, function (n) { return n.parent && n.parent.kind === 180 /* ConditionalType */ && n.parent.extendsType === n; })) {
62306                 grammarErrorOnNode(node, ts.Diagnostics.infer_declarations_are_only_permitted_in_the_extends_clause_of_a_conditional_type);
62307             }
62308             checkSourceElement(node.typeParameter);
62309             registerForUnusedIdentifiersCheck(node);
62310         }
62311         function checkImportType(node) {
62312             checkSourceElement(node.argument);
62313             getTypeFromTypeNode(node);
62314         }
62315         function isPrivateWithinAmbient(node) {
62316             return (ts.hasModifier(node, 8 /* Private */) || ts.isPrivateIdentifierPropertyDeclaration(node)) && !!(node.flags & 8388608 /* Ambient */);
62317         }
62318         function getEffectiveDeclarationFlags(n, flagsToCheck) {
62319             var flags = ts.getCombinedModifierFlags(n);
62320             // children of classes (even ambient classes) should not be marked as ambient or export
62321             // because those flags have no useful semantics there.
62322             if (n.parent.kind !== 246 /* InterfaceDeclaration */ &&
62323                 n.parent.kind !== 245 /* ClassDeclaration */ &&
62324                 n.parent.kind !== 214 /* ClassExpression */ &&
62325                 n.flags & 8388608 /* Ambient */) {
62326                 if (!(flags & 2 /* Ambient */) && !(ts.isModuleBlock(n.parent) && ts.isModuleDeclaration(n.parent.parent) && ts.isGlobalScopeAugmentation(n.parent.parent))) {
62327                     // It is nested in an ambient context, which means it is automatically exported
62328                     flags |= 1 /* Export */;
62329                 }
62330                 flags |= 2 /* Ambient */;
62331             }
62332             return flags & flagsToCheck;
62333         }
62334         function checkFunctionOrConstructorSymbol(symbol) {
62335             if (!produceDiagnostics) {
62336                 return;
62337             }
62338             function getCanonicalOverload(overloads, implementation) {
62339                 // Consider the canonical set of flags to be the flags of the bodyDeclaration or the first declaration
62340                 // Error on all deviations from this canonical set of flags
62341                 // The caveat is that if some overloads are defined in lib.d.ts, we don't want to
62342                 // report the errors on those. To achieve this, we will say that the implementation is
62343                 // the canonical signature only if it is in the same container as the first overload
62344                 var implementationSharesContainerWithFirstOverload = implementation !== undefined && implementation.parent === overloads[0].parent;
62345                 return implementationSharesContainerWithFirstOverload ? implementation : overloads[0];
62346             }
62347             function checkFlagAgreementBetweenOverloads(overloads, implementation, flagsToCheck, someOverloadFlags, allOverloadFlags) {
62348                 // Error if some overloads have a flag that is not shared by all overloads. To find the
62349                 // deviations, we XOR someOverloadFlags with allOverloadFlags
62350                 var someButNotAllOverloadFlags = someOverloadFlags ^ allOverloadFlags;
62351                 if (someButNotAllOverloadFlags !== 0) {
62352                     var canonicalFlags_1 = getEffectiveDeclarationFlags(getCanonicalOverload(overloads, implementation), flagsToCheck);
62353                     ts.forEach(overloads, function (o) {
62354                         var deviation = getEffectiveDeclarationFlags(o, flagsToCheck) ^ canonicalFlags_1;
62355                         if (deviation & 1 /* Export */) {
62356                             error(ts.getNameOfDeclaration(o), ts.Diagnostics.Overload_signatures_must_all_be_exported_or_non_exported);
62357                         }
62358                         else if (deviation & 2 /* Ambient */) {
62359                             error(ts.getNameOfDeclaration(o), ts.Diagnostics.Overload_signatures_must_all_be_ambient_or_non_ambient);
62360                         }
62361                         else if (deviation & (8 /* Private */ | 16 /* Protected */)) {
62362                             error(ts.getNameOfDeclaration(o) || o, ts.Diagnostics.Overload_signatures_must_all_be_public_private_or_protected);
62363                         }
62364                         else if (deviation & 128 /* Abstract */) {
62365                             error(ts.getNameOfDeclaration(o), ts.Diagnostics.Overload_signatures_must_all_be_abstract_or_non_abstract);
62366                         }
62367                     });
62368                 }
62369             }
62370             function checkQuestionTokenAgreementBetweenOverloads(overloads, implementation, someHaveQuestionToken, allHaveQuestionToken) {
62371                 if (someHaveQuestionToken !== allHaveQuestionToken) {
62372                     var canonicalHasQuestionToken_1 = ts.hasQuestionToken(getCanonicalOverload(overloads, implementation));
62373                     ts.forEach(overloads, function (o) {
62374                         var deviation = ts.hasQuestionToken(o) !== canonicalHasQuestionToken_1;
62375                         if (deviation) {
62376                             error(ts.getNameOfDeclaration(o), ts.Diagnostics.Overload_signatures_must_all_be_optional_or_required);
62377                         }
62378                     });
62379                 }
62380             }
62381             var flagsToCheck = 1 /* Export */ | 2 /* Ambient */ | 8 /* Private */ | 16 /* Protected */ | 128 /* Abstract */;
62382             var someNodeFlags = 0 /* None */;
62383             var allNodeFlags = flagsToCheck;
62384             var someHaveQuestionToken = false;
62385             var allHaveQuestionToken = true;
62386             var hasOverloads = false;
62387             var bodyDeclaration;
62388             var lastSeenNonAmbientDeclaration;
62389             var previousDeclaration;
62390             var declarations = symbol.declarations;
62391             var isConstructor = (symbol.flags & 16384 /* Constructor */) !== 0;
62392             function reportImplementationExpectedError(node) {
62393                 if (node.name && ts.nodeIsMissing(node.name)) {
62394                     return;
62395                 }
62396                 var seen = false;
62397                 var subsequentNode = ts.forEachChild(node.parent, function (c) {
62398                     if (seen) {
62399                         return c;
62400                     }
62401                     else {
62402                         seen = c === node;
62403                     }
62404                 });
62405                 // We may be here because of some extra nodes between overloads that could not be parsed into a valid node.
62406                 // In this case the subsequent node is not really consecutive (.pos !== node.end), and we must ignore it here.
62407                 if (subsequentNode && subsequentNode.pos === node.end) {
62408                     if (subsequentNode.kind === node.kind) {
62409                         var errorNode_1 = subsequentNode.name || subsequentNode;
62410                         var subsequentName = subsequentNode.name;
62411                         if (node.name && subsequentName && (
62412                         // both are private identifiers
62413                         ts.isPrivateIdentifier(node.name) && ts.isPrivateIdentifier(subsequentName) && node.name.escapedText === subsequentName.escapedText ||
62414                             // Both are computed property names
62415                             // TODO: GH#17345: These are methods, so handle computed name case. (`Always allowing computed property names is *not* the correct behavior!)
62416                             ts.isComputedPropertyName(node.name) && ts.isComputedPropertyName(subsequentName) ||
62417                             // Both are literal property names that are the same.
62418                             ts.isPropertyNameLiteral(node.name) && ts.isPropertyNameLiteral(subsequentName) &&
62419                                 ts.getEscapedTextOfIdentifierOrLiteral(node.name) === ts.getEscapedTextOfIdentifierOrLiteral(subsequentName))) {
62420                             var reportError = (node.kind === 161 /* MethodDeclaration */ || node.kind === 160 /* MethodSignature */) &&
62421                                 ts.hasModifier(node, 32 /* Static */) !== ts.hasModifier(subsequentNode, 32 /* Static */);
62422                             // we can get here in two cases
62423                             // 1. mixed static and instance class members
62424                             // 2. something with the same name was defined before the set of overloads that prevents them from merging
62425                             // here we'll report error only for the first case since for second we should already report error in binder
62426                             if (reportError) {
62427                                 var diagnostic = ts.hasModifier(node, 32 /* Static */) ? ts.Diagnostics.Function_overload_must_be_static : ts.Diagnostics.Function_overload_must_not_be_static;
62428                                 error(errorNode_1, diagnostic);
62429                             }
62430                             return;
62431                         }
62432                         if (ts.nodeIsPresent(subsequentNode.body)) {
62433                             error(errorNode_1, ts.Diagnostics.Function_implementation_name_must_be_0, ts.declarationNameToString(node.name));
62434                             return;
62435                         }
62436                     }
62437                 }
62438                 var errorNode = node.name || node;
62439                 if (isConstructor) {
62440                     error(errorNode, ts.Diagnostics.Constructor_implementation_is_missing);
62441                 }
62442                 else {
62443                     // Report different errors regarding non-consecutive blocks of declarations depending on whether
62444                     // the node in question is abstract.
62445                     if (ts.hasModifier(node, 128 /* Abstract */)) {
62446                         error(errorNode, ts.Diagnostics.All_declarations_of_an_abstract_method_must_be_consecutive);
62447                     }
62448                     else {
62449                         error(errorNode, ts.Diagnostics.Function_implementation_is_missing_or_not_immediately_following_the_declaration);
62450                     }
62451                 }
62452             }
62453             var duplicateFunctionDeclaration = false;
62454             var multipleConstructorImplementation = false;
62455             var hasNonAmbientClass = false;
62456             for (var _i = 0, declarations_4 = declarations; _i < declarations_4.length; _i++) {
62457                 var current = declarations_4[_i];
62458                 var node = current;
62459                 var inAmbientContext = node.flags & 8388608 /* Ambient */;
62460                 var inAmbientContextOrInterface = node.parent.kind === 246 /* InterfaceDeclaration */ || node.parent.kind === 173 /* TypeLiteral */ || inAmbientContext;
62461                 if (inAmbientContextOrInterface) {
62462                     // check if declarations are consecutive only if they are non-ambient
62463                     // 1. ambient declarations can be interleaved
62464                     // i.e. this is legal
62465                     //     declare function foo();
62466                     //     declare function bar();
62467                     //     declare function foo();
62468                     // 2. mixing ambient and non-ambient declarations is a separate error that will be reported - do not want to report an extra one
62469                     previousDeclaration = undefined;
62470                 }
62471                 if ((node.kind === 245 /* ClassDeclaration */ || node.kind === 214 /* ClassExpression */) && !inAmbientContext) {
62472                     hasNonAmbientClass = true;
62473                 }
62474                 if (node.kind === 244 /* FunctionDeclaration */ || node.kind === 161 /* MethodDeclaration */ || node.kind === 160 /* MethodSignature */ || node.kind === 162 /* Constructor */) {
62475                     var currentNodeFlags = getEffectiveDeclarationFlags(node, flagsToCheck);
62476                     someNodeFlags |= currentNodeFlags;
62477                     allNodeFlags &= currentNodeFlags;
62478                     someHaveQuestionToken = someHaveQuestionToken || ts.hasQuestionToken(node);
62479                     allHaveQuestionToken = allHaveQuestionToken && ts.hasQuestionToken(node);
62480                     if (ts.nodeIsPresent(node.body) && bodyDeclaration) {
62481                         if (isConstructor) {
62482                             multipleConstructorImplementation = true;
62483                         }
62484                         else {
62485                             duplicateFunctionDeclaration = true;
62486                         }
62487                     }
62488                     else if (previousDeclaration && previousDeclaration.parent === node.parent && previousDeclaration.end !== node.pos) {
62489                         reportImplementationExpectedError(previousDeclaration);
62490                     }
62491                     if (ts.nodeIsPresent(node.body)) {
62492                         if (!bodyDeclaration) {
62493                             bodyDeclaration = node;
62494                         }
62495                     }
62496                     else {
62497                         hasOverloads = true;
62498                     }
62499                     previousDeclaration = node;
62500                     if (!inAmbientContextOrInterface) {
62501                         lastSeenNonAmbientDeclaration = node;
62502                     }
62503                 }
62504             }
62505             if (multipleConstructorImplementation) {
62506                 ts.forEach(declarations, function (declaration) {
62507                     error(declaration, ts.Diagnostics.Multiple_constructor_implementations_are_not_allowed);
62508                 });
62509             }
62510             if (duplicateFunctionDeclaration) {
62511                 ts.forEach(declarations, function (declaration) {
62512                     error(ts.getNameOfDeclaration(declaration), ts.Diagnostics.Duplicate_function_implementation);
62513                 });
62514             }
62515             if (hasNonAmbientClass && !isConstructor && symbol.flags & 16 /* Function */) {
62516                 // A non-ambient class cannot be an implementation for a non-constructor function/class merge
62517                 // TODO: The below just replicates our older error from when classes and functions were
62518                 // entirely unable to merge - a more helpful message like "Class declaration cannot implement overload list"
62519                 // might be warranted. :shrug:
62520                 ts.forEach(declarations, function (declaration) {
62521                     addDuplicateDeclarationError(declaration, ts.Diagnostics.Duplicate_identifier_0, ts.symbolName(symbol), declarations);
62522                 });
62523             }
62524             // Abstract methods can't have an implementation -- in particular, they don't need one.
62525             if (lastSeenNonAmbientDeclaration && !lastSeenNonAmbientDeclaration.body &&
62526                 !ts.hasModifier(lastSeenNonAmbientDeclaration, 128 /* Abstract */) && !lastSeenNonAmbientDeclaration.questionToken) {
62527                 reportImplementationExpectedError(lastSeenNonAmbientDeclaration);
62528             }
62529             if (hasOverloads) {
62530                 checkFlagAgreementBetweenOverloads(declarations, bodyDeclaration, flagsToCheck, someNodeFlags, allNodeFlags);
62531                 checkQuestionTokenAgreementBetweenOverloads(declarations, bodyDeclaration, someHaveQuestionToken, allHaveQuestionToken);
62532                 if (bodyDeclaration) {
62533                     var signatures = getSignaturesOfSymbol(symbol);
62534                     var bodySignature = getSignatureFromDeclaration(bodyDeclaration);
62535                     for (var _a = 0, signatures_10 = signatures; _a < signatures_10.length; _a++) {
62536                         var signature = signatures_10[_a];
62537                         if (!isImplementationCompatibleWithOverload(bodySignature, signature)) {
62538                             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));
62539                             break;
62540                         }
62541                     }
62542                 }
62543             }
62544         }
62545         function checkExportsOnMergedDeclarations(node) {
62546             if (!produceDiagnostics) {
62547                 return;
62548             }
62549             // if localSymbol is defined on node then node itself is exported - check is required
62550             var symbol = node.localSymbol;
62551             if (!symbol) {
62552                 // local symbol is undefined => this declaration is non-exported.
62553                 // however symbol might contain other declarations that are exported
62554                 symbol = getSymbolOfNode(node);
62555                 if (!symbol.exportSymbol) {
62556                     // this is a pure local symbol (all declarations are non-exported) - no need to check anything
62557                     return;
62558                 }
62559             }
62560             // run the check only for the first declaration in the list
62561             if (ts.getDeclarationOfKind(symbol, node.kind) !== node) {
62562                 return;
62563             }
62564             var exportedDeclarationSpaces = 0 /* None */;
62565             var nonExportedDeclarationSpaces = 0 /* None */;
62566             var defaultExportedDeclarationSpaces = 0 /* None */;
62567             for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) {
62568                 var d = _a[_i];
62569                 var declarationSpaces = getDeclarationSpaces(d);
62570                 var effectiveDeclarationFlags = getEffectiveDeclarationFlags(d, 1 /* Export */ | 512 /* Default */);
62571                 if (effectiveDeclarationFlags & 1 /* Export */) {
62572                     if (effectiveDeclarationFlags & 512 /* Default */) {
62573                         defaultExportedDeclarationSpaces |= declarationSpaces;
62574                     }
62575                     else {
62576                         exportedDeclarationSpaces |= declarationSpaces;
62577                     }
62578                 }
62579                 else {
62580                     nonExportedDeclarationSpaces |= declarationSpaces;
62581                 }
62582             }
62583             // Spaces for anything not declared a 'default export'.
62584             var nonDefaultExportedDeclarationSpaces = exportedDeclarationSpaces | nonExportedDeclarationSpaces;
62585             var commonDeclarationSpacesForExportsAndLocals = exportedDeclarationSpaces & nonExportedDeclarationSpaces;
62586             var commonDeclarationSpacesForDefaultAndNonDefault = defaultExportedDeclarationSpaces & nonDefaultExportedDeclarationSpaces;
62587             if (commonDeclarationSpacesForExportsAndLocals || commonDeclarationSpacesForDefaultAndNonDefault) {
62588                 // declaration spaces for exported and non-exported declarations intersect
62589                 for (var _b = 0, _c = symbol.declarations; _b < _c.length; _b++) {
62590                     var d = _c[_b];
62591                     var declarationSpaces = getDeclarationSpaces(d);
62592                     var name = ts.getNameOfDeclaration(d);
62593                     // Only error on the declarations that contributed to the intersecting spaces.
62594                     if (declarationSpaces & commonDeclarationSpacesForDefaultAndNonDefault) {
62595                         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));
62596                     }
62597                     else if (declarationSpaces & commonDeclarationSpacesForExportsAndLocals) {
62598                         error(name, ts.Diagnostics.Individual_declarations_in_merged_declaration_0_must_be_all_exported_or_all_local, ts.declarationNameToString(name));
62599                     }
62600                 }
62601             }
62602             function getDeclarationSpaces(decl) {
62603                 var d = decl;
62604                 switch (d.kind) {
62605                     case 246 /* InterfaceDeclaration */:
62606                     case 247 /* TypeAliasDeclaration */:
62607                     // A jsdoc typedef and callback are, by definition, type aliases.
62608                     // falls through
62609                     case 322 /* JSDocTypedefTag */:
62610                     case 315 /* JSDocCallbackTag */:
62611                     case 316 /* JSDocEnumTag */:
62612                         return 2 /* ExportType */;
62613                     case 249 /* ModuleDeclaration */:
62614                         return ts.isAmbientModule(d) || ts.getModuleInstanceState(d) !== 0 /* NonInstantiated */
62615                             ? 4 /* ExportNamespace */ | 1 /* ExportValue */
62616                             : 4 /* ExportNamespace */;
62617                     case 245 /* ClassDeclaration */:
62618                     case 248 /* EnumDeclaration */:
62619                     case 284 /* EnumMember */:
62620                         return 2 /* ExportType */ | 1 /* ExportValue */;
62621                     case 290 /* SourceFile */:
62622                         return 2 /* ExportType */ | 1 /* ExportValue */ | 4 /* ExportNamespace */;
62623                     case 259 /* ExportAssignment */:
62624                         // Export assigned entity name expressions act as aliases and should fall through, otherwise they export values
62625                         if (!ts.isEntityNameExpression(d.expression)) {
62626                             return 1 /* ExportValue */;
62627                         }
62628                         d = d.expression;
62629                     // The below options all declare an Alias, which is allowed to merge with other values within the importing module.
62630                     // falls through
62631                     case 253 /* ImportEqualsDeclaration */:
62632                     case 256 /* NamespaceImport */:
62633                     case 255 /* ImportClause */:
62634                         var result_10 = 0 /* None */;
62635                         var target = resolveAlias(getSymbolOfNode(d));
62636                         ts.forEach(target.declarations, function (d) { result_10 |= getDeclarationSpaces(d); });
62637                         return result_10;
62638                     case 242 /* VariableDeclaration */:
62639                     case 191 /* BindingElement */:
62640                     case 244 /* FunctionDeclaration */:
62641                     case 258 /* ImportSpecifier */: // https://github.com/Microsoft/TypeScript/pull/7591
62642                     case 75 /* Identifier */: // https://github.com/microsoft/TypeScript/issues/36098
62643                         // Identifiers are used as declarations of assignment declarations whose parents may be
62644                         // SyntaxKind.CallExpression - `Object.defineProperty(thing, "aField", {value: 42});`
62645                         // SyntaxKind.ElementAccessExpression - `thing["aField"] = 42;` or `thing["aField"];` (with a doc comment on it)
62646                         // or SyntaxKind.PropertyAccessExpression - `thing.aField = 42;`
62647                         // all of which are pretty much always values, or at least imply a value meaning.
62648                         // It may be apprpriate to treat these as aliases in the future.
62649                         return 1 /* ExportValue */;
62650                     default:
62651                         return ts.Debug.failBadSyntaxKind(d);
62652                 }
62653             }
62654         }
62655         function getAwaitedTypeOfPromise(type, errorNode, diagnosticMessage, arg0) {
62656             var promisedType = getPromisedTypeOfPromise(type, errorNode);
62657             return promisedType && getAwaitedType(promisedType, errorNode, diagnosticMessage, arg0);
62658         }
62659         /**
62660          * Gets the "promised type" of a promise.
62661          * @param type The type of the promise.
62662          * @remarks The "promised type" of a type is the type of the "value" parameter of the "onfulfilled" callback.
62663          */
62664         function getPromisedTypeOfPromise(type, errorNode) {
62665             //
62666             //  { // type
62667             //      then( // thenFunction
62668             //          onfulfilled: ( // onfulfilledParameterType
62669             //              value: T // valueParameterType
62670             //          ) => any
62671             //      ): any;
62672             //  }
62673             //
62674             if (isTypeAny(type)) {
62675                 return undefined;
62676             }
62677             var typeAsPromise = type;
62678             if (typeAsPromise.promisedTypeOfPromise) {
62679                 return typeAsPromise.promisedTypeOfPromise;
62680             }
62681             if (isReferenceToType(type, getGlobalPromiseType(/*reportErrors*/ false))) {
62682                 return typeAsPromise.promisedTypeOfPromise = getTypeArguments(type)[0];
62683             }
62684             var thenFunction = getTypeOfPropertyOfType(type, "then"); // TODO: GH#18217
62685             if (isTypeAny(thenFunction)) {
62686                 return undefined;
62687             }
62688             var thenSignatures = thenFunction ? getSignaturesOfType(thenFunction, 0 /* Call */) : ts.emptyArray;
62689             if (thenSignatures.length === 0) {
62690                 if (errorNode) {
62691                     error(errorNode, ts.Diagnostics.A_promise_must_have_a_then_method);
62692                 }
62693                 return undefined;
62694             }
62695             var onfulfilledParameterType = getTypeWithFacts(getUnionType(ts.map(thenSignatures, getTypeOfFirstParameterOfSignature)), 2097152 /* NEUndefinedOrNull */);
62696             if (isTypeAny(onfulfilledParameterType)) {
62697                 return undefined;
62698             }
62699             var onfulfilledParameterSignatures = getSignaturesOfType(onfulfilledParameterType, 0 /* Call */);
62700             if (onfulfilledParameterSignatures.length === 0) {
62701                 if (errorNode) {
62702                     error(errorNode, ts.Diagnostics.The_first_parameter_of_the_then_method_of_a_promise_must_be_a_callback);
62703                 }
62704                 return undefined;
62705             }
62706             return typeAsPromise.promisedTypeOfPromise = getUnionType(ts.map(onfulfilledParameterSignatures, getTypeOfFirstParameterOfSignature), 2 /* Subtype */);
62707         }
62708         /**
62709          * Gets the "awaited type" of a type.
62710          * @param type The type to await.
62711          * @remarks The "awaited type" of an expression is its "promised type" if the expression is a
62712          * Promise-like type; otherwise, it is the type of the expression. This is used to reflect
62713          * The runtime behavior of the `await` keyword.
62714          */
62715         function checkAwaitedType(type, errorNode, diagnosticMessage, arg0) {
62716             var awaitedType = getAwaitedType(type, errorNode, diagnosticMessage, arg0);
62717             return awaitedType || errorType;
62718         }
62719         /**
62720          * Determines whether a type has a callable `then` member.
62721          */
62722         function isThenableType(type) {
62723             var thenFunction = getTypeOfPropertyOfType(type, "then");
62724             return !!thenFunction && getSignaturesOfType(getTypeWithFacts(thenFunction, 2097152 /* NEUndefinedOrNull */), 0 /* Call */).length > 0;
62725         }
62726         /**
62727          * Gets the "awaited type" of a type.
62728          *
62729          * The "awaited type" of an expression is its "promised type" if the expression is a
62730          * Promise-like type; otherwise, it is the type of the expression. If the "promised
62731          * type" is itself a Promise-like, the "promised type" is recursively unwrapped until a
62732          * non-promise type is found.
62733          *
62734          * This is used to reflect the runtime behavior of the `await` keyword.
62735          */
62736         function getAwaitedType(type, errorNode, diagnosticMessage, arg0) {
62737             if (isTypeAny(type)) {
62738                 return type;
62739             }
62740             var typeAsAwaitable = type;
62741             if (typeAsAwaitable.awaitedTypeOfType) {
62742                 return typeAsAwaitable.awaitedTypeOfType;
62743             }
62744             // For a union, get a union of the awaited types of each constituent.
62745             //
62746             return typeAsAwaitable.awaitedTypeOfType =
62747                 mapType(type, errorNode ? function (constituentType) { return getAwaitedTypeWorker(constituentType, errorNode, diagnosticMessage, arg0); } : getAwaitedTypeWorker);
62748         }
62749         function getAwaitedTypeWorker(type, errorNode, diagnosticMessage, arg0) {
62750             var typeAsAwaitable = type;
62751             if (typeAsAwaitable.awaitedTypeOfType) {
62752                 return typeAsAwaitable.awaitedTypeOfType;
62753             }
62754             var promisedType = getPromisedTypeOfPromise(type);
62755             if (promisedType) {
62756                 if (type.id === promisedType.id || awaitedTypeStack.lastIndexOf(promisedType.id) >= 0) {
62757                     // Verify that we don't have a bad actor in the form of a promise whose
62758                     // promised type is the same as the promise type, or a mutually recursive
62759                     // promise. If so, we return undefined as we cannot guess the shape. If this
62760                     // were the actual case in the JavaScript, this Promise would never resolve.
62761                     //
62762                     // An example of a bad actor with a singly-recursive promise type might
62763                     // be:
62764                     //
62765                     //  interface BadPromise {
62766                     //      then(
62767                     //          onfulfilled: (value: BadPromise) => any,
62768                     //          onrejected: (error: any) => any): BadPromise;
62769                     //  }
62770                     //
62771                     // The above interface will pass the PromiseLike check, and return a
62772                     // promised type of `BadPromise`. Since this is a self reference, we
62773                     // don't want to keep recursing ad infinitum.
62774                     //
62775                     // An example of a bad actor in the form of a mutually-recursive
62776                     // promise type might be:
62777                     //
62778                     //  interface BadPromiseA {
62779                     //      then(
62780                     //          onfulfilled: (value: BadPromiseB) => any,
62781                     //          onrejected: (error: any) => any): BadPromiseB;
62782                     //  }
62783                     //
62784                     //  interface BadPromiseB {
62785                     //      then(
62786                     //          onfulfilled: (value: BadPromiseA) => any,
62787                     //          onrejected: (error: any) => any): BadPromiseA;
62788                     //  }
62789                     //
62790                     if (errorNode) {
62791                         error(errorNode, ts.Diagnostics.Type_is_referenced_directly_or_indirectly_in_the_fulfillment_callback_of_its_own_then_method);
62792                     }
62793                     return undefined;
62794                 }
62795                 // Keep track of the type we're about to unwrap to avoid bad recursive promise types.
62796                 // See the comments above for more information.
62797                 awaitedTypeStack.push(type.id);
62798                 var awaitedType = getAwaitedType(promisedType, errorNode, diagnosticMessage, arg0);
62799                 awaitedTypeStack.pop();
62800                 if (!awaitedType) {
62801                     return undefined;
62802                 }
62803                 return typeAsAwaitable.awaitedTypeOfType = awaitedType;
62804             }
62805             // The type was not a promise, so it could not be unwrapped any further.
62806             // As long as the type does not have a callable "then" property, it is
62807             // safe to return the type; otherwise, an error is reported and we return
62808             // undefined.
62809             //
62810             // An example of a non-promise "thenable" might be:
62811             //
62812             //  await { then(): void {} }
62813             //
62814             // The "thenable" does not match the minimal definition for a promise. When
62815             // a Promise/A+-compatible or ES6 promise tries to adopt this value, the promise
62816             // will never settle. We treat this as an error to help flag an early indicator
62817             // of a runtime problem. If the user wants to return this value from an async
62818             // function, they would need to wrap it in some other value. If they want it to
62819             // be treated as a promise, they can cast to <any>.
62820             if (isThenableType(type)) {
62821                 if (errorNode) {
62822                     if (!diagnosticMessage)
62823                         return ts.Debug.fail();
62824                     error(errorNode, diagnosticMessage, arg0);
62825                 }
62826                 return undefined;
62827             }
62828             return typeAsAwaitable.awaitedTypeOfType = type;
62829         }
62830         /**
62831          * Checks the return type of an async function to ensure it is a compatible
62832          * Promise implementation.
62833          *
62834          * This checks that an async function has a valid Promise-compatible return type.
62835          * An async function has a valid Promise-compatible return type if the resolved value
62836          * of the return type has a construct signature that takes in an `initializer` function
62837          * that in turn supplies a `resolve` function as one of its arguments and results in an
62838          * object with a callable `then` signature.
62839          *
62840          * @param node The signature to check
62841          */
62842         function checkAsyncFunctionReturnType(node, returnTypeNode) {
62843             // As part of our emit for an async function, we will need to emit the entity name of
62844             // the return type annotation as an expression. To meet the necessary runtime semantics
62845             // for __awaiter, we must also check that the type of the declaration (e.g. the static
62846             // side or "constructor" of the promise type) is compatible `PromiseConstructorLike`.
62847             //
62848             // An example might be (from lib.es6.d.ts):
62849             //
62850             //  interface Promise<T> { ... }
62851             //  interface PromiseConstructor {
62852             //      new <T>(...): Promise<T>;
62853             //  }
62854             //  declare var Promise: PromiseConstructor;
62855             //
62856             // When an async function declares a return type annotation of `Promise<T>`, we
62857             // need to get the type of the `Promise` variable declaration above, which would
62858             // be `PromiseConstructor`.
62859             //
62860             // The same case applies to a class:
62861             //
62862             //  declare class Promise<T> {
62863             //      constructor(...);
62864             //      then<U>(...): Promise<U>;
62865             //  }
62866             //
62867             var returnType = getTypeFromTypeNode(returnTypeNode);
62868             if (languageVersion >= 2 /* ES2015 */) {
62869                 if (returnType === errorType) {
62870                     return;
62871                 }
62872                 var globalPromiseType = getGlobalPromiseType(/*reportErrors*/ true);
62873                 if (globalPromiseType !== emptyGenericType && !isReferenceToType(returnType, globalPromiseType)) {
62874                     // The promise type was not a valid type reference to the global promise type, so we
62875                     // report an error and return the unknown type.
62876                     error(returnTypeNode, ts.Diagnostics.The_return_type_of_an_async_function_or_method_must_be_the_global_Promise_T_type);
62877                     return;
62878                 }
62879             }
62880             else {
62881                 // Always mark the type node as referenced if it points to a value
62882                 markTypeNodeAsReferenced(returnTypeNode);
62883                 if (returnType === errorType) {
62884                     return;
62885                 }
62886                 var promiseConstructorName = ts.getEntityNameFromTypeNode(returnTypeNode);
62887                 if (promiseConstructorName === undefined) {
62888                     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));
62889                     return;
62890                 }
62891                 var promiseConstructorSymbol = resolveEntityName(promiseConstructorName, 111551 /* Value */, /*ignoreErrors*/ true);
62892                 var promiseConstructorType = promiseConstructorSymbol ? getTypeOfSymbol(promiseConstructorSymbol) : errorType;
62893                 if (promiseConstructorType === errorType) {
62894                     if (promiseConstructorName.kind === 75 /* Identifier */ && promiseConstructorName.escapedText === "Promise" && getTargetType(returnType) === getGlobalPromiseType(/*reportErrors*/ false)) {
62895                         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);
62896                     }
62897                     else {
62898                         error(returnTypeNode, ts.Diagnostics.Type_0_is_not_a_valid_async_function_return_type_in_ES5_SlashES3_because_it_does_not_refer_to_a_Promise_compatible_constructor_value, ts.entityNameToString(promiseConstructorName));
62899                     }
62900                     return;
62901                 }
62902                 var globalPromiseConstructorLikeType = getGlobalPromiseConstructorLikeType(/*reportErrors*/ true);
62903                 if (globalPromiseConstructorLikeType === emptyObjectType) {
62904                     // If we couldn't resolve the global PromiseConstructorLike type we cannot verify
62905                     // compatibility with __awaiter.
62906                     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));
62907                     return;
62908                 }
62909                 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)) {
62910                     return;
62911                 }
62912                 // Verify there is no local declaration that could collide with the promise constructor.
62913                 var rootName = promiseConstructorName && ts.getFirstIdentifier(promiseConstructorName);
62914                 var collidingSymbol = getSymbol(node.locals, rootName.escapedText, 111551 /* Value */);
62915                 if (collidingSymbol) {
62916                     error(collidingSymbol.valueDeclaration, ts.Diagnostics.Duplicate_identifier_0_Compiler_uses_declaration_1_to_support_async_functions, ts.idText(rootName), ts.entityNameToString(promiseConstructorName));
62917                     return;
62918                 }
62919             }
62920             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);
62921         }
62922         /** Check a decorator */
62923         function checkDecorator(node) {
62924             var signature = getResolvedSignature(node);
62925             var returnType = getReturnTypeOfSignature(signature);
62926             if (returnType.flags & 1 /* Any */) {
62927                 return;
62928             }
62929             var expectedReturnType;
62930             var headMessage = getDiagnosticHeadMessageForDecoratorResolution(node);
62931             var errorInfo;
62932             switch (node.parent.kind) {
62933                 case 245 /* ClassDeclaration */:
62934                     var classSymbol = getSymbolOfNode(node.parent);
62935                     var classConstructorType = getTypeOfSymbol(classSymbol);
62936                     expectedReturnType = getUnionType([classConstructorType, voidType]);
62937                     break;
62938                 case 156 /* Parameter */:
62939                     expectedReturnType = voidType;
62940                     errorInfo = ts.chainDiagnosticMessages(
62941                     /*details*/ undefined, ts.Diagnostics.The_return_type_of_a_parameter_decorator_function_must_be_either_void_or_any);
62942                     break;
62943                 case 159 /* PropertyDeclaration */:
62944                     expectedReturnType = voidType;
62945                     errorInfo = ts.chainDiagnosticMessages(
62946                     /*details*/ undefined, ts.Diagnostics.The_return_type_of_a_property_decorator_function_must_be_either_void_or_any);
62947                     break;
62948                 case 161 /* MethodDeclaration */:
62949                 case 163 /* GetAccessor */:
62950                 case 164 /* SetAccessor */:
62951                     var methodType = getTypeOfNode(node.parent);
62952                     var descriptorType = createTypedPropertyDescriptorType(methodType);
62953                     expectedReturnType = getUnionType([descriptorType, voidType]);
62954                     break;
62955                 default:
62956                     return ts.Debug.fail();
62957             }
62958             checkTypeAssignableTo(returnType, expectedReturnType, node, headMessage, function () { return errorInfo; });
62959         }
62960         /**
62961          * If a TypeNode can be resolved to a value symbol imported from an external module, it is
62962          * marked as referenced to prevent import elision.
62963          */
62964         function markTypeNodeAsReferenced(node) {
62965             markEntityNameOrEntityExpressionAsReference(node && ts.getEntityNameFromTypeNode(node));
62966         }
62967         function markEntityNameOrEntityExpressionAsReference(typeName) {
62968             if (!typeName)
62969                 return;
62970             var rootName = ts.getFirstIdentifier(typeName);
62971             var meaning = (typeName.kind === 75 /* Identifier */ ? 788968 /* Type */ : 1920 /* Namespace */) | 2097152 /* Alias */;
62972             var rootSymbol = resolveName(rootName, rootName.escapedText, meaning, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isRefernce*/ true);
62973             if (rootSymbol
62974                 && rootSymbol.flags & 2097152 /* Alias */
62975                 && symbolIsValue(rootSymbol)
62976                 && !isConstEnumOrConstEnumOnlyModule(resolveAlias(rootSymbol))
62977                 && !getTypeOnlyAliasDeclaration(rootSymbol)) {
62978                 markAliasSymbolAsReferenced(rootSymbol);
62979             }
62980         }
62981         /**
62982          * This function marks the type used for metadata decorator as referenced if it is import
62983          * from external module.
62984          * This is different from markTypeNodeAsReferenced because it tries to simplify type nodes in
62985          * union and intersection type
62986          * @param node
62987          */
62988         function markDecoratorMedataDataTypeNodeAsReferenced(node) {
62989             var entityName = getEntityNameForDecoratorMetadata(node);
62990             if (entityName && ts.isEntityName(entityName)) {
62991                 markEntityNameOrEntityExpressionAsReference(entityName);
62992             }
62993         }
62994         function getEntityNameForDecoratorMetadata(node) {
62995             if (node) {
62996                 switch (node.kind) {
62997                     case 179 /* IntersectionType */:
62998                     case 178 /* UnionType */:
62999                         return getEntityNameForDecoratorMetadataFromTypeList(node.types);
63000                     case 180 /* ConditionalType */:
63001                         return getEntityNameForDecoratorMetadataFromTypeList([node.trueType, node.falseType]);
63002                     case 182 /* ParenthesizedType */:
63003                         return getEntityNameForDecoratorMetadata(node.type);
63004                     case 169 /* TypeReference */:
63005                         return node.typeName;
63006                 }
63007             }
63008         }
63009         function getEntityNameForDecoratorMetadataFromTypeList(types) {
63010             var commonEntityName;
63011             for (var _i = 0, types_20 = types; _i < types_20.length; _i++) {
63012                 var typeNode = types_20[_i];
63013                 while (typeNode.kind === 182 /* ParenthesizedType */) {
63014                     typeNode = typeNode.type; // Skip parens if need be
63015                 }
63016                 if (typeNode.kind === 137 /* NeverKeyword */) {
63017                     continue; // Always elide `never` from the union/intersection if possible
63018                 }
63019                 if (!strictNullChecks && (typeNode.kind === 100 /* NullKeyword */ || typeNode.kind === 146 /* UndefinedKeyword */)) {
63020                     continue; // Elide null and undefined from unions for metadata, just like what we did prior to the implementation of strict null checks
63021                 }
63022                 var individualEntityName = getEntityNameForDecoratorMetadata(typeNode);
63023                 if (!individualEntityName) {
63024                     // Individual is something like string number
63025                     // So it would be serialized to either that type or object
63026                     // Safe to return here
63027                     return undefined;
63028                 }
63029                 if (commonEntityName) {
63030                     // Note this is in sync with the transformation that happens for type node.
63031                     // Keep this in sync with serializeUnionOrIntersectionType
63032                     // Verify if they refer to same entity and is identifier
63033                     // return undefined if they dont match because we would emit object
63034                     if (!ts.isIdentifier(commonEntityName) ||
63035                         !ts.isIdentifier(individualEntityName) ||
63036                         commonEntityName.escapedText !== individualEntityName.escapedText) {
63037                         return undefined;
63038                     }
63039                 }
63040                 else {
63041                     commonEntityName = individualEntityName;
63042                 }
63043             }
63044             return commonEntityName;
63045         }
63046         function getParameterTypeNodeForDecoratorCheck(node) {
63047             var typeNode = ts.getEffectiveTypeAnnotationNode(node);
63048             return ts.isRestParameter(node) ? ts.getRestParameterElementType(typeNode) : typeNode;
63049         }
63050         /** Check the decorators of a node */
63051         function checkDecorators(node) {
63052             if (!node.decorators) {
63053                 return;
63054             }
63055             // skip this check for nodes that cannot have decorators. These should have already had an error reported by
63056             // checkGrammarDecorators.
63057             if (!ts.nodeCanBeDecorated(node, node.parent, node.parent.parent)) {
63058                 return;
63059             }
63060             if (!compilerOptions.experimentalDecorators) {
63061                 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);
63062             }
63063             var firstDecorator = node.decorators[0];
63064             checkExternalEmitHelpers(firstDecorator, 8 /* Decorate */);
63065             if (node.kind === 156 /* Parameter */) {
63066                 checkExternalEmitHelpers(firstDecorator, 32 /* Param */);
63067             }
63068             if (compilerOptions.emitDecoratorMetadata) {
63069                 checkExternalEmitHelpers(firstDecorator, 16 /* Metadata */);
63070                 // we only need to perform these checks if we are emitting serialized type metadata for the target of a decorator.
63071                 switch (node.kind) {
63072                     case 245 /* ClassDeclaration */:
63073                         var constructor = ts.getFirstConstructorWithBody(node);
63074                         if (constructor) {
63075                             for (var _i = 0, _a = constructor.parameters; _i < _a.length; _i++) {
63076                                 var parameter = _a[_i];
63077                                 markDecoratorMedataDataTypeNodeAsReferenced(getParameterTypeNodeForDecoratorCheck(parameter));
63078                             }
63079                         }
63080                         break;
63081                     case 163 /* GetAccessor */:
63082                     case 164 /* SetAccessor */:
63083                         var otherKind = node.kind === 163 /* GetAccessor */ ? 164 /* SetAccessor */ : 163 /* GetAccessor */;
63084                         var otherAccessor = ts.getDeclarationOfKind(getSymbolOfNode(node), otherKind);
63085                         markDecoratorMedataDataTypeNodeAsReferenced(getAnnotatedAccessorTypeNode(node) || otherAccessor && getAnnotatedAccessorTypeNode(otherAccessor));
63086                         break;
63087                     case 161 /* MethodDeclaration */:
63088                         for (var _b = 0, _c = node.parameters; _b < _c.length; _b++) {
63089                             var parameter = _c[_b];
63090                             markDecoratorMedataDataTypeNodeAsReferenced(getParameterTypeNodeForDecoratorCheck(parameter));
63091                         }
63092                         markDecoratorMedataDataTypeNodeAsReferenced(ts.getEffectiveReturnTypeNode(node));
63093                         break;
63094                     case 159 /* PropertyDeclaration */:
63095                         markDecoratorMedataDataTypeNodeAsReferenced(ts.getEffectiveTypeAnnotationNode(node));
63096                         break;
63097                     case 156 /* Parameter */:
63098                         markDecoratorMedataDataTypeNodeAsReferenced(getParameterTypeNodeForDecoratorCheck(node));
63099                         var containingSignature = node.parent;
63100                         for (var _d = 0, _e = containingSignature.parameters; _d < _e.length; _d++) {
63101                             var parameter = _e[_d];
63102                             markDecoratorMedataDataTypeNodeAsReferenced(getParameterTypeNodeForDecoratorCheck(parameter));
63103                         }
63104                         break;
63105                 }
63106             }
63107             ts.forEach(node.decorators, checkDecorator);
63108         }
63109         function checkFunctionDeclaration(node) {
63110             if (produceDiagnostics) {
63111                 checkFunctionOrMethodDeclaration(node);
63112                 checkGrammarForGenerator(node);
63113                 checkCollisionWithRequireExportsInGeneratedCode(node, node.name);
63114                 checkCollisionWithGlobalPromiseInGeneratedCode(node, node.name);
63115             }
63116         }
63117         function checkJSDocTypeAliasTag(node) {
63118             if (!node.typeExpression) {
63119                 // If the node had `@property` tags, `typeExpression` would have been set to the first property tag.
63120                 error(node.name, ts.Diagnostics.JSDoc_typedef_tag_should_either_have_a_type_annotation_or_be_followed_by_property_or_member_tags);
63121             }
63122             if (node.name) {
63123                 checkTypeNameIsReserved(node.name, ts.Diagnostics.Type_alias_name_cannot_be_0);
63124             }
63125             checkSourceElement(node.typeExpression);
63126         }
63127         function checkJSDocTemplateTag(node) {
63128             checkSourceElement(node.constraint);
63129             for (var _i = 0, _a = node.typeParameters; _i < _a.length; _i++) {
63130                 var tp = _a[_i];
63131                 checkSourceElement(tp);
63132             }
63133         }
63134         function checkJSDocTypeTag(node) {
63135             checkSourceElement(node.typeExpression);
63136         }
63137         function checkJSDocParameterTag(node) {
63138             checkSourceElement(node.typeExpression);
63139             if (!ts.getParameterSymbolFromJSDoc(node)) {
63140                 var decl = ts.getHostSignatureFromJSDoc(node);
63141                 // don't issue an error for invalid hosts -- just functions --
63142                 // and give a better error message when the host function mentions `arguments`
63143                 // but the tag doesn't have an array type
63144                 if (decl) {
63145                     var i = ts.getJSDocTags(decl).filter(ts.isJSDocParameterTag).indexOf(node);
63146                     if (i > -1 && i < decl.parameters.length && ts.isBindingPattern(decl.parameters[i].name)) {
63147                         return;
63148                     }
63149                     if (!containsArgumentsReference(decl)) {
63150                         if (ts.isQualifiedName(node.name)) {
63151                             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));
63152                         }
63153                         else {
63154                             error(node.name, ts.Diagnostics.JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name, ts.idText(node.name));
63155                         }
63156                     }
63157                     else if (ts.findLast(ts.getJSDocTags(decl), ts.isJSDocParameterTag) === node &&
63158                         node.typeExpression && node.typeExpression.type &&
63159                         !isArrayType(getTypeFromTypeNode(node.typeExpression.type))) {
63160                         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));
63161                     }
63162                 }
63163             }
63164         }
63165         function checkJSDocPropertyTag(node) {
63166             checkSourceElement(node.typeExpression);
63167         }
63168         function checkJSDocFunctionType(node) {
63169             if (produceDiagnostics && !node.type && !ts.isJSDocConstructSignature(node)) {
63170                 reportImplicitAny(node, anyType);
63171             }
63172             checkSignatureDeclaration(node);
63173         }
63174         function checkJSDocImplementsTag(node) {
63175             var classLike = ts.getEffectiveJSDocHost(node);
63176             if (!classLike || !ts.isClassDeclaration(classLike) && !ts.isClassExpression(classLike)) {
63177                 error(classLike, ts.Diagnostics.JSDoc_0_is_not_attached_to_a_class, ts.idText(node.tagName));
63178             }
63179         }
63180         function checkJSDocAugmentsTag(node) {
63181             var classLike = ts.getEffectiveJSDocHost(node);
63182             if (!classLike || !ts.isClassDeclaration(classLike) && !ts.isClassExpression(classLike)) {
63183                 error(classLike, ts.Diagnostics.JSDoc_0_is_not_attached_to_a_class, ts.idText(node.tagName));
63184                 return;
63185             }
63186             var augmentsTags = ts.getJSDocTags(classLike).filter(ts.isJSDocAugmentsTag);
63187             ts.Debug.assert(augmentsTags.length > 0);
63188             if (augmentsTags.length > 1) {
63189                 error(augmentsTags[1], ts.Diagnostics.Class_declarations_cannot_have_more_than_one_augments_or_extends_tag);
63190             }
63191             var name = getIdentifierFromEntityNameExpression(node.class.expression);
63192             var extend = ts.getClassExtendsHeritageElement(classLike);
63193             if (extend) {
63194                 var className = getIdentifierFromEntityNameExpression(extend.expression);
63195                 if (className && name.escapedText !== className.escapedText) {
63196                     error(name, ts.Diagnostics.JSDoc_0_1_does_not_match_the_extends_2_clause, ts.idText(node.tagName), ts.idText(name), ts.idText(className));
63197                 }
63198             }
63199         }
63200         function getIdentifierFromEntityNameExpression(node) {
63201             switch (node.kind) {
63202                 case 75 /* Identifier */:
63203                     return node;
63204                 case 194 /* PropertyAccessExpression */:
63205                     return node.name;
63206                 default:
63207                     return undefined;
63208             }
63209         }
63210         function checkFunctionOrMethodDeclaration(node) {
63211             checkDecorators(node);
63212             checkSignatureDeclaration(node);
63213             var functionFlags = ts.getFunctionFlags(node);
63214             // Do not use hasDynamicName here, because that returns false for well known symbols.
63215             // We want to perform checkComputedPropertyName for all computed properties, including
63216             // well known symbols.
63217             if (node.name && node.name.kind === 154 /* ComputedPropertyName */) {
63218                 // This check will account for methods in class/interface declarations,
63219                 // as well as accessors in classes/object literals
63220                 checkComputedPropertyName(node.name);
63221             }
63222             if (!hasNonBindableDynamicName(node)) {
63223                 // first we want to check the local symbol that contain this declaration
63224                 // - if node.localSymbol !== undefined - this is current declaration is exported and localSymbol points to the local symbol
63225                 // - if node.localSymbol === undefined - this node is non-exported so we can just pick the result of getSymbolOfNode
63226                 var symbol = getSymbolOfNode(node);
63227                 var localSymbol = node.localSymbol || symbol;
63228                 // Since the javascript won't do semantic analysis like typescript,
63229                 // if the javascript file comes before the typescript file and both contain same name functions,
63230                 // checkFunctionOrConstructorSymbol wouldn't be called if we didnt ignore javascript function.
63231                 var firstDeclaration = ts.find(localSymbol.declarations, 
63232                 // Get first non javascript function declaration
63233                 function (declaration) { return declaration.kind === node.kind && !(declaration.flags & 131072 /* JavaScriptFile */); });
63234                 // Only type check the symbol once
63235                 if (node === firstDeclaration) {
63236                     checkFunctionOrConstructorSymbol(localSymbol);
63237                 }
63238                 if (symbol.parent) {
63239                     // run check once for the first declaration
63240                     if (ts.getDeclarationOfKind(symbol, node.kind) === node) {
63241                         // run check on export symbol to check that modifiers agree across all exported declarations
63242                         checkFunctionOrConstructorSymbol(symbol);
63243                     }
63244                 }
63245             }
63246             var body = node.kind === 160 /* MethodSignature */ ? undefined : node.body;
63247             checkSourceElement(body);
63248             checkAllCodePathsInNonVoidFunctionReturnOrThrow(node, getReturnTypeFromAnnotation(node));
63249             if (produceDiagnostics && !ts.getEffectiveReturnTypeNode(node)) {
63250                 // Report an implicit any error if there is no body, no explicit return type, and node is not a private method
63251                 // in an ambient context
63252                 if (ts.nodeIsMissing(body) && !isPrivateWithinAmbient(node)) {
63253                     reportImplicitAny(node, anyType);
63254                 }
63255                 if (functionFlags & 1 /* Generator */ && ts.nodeIsPresent(body)) {
63256                     // A generator with a body and no type annotation can still cause errors. It can error if the
63257                     // yielded values have no common supertype, or it can give an implicit any error if it has no
63258                     // yielded values. The only way to trigger these errors is to try checking its return type.
63259                     getReturnTypeOfSignature(getSignatureFromDeclaration(node));
63260                 }
63261             }
63262             // A js function declaration can have a @type tag instead of a return type node, but that type must have a call signature
63263             if (ts.isInJSFile(node)) {
63264                 var typeTag = ts.getJSDocTypeTag(node);
63265                 if (typeTag && typeTag.typeExpression && !getContextualCallSignature(getTypeFromTypeNode(typeTag.typeExpression), node)) {
63266                     error(typeTag, ts.Diagnostics.The_type_of_a_function_declaration_must_match_the_function_s_signature);
63267                 }
63268             }
63269         }
63270         function registerForUnusedIdentifiersCheck(node) {
63271             // May be in a call such as getTypeOfNode that happened to call this. But potentiallyUnusedIdentifiers is only defined in the scope of `checkSourceFile`.
63272             if (produceDiagnostics) {
63273                 var sourceFile = ts.getSourceFileOfNode(node);
63274                 var potentiallyUnusedIdentifiers = allPotentiallyUnusedIdentifiers.get(sourceFile.path);
63275                 if (!potentiallyUnusedIdentifiers) {
63276                     potentiallyUnusedIdentifiers = [];
63277                     allPotentiallyUnusedIdentifiers.set(sourceFile.path, potentiallyUnusedIdentifiers);
63278                 }
63279                 // TODO: GH#22580
63280                 // Debug.assert(addToSeen(seenPotentiallyUnusedIdentifiers, getNodeId(node)), "Adding potentially-unused identifier twice");
63281                 potentiallyUnusedIdentifiers.push(node);
63282             }
63283         }
63284         function checkUnusedIdentifiers(potentiallyUnusedIdentifiers, addDiagnostic) {
63285             for (var _i = 0, potentiallyUnusedIdentifiers_1 = potentiallyUnusedIdentifiers; _i < potentiallyUnusedIdentifiers_1.length; _i++) {
63286                 var node = potentiallyUnusedIdentifiers_1[_i];
63287                 switch (node.kind) {
63288                     case 245 /* ClassDeclaration */:
63289                     case 214 /* ClassExpression */:
63290                         checkUnusedClassMembers(node, addDiagnostic);
63291                         checkUnusedTypeParameters(node, addDiagnostic);
63292                         break;
63293                     case 290 /* SourceFile */:
63294                     case 249 /* ModuleDeclaration */:
63295                     case 223 /* Block */:
63296                     case 251 /* CaseBlock */:
63297                     case 230 /* ForStatement */:
63298                     case 231 /* ForInStatement */:
63299                     case 232 /* ForOfStatement */:
63300                         checkUnusedLocalsAndParameters(node, addDiagnostic);
63301                         break;
63302                     case 162 /* Constructor */:
63303                     case 201 /* FunctionExpression */:
63304                     case 244 /* FunctionDeclaration */:
63305                     case 202 /* ArrowFunction */:
63306                     case 161 /* MethodDeclaration */:
63307                     case 163 /* GetAccessor */:
63308                     case 164 /* SetAccessor */:
63309                         if (node.body) { // Don't report unused parameters in overloads
63310                             checkUnusedLocalsAndParameters(node, addDiagnostic);
63311                         }
63312                         checkUnusedTypeParameters(node, addDiagnostic);
63313                         break;
63314                     case 160 /* MethodSignature */:
63315                     case 165 /* CallSignature */:
63316                     case 166 /* ConstructSignature */:
63317                     case 170 /* FunctionType */:
63318                     case 171 /* ConstructorType */:
63319                     case 247 /* TypeAliasDeclaration */:
63320                     case 246 /* InterfaceDeclaration */:
63321                         checkUnusedTypeParameters(node, addDiagnostic);
63322                         break;
63323                     case 181 /* InferType */:
63324                         checkUnusedInferTypeParameter(node, addDiagnostic);
63325                         break;
63326                     default:
63327                         ts.Debug.assertNever(node, "Node should not have been registered for unused identifiers check");
63328                 }
63329             }
63330         }
63331         function errorUnusedLocal(declaration, name, addDiagnostic) {
63332             var node = ts.getNameOfDeclaration(declaration) || declaration;
63333             var message = isTypeDeclaration(declaration) ? ts.Diagnostics._0_is_declared_but_never_used : ts.Diagnostics._0_is_declared_but_its_value_is_never_read;
63334             addDiagnostic(declaration, 0 /* Local */, ts.createDiagnosticForNode(node, message, name));
63335         }
63336         function isIdentifierThatStartsWithUnderscore(node) {
63337             return ts.isIdentifier(node) && ts.idText(node).charCodeAt(0) === 95 /* _ */;
63338         }
63339         function checkUnusedClassMembers(node, addDiagnostic) {
63340             for (var _i = 0, _a = node.members; _i < _a.length; _i++) {
63341                 var member = _a[_i];
63342                 switch (member.kind) {
63343                     case 161 /* MethodDeclaration */:
63344                     case 159 /* PropertyDeclaration */:
63345                     case 163 /* GetAccessor */:
63346                     case 164 /* SetAccessor */:
63347                         if (member.kind === 164 /* SetAccessor */ && member.symbol.flags & 32768 /* GetAccessor */) {
63348                             // Already would have reported an error on the getter.
63349                             break;
63350                         }
63351                         var symbol = getSymbolOfNode(member);
63352                         if (!symbol.isReferenced
63353                             && (ts.hasModifier(member, 8 /* Private */) || ts.isNamedDeclaration(member) && ts.isPrivateIdentifier(member.name))
63354                             && !(member.flags & 8388608 /* Ambient */)) {
63355                             addDiagnostic(member, 0 /* Local */, ts.createDiagnosticForNode(member.name, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, symbolToString(symbol)));
63356                         }
63357                         break;
63358                     case 162 /* Constructor */:
63359                         for (var _b = 0, _c = member.parameters; _b < _c.length; _b++) {
63360                             var parameter = _c[_b];
63361                             if (!parameter.symbol.isReferenced && ts.hasModifier(parameter, 8 /* Private */)) {
63362                                 addDiagnostic(parameter, 0 /* Local */, ts.createDiagnosticForNode(parameter.name, ts.Diagnostics.Property_0_is_declared_but_its_value_is_never_read, ts.symbolName(parameter.symbol)));
63363                             }
63364                         }
63365                         break;
63366                     case 167 /* IndexSignature */:
63367                     case 222 /* SemicolonClassElement */:
63368                         // Can't be private
63369                         break;
63370                     default:
63371                         ts.Debug.fail();
63372                 }
63373             }
63374         }
63375         function checkUnusedInferTypeParameter(node, addDiagnostic) {
63376             var typeParameter = node.typeParameter;
63377             if (isTypeParameterUnused(typeParameter)) {
63378                 addDiagnostic(node, 1 /* Parameter */, ts.createDiagnosticForNode(node, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, ts.idText(typeParameter.name)));
63379             }
63380         }
63381         function checkUnusedTypeParameters(node, addDiagnostic) {
63382             // Only report errors on the last declaration for the type parameter container;
63383             // this ensures that all uses have been accounted for.
63384             if (ts.last(getSymbolOfNode(node).declarations) !== node)
63385                 return;
63386             var typeParameters = ts.getEffectiveTypeParameterDeclarations(node);
63387             var seenParentsWithEveryUnused = new ts.NodeSet();
63388             for (var _i = 0, typeParameters_3 = typeParameters; _i < typeParameters_3.length; _i++) {
63389                 var typeParameter = typeParameters_3[_i];
63390                 if (!isTypeParameterUnused(typeParameter))
63391                     continue;
63392                 var name = ts.idText(typeParameter.name);
63393                 var parent = typeParameter.parent;
63394                 if (parent.kind !== 181 /* InferType */ && parent.typeParameters.every(isTypeParameterUnused)) {
63395                     if (seenParentsWithEveryUnused.tryAdd(parent)) {
63396                         var range = ts.isJSDocTemplateTag(parent)
63397                             // Whole @template tag
63398                             ? ts.rangeOfNode(parent)
63399                             // Include the `<>` in the error message
63400                             : ts.rangeOfTypeParameters(parent.typeParameters);
63401                         var only = parent.typeParameters.length === 1;
63402                         var message = only ? ts.Diagnostics._0_is_declared_but_its_value_is_never_read : ts.Diagnostics.All_type_parameters_are_unused;
63403                         var arg0 = only ? name : undefined;
63404                         addDiagnostic(typeParameter, 1 /* Parameter */, ts.createFileDiagnostic(ts.getSourceFileOfNode(parent), range.pos, range.end - range.pos, message, arg0));
63405                     }
63406                 }
63407                 else {
63408                     addDiagnostic(typeParameter, 1 /* Parameter */, ts.createDiagnosticForNode(typeParameter, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, name));
63409                 }
63410             }
63411         }
63412         function isTypeParameterUnused(typeParameter) {
63413             return !(getMergedSymbol(typeParameter.symbol).isReferenced & 262144 /* TypeParameter */) && !isIdentifierThatStartsWithUnderscore(typeParameter.name);
63414         }
63415         function addToGroup(map, key, value, getKey) {
63416             var keyString = String(getKey(key));
63417             var group = map.get(keyString);
63418             if (group) {
63419                 group[1].push(value);
63420             }
63421             else {
63422                 map.set(keyString, [key, [value]]);
63423             }
63424         }
63425         function tryGetRootParameterDeclaration(node) {
63426             return ts.tryCast(ts.getRootDeclaration(node), ts.isParameter);
63427         }
63428         function isValidUnusedLocalDeclaration(declaration) {
63429             if (ts.isBindingElement(declaration) && isIdentifierThatStartsWithUnderscore(declaration.name)) {
63430                 return !!ts.findAncestor(declaration.parent, function (ancestor) {
63431                     return ts.isArrayBindingPattern(ancestor) || ts.isVariableDeclaration(ancestor) || ts.isVariableDeclarationList(ancestor) ? false :
63432                         ts.isForOfStatement(ancestor) ? true : "quit";
63433                 });
63434             }
63435             return ts.isAmbientModule(declaration) ||
63436                 (ts.isVariableDeclaration(declaration) && ts.isForInOrOfStatement(declaration.parent.parent) || isImportedDeclaration(declaration)) && isIdentifierThatStartsWithUnderscore(declaration.name);
63437         }
63438         function checkUnusedLocalsAndParameters(nodeWithLocals, addDiagnostic) {
63439             // 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.
63440             var unusedImports = ts.createMap();
63441             var unusedDestructures = ts.createMap();
63442             var unusedVariables = ts.createMap();
63443             nodeWithLocals.locals.forEach(function (local) {
63444                 // If it's purely a type parameter, ignore, will be checked in `checkUnusedTypeParameters`.
63445                 // If it's a type parameter merged with a parameter, check if the parameter-side is used.
63446                 if (local.flags & 262144 /* TypeParameter */ ? !(local.flags & 3 /* Variable */ && !(local.isReferenced & 3 /* Variable */)) : local.isReferenced || local.exportSymbol) {
63447                     return;
63448                 }
63449                 for (var _i = 0, _a = local.declarations; _i < _a.length; _i++) {
63450                     var declaration = _a[_i];
63451                     if (isValidUnusedLocalDeclaration(declaration)) {
63452                         continue;
63453                     }
63454                     if (isImportedDeclaration(declaration)) {
63455                         addToGroup(unusedImports, importClauseFromImported(declaration), declaration, getNodeId);
63456                     }
63457                     else if (ts.isBindingElement(declaration) && ts.isObjectBindingPattern(declaration.parent)) {
63458                         // In `{ a, ...b }, `a` is considered used since it removes a property from `b`. `b` may still be unused though.
63459                         var lastElement = ts.last(declaration.parent.elements);
63460                         if (declaration === lastElement || !ts.last(declaration.parent.elements).dotDotDotToken) {
63461                             addToGroup(unusedDestructures, declaration.parent, declaration, getNodeId);
63462                         }
63463                     }
63464                     else if (ts.isVariableDeclaration(declaration)) {
63465                         addToGroup(unusedVariables, declaration.parent, declaration, getNodeId);
63466                     }
63467                     else {
63468                         var parameter = local.valueDeclaration && tryGetRootParameterDeclaration(local.valueDeclaration);
63469                         var name = local.valueDeclaration && ts.getNameOfDeclaration(local.valueDeclaration);
63470                         if (parameter && name) {
63471                             if (!ts.isParameterPropertyDeclaration(parameter, parameter.parent) && !ts.parameterIsThisKeyword(parameter) && !isIdentifierThatStartsWithUnderscore(name)) {
63472                                 addDiagnostic(parameter, 1 /* Parameter */, ts.createDiagnosticForNode(name, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, ts.symbolName(local)));
63473                             }
63474                         }
63475                         else {
63476                             errorUnusedLocal(declaration, ts.symbolName(local), addDiagnostic);
63477                         }
63478                     }
63479                 }
63480             });
63481             unusedImports.forEach(function (_a) {
63482                 var importClause = _a[0], unuseds = _a[1];
63483                 var importDecl = importClause.parent;
63484                 var nDeclarations = (importClause.name ? 1 : 0) +
63485                     (importClause.namedBindings ?
63486                         (importClause.namedBindings.kind === 256 /* NamespaceImport */ ? 1 : importClause.namedBindings.elements.length)
63487                         : 0);
63488                 if (nDeclarations === unuseds.length) {
63489                     addDiagnostic(importDecl, 0 /* Local */, unuseds.length === 1
63490                         ? ts.createDiagnosticForNode(importDecl, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, ts.idText(ts.first(unuseds).name))
63491                         : ts.createDiagnosticForNode(importDecl, ts.Diagnostics.All_imports_in_import_declaration_are_unused));
63492                 }
63493                 else {
63494                     for (var _i = 0, unuseds_1 = unuseds; _i < unuseds_1.length; _i++) {
63495                         var unused = unuseds_1[_i];
63496                         errorUnusedLocal(unused, ts.idText(unused.name), addDiagnostic);
63497                     }
63498                 }
63499             });
63500             unusedDestructures.forEach(function (_a) {
63501                 var bindingPattern = _a[0], bindingElements = _a[1];
63502                 var kind = tryGetRootParameterDeclaration(bindingPattern.parent) ? 1 /* Parameter */ : 0 /* Local */;
63503                 if (bindingPattern.elements.length === bindingElements.length) {
63504                     if (bindingElements.length === 1 && bindingPattern.parent.kind === 242 /* VariableDeclaration */ && bindingPattern.parent.parent.kind === 243 /* VariableDeclarationList */) {
63505                         addToGroup(unusedVariables, bindingPattern.parent.parent, bindingPattern.parent, getNodeId);
63506                     }
63507                     else {
63508                         addDiagnostic(bindingPattern, kind, bindingElements.length === 1
63509                             ? ts.createDiagnosticForNode(bindingPattern, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, bindingNameText(ts.first(bindingElements).name))
63510                             : ts.createDiagnosticForNode(bindingPattern, ts.Diagnostics.All_destructured_elements_are_unused));
63511                     }
63512                 }
63513                 else {
63514                     for (var _i = 0, bindingElements_1 = bindingElements; _i < bindingElements_1.length; _i++) {
63515                         var e = bindingElements_1[_i];
63516                         addDiagnostic(e, kind, ts.createDiagnosticForNode(e, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, bindingNameText(e.name)));
63517                     }
63518                 }
63519             });
63520             unusedVariables.forEach(function (_a) {
63521                 var declarationList = _a[0], declarations = _a[1];
63522                 if (declarationList.declarations.length === declarations.length) {
63523                     addDiagnostic(declarationList, 0 /* Local */, declarations.length === 1
63524                         ? ts.createDiagnosticForNode(ts.first(declarations).name, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, bindingNameText(ts.first(declarations).name))
63525                         : ts.createDiagnosticForNode(declarationList.parent.kind === 225 /* VariableStatement */ ? declarationList.parent : declarationList, ts.Diagnostics.All_variables_are_unused));
63526                 }
63527                 else {
63528                     for (var _i = 0, declarations_5 = declarations; _i < declarations_5.length; _i++) {
63529                         var decl = declarations_5[_i];
63530                         addDiagnostic(decl, 0 /* Local */, ts.createDiagnosticForNode(decl, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, bindingNameText(decl.name)));
63531                     }
63532                 }
63533             });
63534         }
63535         function bindingNameText(name) {
63536             switch (name.kind) {
63537                 case 75 /* Identifier */:
63538                     return ts.idText(name);
63539                 case 190 /* ArrayBindingPattern */:
63540                 case 189 /* ObjectBindingPattern */:
63541                     return bindingNameText(ts.cast(ts.first(name.elements), ts.isBindingElement).name);
63542                 default:
63543                     return ts.Debug.assertNever(name);
63544             }
63545         }
63546         function isImportedDeclaration(node) {
63547             return node.kind === 255 /* ImportClause */ || node.kind === 258 /* ImportSpecifier */ || node.kind === 256 /* NamespaceImport */;
63548         }
63549         function importClauseFromImported(decl) {
63550             return decl.kind === 255 /* ImportClause */ ? decl : decl.kind === 256 /* NamespaceImport */ ? decl.parent : decl.parent.parent;
63551         }
63552         function checkBlock(node) {
63553             // Grammar checking for SyntaxKind.Block
63554             if (node.kind === 223 /* Block */) {
63555                 checkGrammarStatementInAmbientContext(node);
63556             }
63557             if (ts.isFunctionOrModuleBlock(node)) {
63558                 var saveFlowAnalysisDisabled = flowAnalysisDisabled;
63559                 ts.forEach(node.statements, checkSourceElement);
63560                 flowAnalysisDisabled = saveFlowAnalysisDisabled;
63561             }
63562             else {
63563                 ts.forEach(node.statements, checkSourceElement);
63564             }
63565             if (node.locals) {
63566                 registerForUnusedIdentifiersCheck(node);
63567             }
63568         }
63569         function checkCollisionWithArgumentsInGeneratedCode(node) {
63570             // no rest parameters \ declaration context \ overload - no codegen impact
63571             if (languageVersion >= 2 /* ES2015 */ || compilerOptions.noEmit || !ts.hasRestParameter(node) || node.flags & 8388608 /* Ambient */ || ts.nodeIsMissing(node.body)) {
63572                 return;
63573             }
63574             ts.forEach(node.parameters, function (p) {
63575                 if (p.name && !ts.isBindingPattern(p.name) && p.name.escapedText === argumentsSymbol.escapedName) {
63576                     error(p, ts.Diagnostics.Duplicate_identifier_arguments_Compiler_uses_arguments_to_initialize_rest_parameters);
63577                 }
63578             });
63579         }
63580         function needCollisionCheckForIdentifier(node, identifier, name) {
63581             if (!(identifier && identifier.escapedText === name)) {
63582                 return false;
63583             }
63584             if (node.kind === 159 /* PropertyDeclaration */ ||
63585                 node.kind === 158 /* PropertySignature */ ||
63586                 node.kind === 161 /* MethodDeclaration */ ||
63587                 node.kind === 160 /* MethodSignature */ ||
63588                 node.kind === 163 /* GetAccessor */ ||
63589                 node.kind === 164 /* SetAccessor */) {
63590                 // it is ok to have member named '_super' or '_this' - member access is always qualified
63591                 return false;
63592             }
63593             if (node.flags & 8388608 /* Ambient */) {
63594                 // ambient context - no codegen impact
63595                 return false;
63596             }
63597             var root = ts.getRootDeclaration(node);
63598             if (root.kind === 156 /* Parameter */ && ts.nodeIsMissing(root.parent.body)) {
63599                 // just an overload - no codegen impact
63600                 return false;
63601             }
63602             return true;
63603         }
63604         // this function will run after checking the source file so 'CaptureThis' is correct for all nodes
63605         function checkIfThisIsCapturedInEnclosingScope(node) {
63606             ts.findAncestor(node, function (current) {
63607                 if (getNodeCheckFlags(current) & 4 /* CaptureThis */) {
63608                     var isDeclaration_1 = node.kind !== 75 /* Identifier */;
63609                     if (isDeclaration_1) {
63610                         error(ts.getNameOfDeclaration(node), ts.Diagnostics.Duplicate_identifier_this_Compiler_uses_variable_declaration_this_to_capture_this_reference);
63611                     }
63612                     else {
63613                         error(node, ts.Diagnostics.Expression_resolves_to_variable_declaration_this_that_compiler_uses_to_capture_this_reference);
63614                     }
63615                     return true;
63616                 }
63617                 return false;
63618             });
63619         }
63620         function checkIfNewTargetIsCapturedInEnclosingScope(node) {
63621             ts.findAncestor(node, function (current) {
63622                 if (getNodeCheckFlags(current) & 8 /* CaptureNewTarget */) {
63623                     var isDeclaration_2 = node.kind !== 75 /* Identifier */;
63624                     if (isDeclaration_2) {
63625                         error(ts.getNameOfDeclaration(node), ts.Diagnostics.Duplicate_identifier_newTarget_Compiler_uses_variable_declaration_newTarget_to_capture_new_target_meta_property_reference);
63626                     }
63627                     else {
63628                         error(node, ts.Diagnostics.Expression_resolves_to_variable_declaration_newTarget_that_compiler_uses_to_capture_new_target_meta_property_reference);
63629                     }
63630                     return true;
63631                 }
63632                 return false;
63633             });
63634         }
63635         function checkWeakMapCollision(node) {
63636             var enclosingBlockScope = ts.getEnclosingBlockScopeContainer(node);
63637             if (getNodeCheckFlags(enclosingBlockScope) & 67108864 /* ContainsClassWithPrivateIdentifiers */) {
63638                 error(node, ts.Diagnostics.Compiler_reserves_name_0_when_emitting_private_identifier_downlevel, "WeakMap");
63639             }
63640         }
63641         function checkCollisionWithRequireExportsInGeneratedCode(node, name) {
63642             // No need to check for require or exports for ES6 modules and later
63643             if (moduleKind >= ts.ModuleKind.ES2015 || compilerOptions.noEmit) {
63644                 return;
63645             }
63646             if (!needCollisionCheckForIdentifier(node, name, "require") && !needCollisionCheckForIdentifier(node, name, "exports")) {
63647                 return;
63648             }
63649             // Uninstantiated modules shouldnt do this check
63650             if (ts.isModuleDeclaration(node) && ts.getModuleInstanceState(node) !== 1 /* Instantiated */) {
63651                 return;
63652             }
63653             // In case of variable declaration, node.parent is variable statement so look at the variable statement's parent
63654             var parent = getDeclarationContainer(node);
63655             if (parent.kind === 290 /* SourceFile */ && ts.isExternalOrCommonJsModule(parent)) {
63656                 // If the declaration happens to be in external module, report error that require and exports are reserved keywords
63657                 error(name, ts.Diagnostics.Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module, ts.declarationNameToString(name), ts.declarationNameToString(name));
63658             }
63659         }
63660         function checkCollisionWithGlobalPromiseInGeneratedCode(node, name) {
63661             if (languageVersion >= 4 /* ES2017 */ || compilerOptions.noEmit || !needCollisionCheckForIdentifier(node, name, "Promise")) {
63662                 return;
63663             }
63664             // Uninstantiated modules shouldnt do this check
63665             if (ts.isModuleDeclaration(node) && ts.getModuleInstanceState(node) !== 1 /* Instantiated */) {
63666                 return;
63667             }
63668             // In case of variable declaration, node.parent is variable statement so look at the variable statement's parent
63669             var parent = getDeclarationContainer(node);
63670             if (parent.kind === 290 /* SourceFile */ && ts.isExternalOrCommonJsModule(parent) && parent.flags & 2048 /* HasAsyncFunctions */) {
63671                 // If the declaration happens to be in external module, report error that Promise is a reserved identifier.
63672                 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));
63673             }
63674         }
63675         function checkVarDeclaredNamesNotShadowed(node) {
63676             // - ScriptBody : StatementList
63677             // It is a Syntax Error if any element of the LexicallyDeclaredNames of StatementList
63678             // also occurs in the VarDeclaredNames of StatementList.
63679             // - Block : { StatementList }
63680             // It is a Syntax Error if any element of the LexicallyDeclaredNames of StatementList
63681             // also occurs in the VarDeclaredNames of StatementList.
63682             // Variable declarations are hoisted to the top of their function scope. They can shadow
63683             // block scoped declarations, which bind tighter. this will not be flagged as duplicate definition
63684             // by the binder as the declaration scope is different.
63685             // A non-initialized declaration is a no-op as the block declaration will resolve before the var
63686             // declaration. the problem is if the declaration has an initializer. this will act as a write to the
63687             // block declared value. this is fine for let, but not const.
63688             // Only consider declarations with initializers, uninitialized const declarations will not
63689             // step on a let/const variable.
63690             // Do not consider const and const declarations, as duplicate block-scoped declarations
63691             // are handled by the binder.
63692             // We are only looking for const declarations that step on let\const declarations from a
63693             // different scope. e.g.:
63694             //      {
63695             //          const x = 0; // localDeclarationSymbol obtained after name resolution will correspond to this declaration
63696             //          const x = 0; // symbol for this declaration will be 'symbol'
63697             //      }
63698             // skip block-scoped variables and parameters
63699             if ((ts.getCombinedNodeFlags(node) & 3 /* BlockScoped */) !== 0 || ts.isParameterDeclaration(node)) {
63700                 return;
63701             }
63702             // skip variable declarations that don't have initializers
63703             // NOTE: in ES6 spec initializer is required in variable declarations where name is binding pattern
63704             // so we'll always treat binding elements as initialized
63705             if (node.kind === 242 /* VariableDeclaration */ && !node.initializer) {
63706                 return;
63707             }
63708             var symbol = getSymbolOfNode(node);
63709             if (symbol.flags & 1 /* FunctionScopedVariable */) {
63710                 if (!ts.isIdentifier(node.name))
63711                     return ts.Debug.fail();
63712                 var localDeclarationSymbol = resolveName(node, node.name.escapedText, 3 /* Variable */, /*nodeNotFoundErrorMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false);
63713                 if (localDeclarationSymbol &&
63714                     localDeclarationSymbol !== symbol &&
63715                     localDeclarationSymbol.flags & 2 /* BlockScopedVariable */) {
63716                     if (getDeclarationNodeFlagsFromSymbol(localDeclarationSymbol) & 3 /* BlockScoped */) {
63717                         var varDeclList = ts.getAncestor(localDeclarationSymbol.valueDeclaration, 243 /* VariableDeclarationList */);
63718                         var container = varDeclList.parent.kind === 225 /* VariableStatement */ && varDeclList.parent.parent
63719                             ? varDeclList.parent.parent
63720                             : undefined;
63721                         // names of block-scoped and function scoped variables can collide only
63722                         // if block scoped variable is defined in the function\module\source file scope (because of variable hoisting)
63723                         var namesShareScope = container &&
63724                             (container.kind === 223 /* Block */ && ts.isFunctionLike(container.parent) ||
63725                                 container.kind === 250 /* ModuleBlock */ ||
63726                                 container.kind === 249 /* ModuleDeclaration */ ||
63727                                 container.kind === 290 /* SourceFile */);
63728                         // here we know that function scoped variable is shadowed by block scoped one
63729                         // if they are defined in the same scope - binder has already reported redeclaration error
63730                         // otherwise if variable has an initializer - show error that initialization will fail
63731                         // since LHS will be block scoped name instead of function scoped
63732                         if (!namesShareScope) {
63733                             var name = symbolToString(localDeclarationSymbol);
63734                             error(node, ts.Diagnostics.Cannot_initialize_outer_scoped_variable_0_in_the_same_scope_as_block_scoped_declaration_1, name, name);
63735                         }
63736                     }
63737                 }
63738             }
63739         }
63740         function convertAutoToAny(type) {
63741             return type === autoType ? anyType : type === autoArrayType ? anyArrayType : type;
63742         }
63743         // Check variable, parameter, or property declaration
63744         function checkVariableLikeDeclaration(node) {
63745             checkDecorators(node);
63746             if (!ts.isBindingElement(node)) {
63747                 checkSourceElement(node.type);
63748             }
63749             // JSDoc `function(string, string): string` syntax results in parameters with no name
63750             if (!node.name) {
63751                 return;
63752             }
63753             // For a computed property, just check the initializer and exit
63754             // Do not use hasDynamicName here, because that returns false for well known symbols.
63755             // We want to perform checkComputedPropertyName for all computed properties, including
63756             // well known symbols.
63757             if (node.name.kind === 154 /* ComputedPropertyName */) {
63758                 checkComputedPropertyName(node.name);
63759                 if (node.initializer) {
63760                     checkExpressionCached(node.initializer);
63761                 }
63762             }
63763             if (node.kind === 191 /* BindingElement */) {
63764                 if (node.parent.kind === 189 /* ObjectBindingPattern */ && languageVersion < 99 /* ESNext */) {
63765                     checkExternalEmitHelpers(node, 4 /* Rest */);
63766                 }
63767                 // check computed properties inside property names of binding elements
63768                 if (node.propertyName && node.propertyName.kind === 154 /* ComputedPropertyName */) {
63769                     checkComputedPropertyName(node.propertyName);
63770                 }
63771                 // check private/protected variable access
63772                 var parent = node.parent.parent;
63773                 var parentType = getTypeForBindingElementParent(parent);
63774                 var name = node.propertyName || node.name;
63775                 if (parentType && !ts.isBindingPattern(name)) {
63776                     var exprType = getLiteralTypeFromPropertyName(name);
63777                     if (isTypeUsableAsPropertyName(exprType)) {
63778                         var nameText = getPropertyNameFromType(exprType);
63779                         var property = getPropertyOfType(parentType, nameText);
63780                         if (property) {
63781                             markPropertyAsReferenced(property, /*nodeForCheckWriteOnly*/ undefined, /*isThisAccess*/ false); // A destructuring is never a write-only reference.
63782                             checkPropertyAccessibility(parent, !!parent.initializer && parent.initializer.kind === 102 /* SuperKeyword */, parentType, property);
63783                         }
63784                     }
63785                 }
63786             }
63787             // For a binding pattern, check contained binding elements
63788             if (ts.isBindingPattern(node.name)) {
63789                 if (node.name.kind === 190 /* ArrayBindingPattern */ && languageVersion < 2 /* ES2015 */ && compilerOptions.downlevelIteration) {
63790                     checkExternalEmitHelpers(node, 512 /* Read */);
63791                 }
63792                 ts.forEach(node.name.elements, checkSourceElement);
63793             }
63794             // For a parameter declaration with an initializer, error and exit if the containing function doesn't have a body
63795             if (node.initializer && ts.getRootDeclaration(node).kind === 156 /* Parameter */ && ts.nodeIsMissing(ts.getContainingFunction(node).body)) {
63796                 error(node, ts.Diagnostics.A_parameter_initializer_is_only_allowed_in_a_function_or_constructor_implementation);
63797                 return;
63798             }
63799             // For a binding pattern, validate the initializer and exit
63800             if (ts.isBindingPattern(node.name)) {
63801                 var needCheckInitializer = node.initializer && node.parent.parent.kind !== 231 /* ForInStatement */;
63802                 var needCheckWidenedType = node.name.elements.length === 0;
63803                 if (needCheckInitializer || needCheckWidenedType) {
63804                     // Don't validate for-in initializer as it is already an error
63805                     var widenedType = getWidenedTypeForVariableLikeDeclaration(node);
63806                     if (needCheckInitializer) {
63807                         var initializerType = checkExpressionCached(node.initializer);
63808                         if (strictNullChecks && needCheckWidenedType) {
63809                             checkNonNullNonVoidType(initializerType, node);
63810                         }
63811                         else {
63812                             checkTypeAssignableToAndOptionallyElaborate(initializerType, getWidenedTypeForVariableLikeDeclaration(node), node, node.initializer);
63813                         }
63814                     }
63815                     // check the binding pattern with empty elements
63816                     if (needCheckWidenedType) {
63817                         if (ts.isArrayBindingPattern(node.name)) {
63818                             checkIteratedTypeOrElementType(65 /* Destructuring */, widenedType, undefinedType, node);
63819                         }
63820                         else if (strictNullChecks) {
63821                             checkNonNullNonVoidType(widenedType, node);
63822                         }
63823                     }
63824                 }
63825                 return;
63826             }
63827             var symbol = getSymbolOfNode(node);
63828             var type = convertAutoToAny(getTypeOfSymbol(symbol));
63829             if (node === symbol.valueDeclaration) {
63830                 // Node is the primary declaration of the symbol, just validate the initializer
63831                 // Don't validate for-in initializer as it is already an error
63832                 var initializer = ts.getEffectiveInitializer(node);
63833                 if (initializer) {
63834                     var isJSObjectLiteralInitializer = ts.isInJSFile(node) &&
63835                         ts.isObjectLiteralExpression(initializer) &&
63836                         (initializer.properties.length === 0 || ts.isPrototypeAccess(node.name)) &&
63837                         ts.hasEntries(symbol.exports);
63838                     if (!isJSObjectLiteralInitializer && node.parent.parent.kind !== 231 /* ForInStatement */) {
63839                         checkTypeAssignableToAndOptionallyElaborate(checkExpressionCached(initializer), type, node, initializer, /*headMessage*/ undefined);
63840                     }
63841                 }
63842                 if (symbol.declarations.length > 1) {
63843                     if (ts.some(symbol.declarations, function (d) { return d !== node && ts.isVariableLike(d) && !areDeclarationFlagsIdentical(d, node); })) {
63844                         error(node.name, ts.Diagnostics.All_declarations_of_0_must_have_identical_modifiers, ts.declarationNameToString(node.name));
63845                     }
63846                 }
63847             }
63848             else {
63849                 // Node is a secondary declaration, check that type is identical to primary declaration and check that
63850                 // initializer is consistent with type associated with the node
63851                 var declarationType = convertAutoToAny(getWidenedTypeForVariableLikeDeclaration(node));
63852                 if (type !== errorType && declarationType !== errorType &&
63853                     !isTypeIdenticalTo(type, declarationType) &&
63854                     !(symbol.flags & 67108864 /* Assignment */)) {
63855                     errorNextVariableOrPropertyDeclarationMustHaveSameType(symbol.valueDeclaration, type, node, declarationType);
63856                 }
63857                 if (node.initializer) {
63858                     checkTypeAssignableToAndOptionallyElaborate(checkExpressionCached(node.initializer), declarationType, node, node.initializer, /*headMessage*/ undefined);
63859                 }
63860                 if (!areDeclarationFlagsIdentical(node, symbol.valueDeclaration)) {
63861                     error(node.name, ts.Diagnostics.All_declarations_of_0_must_have_identical_modifiers, ts.declarationNameToString(node.name));
63862                 }
63863             }
63864             if (node.kind !== 159 /* PropertyDeclaration */ && node.kind !== 158 /* PropertySignature */) {
63865                 // We know we don't have a binding pattern or computed name here
63866                 checkExportsOnMergedDeclarations(node);
63867                 if (node.kind === 242 /* VariableDeclaration */ || node.kind === 191 /* BindingElement */) {
63868                     checkVarDeclaredNamesNotShadowed(node);
63869                 }
63870                 checkCollisionWithRequireExportsInGeneratedCode(node, node.name);
63871                 checkCollisionWithGlobalPromiseInGeneratedCode(node, node.name);
63872                 if (!compilerOptions.noEmit && languageVersion < 99 /* ESNext */ && needCollisionCheckForIdentifier(node, node.name, "WeakMap")) {
63873                     potentialWeakMapCollisions.push(node);
63874                 }
63875             }
63876         }
63877         function errorNextVariableOrPropertyDeclarationMustHaveSameType(firstDeclaration, firstType, nextDeclaration, nextType) {
63878             var nextDeclarationName = ts.getNameOfDeclaration(nextDeclaration);
63879             var message = nextDeclaration.kind === 159 /* PropertyDeclaration */ || nextDeclaration.kind === 158 /* PropertySignature */
63880                 ? ts.Diagnostics.Subsequent_property_declarations_must_have_the_same_type_Property_0_must_be_of_type_1_but_here_has_type_2
63881                 : ts.Diagnostics.Subsequent_variable_declarations_must_have_the_same_type_Variable_0_must_be_of_type_1_but_here_has_type_2;
63882             var declName = ts.declarationNameToString(nextDeclarationName);
63883             var err = error(nextDeclarationName, message, declName, typeToString(firstType), typeToString(nextType));
63884             if (firstDeclaration) {
63885                 ts.addRelatedInfo(err, ts.createDiagnosticForNode(firstDeclaration, ts.Diagnostics._0_was_also_declared_here, declName));
63886             }
63887         }
63888         function areDeclarationFlagsIdentical(left, right) {
63889             if ((left.kind === 156 /* Parameter */ && right.kind === 242 /* VariableDeclaration */) ||
63890                 (left.kind === 242 /* VariableDeclaration */ && right.kind === 156 /* Parameter */)) {
63891                 // Differences in optionality between parameters and variables are allowed.
63892                 return true;
63893             }
63894             if (ts.hasQuestionToken(left) !== ts.hasQuestionToken(right)) {
63895                 return false;
63896             }
63897             var interestingFlags = 8 /* Private */ |
63898                 16 /* Protected */ |
63899                 256 /* Async */ |
63900                 128 /* Abstract */ |
63901                 64 /* Readonly */ |
63902                 32 /* Static */;
63903             return ts.getSelectedModifierFlags(left, interestingFlags) === ts.getSelectedModifierFlags(right, interestingFlags);
63904         }
63905         function checkVariableDeclaration(node) {
63906             checkGrammarVariableDeclaration(node);
63907             return checkVariableLikeDeclaration(node);
63908         }
63909         function checkBindingElement(node) {
63910             checkGrammarBindingElement(node);
63911             return checkVariableLikeDeclaration(node);
63912         }
63913         function checkVariableStatement(node) {
63914             // Grammar checking
63915             if (!checkGrammarDecoratorsAndModifiers(node) && !checkGrammarVariableDeclarationList(node.declarationList))
63916                 checkGrammarForDisallowedLetOrConstStatement(node);
63917             ts.forEach(node.declarationList.declarations, checkSourceElement);
63918         }
63919         function checkExpressionStatement(node) {
63920             // Grammar checking
63921             checkGrammarStatementInAmbientContext(node);
63922             checkExpression(node.expression);
63923         }
63924         function checkIfStatement(node) {
63925             // Grammar checking
63926             checkGrammarStatementInAmbientContext(node);
63927             var type = checkTruthinessExpression(node.expression);
63928             checkTestingKnownTruthyCallableType(node.expression, node.thenStatement, type);
63929             checkSourceElement(node.thenStatement);
63930             if (node.thenStatement.kind === 224 /* EmptyStatement */) {
63931                 error(node.thenStatement, ts.Diagnostics.The_body_of_an_if_statement_cannot_be_the_empty_statement);
63932             }
63933             checkSourceElement(node.elseStatement);
63934         }
63935         function checkTestingKnownTruthyCallableType(condExpr, body, type) {
63936             if (!strictNullChecks) {
63937                 return;
63938             }
63939             var testedNode = ts.isIdentifier(condExpr)
63940                 ? condExpr
63941                 : ts.isPropertyAccessExpression(condExpr)
63942                     ? condExpr.name
63943                     : undefined;
63944             if (!testedNode) {
63945                 return;
63946             }
63947             var possiblyFalsy = getFalsyFlags(type);
63948             if (possiblyFalsy) {
63949                 return;
63950             }
63951             // While it technically should be invalid for any known-truthy value
63952             // to be tested, we de-scope to functions unrefenced in the block as a
63953             // heuristic to identify the most common bugs. There are too many
63954             // false positives for values sourced from type definitions without
63955             // strictNullChecks otherwise.
63956             var callSignatures = getSignaturesOfType(type, 0 /* Call */);
63957             if (callSignatures.length === 0) {
63958                 return;
63959             }
63960             var testedFunctionSymbol = getSymbolAtLocation(testedNode);
63961             if (!testedFunctionSymbol) {
63962                 return;
63963             }
63964             var functionIsUsedInBody = ts.forEachChild(body, function check(childNode) {
63965                 if (ts.isIdentifier(childNode)) {
63966                     var childSymbol = getSymbolAtLocation(childNode);
63967                     if (childSymbol && childSymbol === testedFunctionSymbol) {
63968                         // If the test was a simple identifier, the above check is sufficient
63969                         if (ts.isIdentifier(condExpr)) {
63970                             return true;
63971                         }
63972                         // Otherwise we need to ensure the symbol is called on the same target
63973                         var testedExpression = testedNode.parent;
63974                         var childExpression = childNode.parent;
63975                         while (testedExpression && childExpression) {
63976                             if (ts.isIdentifier(testedExpression) && ts.isIdentifier(childExpression) ||
63977                                 testedExpression.kind === 104 /* ThisKeyword */ && childExpression.kind === 104 /* ThisKeyword */) {
63978                                 return getSymbolAtLocation(testedExpression) === getSymbolAtLocation(childExpression);
63979                             }
63980                             if (ts.isPropertyAccessExpression(testedExpression) && ts.isPropertyAccessExpression(childExpression)) {
63981                                 if (getSymbolAtLocation(testedExpression.name) !== getSymbolAtLocation(childExpression.name)) {
63982                                     return false;
63983                                 }
63984                                 childExpression = childExpression.expression;
63985                                 testedExpression = testedExpression.expression;
63986                             }
63987                             else {
63988                                 return false;
63989                             }
63990                         }
63991                     }
63992                 }
63993                 return ts.forEachChild(childNode, check);
63994             });
63995             if (!functionIsUsedInBody) {
63996                 error(condExpr, ts.Diagnostics.This_condition_will_always_return_true_since_the_function_is_always_defined_Did_you_mean_to_call_it_instead);
63997             }
63998         }
63999         function checkDoStatement(node) {
64000             // Grammar checking
64001             checkGrammarStatementInAmbientContext(node);
64002             checkSourceElement(node.statement);
64003             checkTruthinessExpression(node.expression);
64004         }
64005         function checkWhileStatement(node) {
64006             // Grammar checking
64007             checkGrammarStatementInAmbientContext(node);
64008             checkTruthinessExpression(node.expression);
64009             checkSourceElement(node.statement);
64010         }
64011         function checkTruthinessOfType(type, node) {
64012             if (type.flags & 16384 /* Void */) {
64013                 error(node, ts.Diagnostics.An_expression_of_type_void_cannot_be_tested_for_truthiness);
64014             }
64015             return type;
64016         }
64017         function checkTruthinessExpression(node, checkMode) {
64018             return checkTruthinessOfType(checkExpression(node, checkMode), node);
64019         }
64020         function checkForStatement(node) {
64021             // Grammar checking
64022             if (!checkGrammarStatementInAmbientContext(node)) {
64023                 if (node.initializer && node.initializer.kind === 243 /* VariableDeclarationList */) {
64024                     checkGrammarVariableDeclarationList(node.initializer);
64025                 }
64026             }
64027             if (node.initializer) {
64028                 if (node.initializer.kind === 243 /* VariableDeclarationList */) {
64029                     ts.forEach(node.initializer.declarations, checkVariableDeclaration);
64030                 }
64031                 else {
64032                     checkExpression(node.initializer);
64033                 }
64034             }
64035             if (node.condition)
64036                 checkTruthinessExpression(node.condition);
64037             if (node.incrementor)
64038                 checkExpression(node.incrementor);
64039             checkSourceElement(node.statement);
64040             if (node.locals) {
64041                 registerForUnusedIdentifiersCheck(node);
64042             }
64043         }
64044         function checkForOfStatement(node) {
64045             checkGrammarForInOrForOfStatement(node);
64046             if (node.awaitModifier) {
64047                 var functionFlags = ts.getFunctionFlags(ts.getContainingFunction(node));
64048                 if ((functionFlags & (4 /* Invalid */ | 2 /* Async */)) === 2 /* Async */ && languageVersion < 99 /* ESNext */) {
64049                     // for..await..of in an async function or async generator function prior to ESNext requires the __asyncValues helper
64050                     checkExternalEmitHelpers(node, 32768 /* ForAwaitOfIncludes */);
64051                 }
64052             }
64053             else if (compilerOptions.downlevelIteration && languageVersion < 2 /* ES2015 */) {
64054                 // for..of prior to ES2015 requires the __values helper when downlevelIteration is enabled
64055                 checkExternalEmitHelpers(node, 256 /* ForOfIncludes */);
64056             }
64057             // Check the LHS and RHS
64058             // If the LHS is a declaration, just check it as a variable declaration, which will in turn check the RHS
64059             // via checkRightHandSideOfForOf.
64060             // If the LHS is an expression, check the LHS, as a destructuring assignment or as a reference.
64061             // Then check that the RHS is assignable to it.
64062             if (node.initializer.kind === 243 /* VariableDeclarationList */) {
64063                 checkForInOrForOfVariableDeclaration(node);
64064             }
64065             else {
64066                 var varExpr = node.initializer;
64067                 var iteratedType = checkRightHandSideOfForOf(node);
64068                 // There may be a destructuring assignment on the left side
64069                 if (varExpr.kind === 192 /* ArrayLiteralExpression */ || varExpr.kind === 193 /* ObjectLiteralExpression */) {
64070                     // iteratedType may be undefined. In this case, we still want to check the structure of
64071                     // varExpr, in particular making sure it's a valid LeftHandSideExpression. But we'd like
64072                     // to short circuit the type relation checking as much as possible, so we pass the unknownType.
64073                     checkDestructuringAssignment(varExpr, iteratedType || errorType);
64074                 }
64075                 else {
64076                     var leftType = checkExpression(varExpr);
64077                     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);
64078                     // iteratedType will be undefined if the rightType was missing properties/signatures
64079                     // required to get its iteratedType (like [Symbol.iterator] or next). This may be
64080                     // because we accessed properties from anyType, or it may have led to an error inside
64081                     // getElementTypeOfIterable.
64082                     if (iteratedType) {
64083                         checkTypeAssignableToAndOptionallyElaborate(iteratedType, leftType, varExpr, node.expression);
64084                     }
64085                 }
64086             }
64087             checkSourceElement(node.statement);
64088             if (node.locals) {
64089                 registerForUnusedIdentifiersCheck(node);
64090             }
64091         }
64092         function checkForInStatement(node) {
64093             // Grammar checking
64094             checkGrammarForInOrForOfStatement(node);
64095             var rightType = getNonNullableTypeIfNeeded(checkExpression(node.expression));
64096             // TypeScript 1.0 spec (April 2014): 5.4
64097             // In a 'for-in' statement of the form
64098             // for (let VarDecl in Expr) Statement
64099             //   VarDecl must be a variable declaration without a type annotation that declares a variable of type Any,
64100             //   and Expr must be an expression of type Any, an object type, or a type parameter type.
64101             if (node.initializer.kind === 243 /* VariableDeclarationList */) {
64102                 var variable = node.initializer.declarations[0];
64103                 if (variable && ts.isBindingPattern(variable.name)) {
64104                     error(variable.name, ts.Diagnostics.The_left_hand_side_of_a_for_in_statement_cannot_be_a_destructuring_pattern);
64105                 }
64106                 checkForInOrForOfVariableDeclaration(node);
64107             }
64108             else {
64109                 // In a 'for-in' statement of the form
64110                 // for (Var in Expr) Statement
64111                 //   Var must be an expression classified as a reference of type Any or the String primitive type,
64112                 //   and Expr must be an expression of type Any, an object type, or a type parameter type.
64113                 var varExpr = node.initializer;
64114                 var leftType = checkExpression(varExpr);
64115                 if (varExpr.kind === 192 /* ArrayLiteralExpression */ || varExpr.kind === 193 /* ObjectLiteralExpression */) {
64116                     error(varExpr, ts.Diagnostics.The_left_hand_side_of_a_for_in_statement_cannot_be_a_destructuring_pattern);
64117                 }
64118                 else if (!isTypeAssignableTo(getIndexTypeOrString(rightType), leftType)) {
64119                     error(varExpr, ts.Diagnostics.The_left_hand_side_of_a_for_in_statement_must_be_of_type_string_or_any);
64120                 }
64121                 else {
64122                     // run check only former check succeeded to avoid cascading errors
64123                     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);
64124                 }
64125             }
64126             // unknownType is returned i.e. if node.expression is identifier whose name cannot be resolved
64127             // in this case error about missing name is already reported - do not report extra one
64128             if (rightType === neverType || !isTypeAssignableToKind(rightType, 67108864 /* NonPrimitive */ | 58982400 /* InstantiableNonPrimitive */)) {
64129                 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));
64130             }
64131             checkSourceElement(node.statement);
64132             if (node.locals) {
64133                 registerForUnusedIdentifiersCheck(node);
64134             }
64135         }
64136         function checkForInOrForOfVariableDeclaration(iterationStatement) {
64137             var variableDeclarationList = iterationStatement.initializer;
64138             // checkGrammarForInOrForOfStatement will check that there is exactly one declaration.
64139             if (variableDeclarationList.declarations.length >= 1) {
64140                 var decl = variableDeclarationList.declarations[0];
64141                 checkVariableDeclaration(decl);
64142             }
64143         }
64144         function checkRightHandSideOfForOf(statement) {
64145             var use = statement.awaitModifier ? 15 /* ForAwaitOf */ : 13 /* ForOf */;
64146             return checkIteratedTypeOrElementType(use, checkNonNullExpression(statement.expression), undefinedType, statement.expression);
64147         }
64148         function checkIteratedTypeOrElementType(use, inputType, sentType, errorNode) {
64149             if (isTypeAny(inputType)) {
64150                 return inputType;
64151             }
64152             return getIteratedTypeOrElementType(use, inputType, sentType, errorNode, /*checkAssignability*/ true) || anyType;
64153         }
64154         /**
64155          * When consuming an iterable type in a for..of, spread, or iterator destructuring assignment
64156          * we want to get the iterated type of an iterable for ES2015 or later, or the iterated type
64157          * of a iterable (if defined globally) or element type of an array like for ES2015 or earlier.
64158          */
64159         function getIteratedTypeOrElementType(use, inputType, sentType, errorNode, checkAssignability) {
64160             var allowAsyncIterables = (use & 2 /* AllowsAsyncIterablesFlag */) !== 0;
64161             if (inputType === neverType) {
64162                 reportTypeNotIterableError(errorNode, inputType, allowAsyncIterables); // TODO: GH#18217
64163                 return undefined;
64164             }
64165             var uplevelIteration = languageVersion >= 2 /* ES2015 */;
64166             var downlevelIteration = !uplevelIteration && compilerOptions.downlevelIteration;
64167             // Get the iterated type of an `Iterable<T>` or `IterableIterator<T>` only in ES2015
64168             // or higher, when inside of an async generator or for-await-if, or when
64169             // downlevelIteration is requested.
64170             if (uplevelIteration || downlevelIteration || allowAsyncIterables) {
64171                 // We only report errors for an invalid iterable type in ES2015 or higher.
64172                 var iterationTypes = getIterationTypesOfIterable(inputType, use, uplevelIteration ? errorNode : undefined);
64173                 if (checkAssignability) {
64174                     if (iterationTypes) {
64175                         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 :
64176                             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 :
64177                                 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 :
64178                                     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 :
64179                                         undefined;
64180                         if (diagnostic) {
64181                             checkTypeAssignableTo(sentType, iterationTypes.nextType, errorNode, diagnostic);
64182                         }
64183                     }
64184                 }
64185                 if (iterationTypes || uplevelIteration) {
64186                     return iterationTypes && iterationTypes.yieldType;
64187                 }
64188             }
64189             var arrayType = inputType;
64190             var reportedError = false;
64191             var hasStringConstituent = false;
64192             // If strings are permitted, remove any string-like constituents from the array type.
64193             // This allows us to find other non-string element types from an array unioned with
64194             // a string.
64195             if (use & 4 /* AllowsStringInputFlag */) {
64196                 if (arrayType.flags & 1048576 /* Union */) {
64197                     // After we remove all types that are StringLike, we will know if there was a string constituent
64198                     // based on whether the result of filter is a new array.
64199                     var arrayTypes = inputType.types;
64200                     var filteredTypes = ts.filter(arrayTypes, function (t) { return !(t.flags & 132 /* StringLike */); });
64201                     if (filteredTypes !== arrayTypes) {
64202                         arrayType = getUnionType(filteredTypes, 2 /* Subtype */);
64203                     }
64204                 }
64205                 else if (arrayType.flags & 132 /* StringLike */) {
64206                     arrayType = neverType;
64207                 }
64208                 hasStringConstituent = arrayType !== inputType;
64209                 if (hasStringConstituent) {
64210                     if (languageVersion < 1 /* ES5 */) {
64211                         if (errorNode) {
64212                             error(errorNode, ts.Diagnostics.Using_a_string_in_a_for_of_statement_is_only_supported_in_ECMAScript_5_and_higher);
64213                             reportedError = true;
64214                         }
64215                     }
64216                     // Now that we've removed all the StringLike types, if no constituents remain, then the entire
64217                     // arrayOrStringType was a string.
64218                     if (arrayType.flags & 131072 /* Never */) {
64219                         return stringType;
64220                     }
64221                 }
64222             }
64223             if (!isArrayLikeType(arrayType)) {
64224                 if (errorNode && !reportedError) {
64225                     // Which error we report depends on whether we allow strings or if there was a
64226                     // string constituent. For example, if the input type is number | string, we
64227                     // want to say that number is not an array type. But if the input was just
64228                     // number and string input is allowed, we want to say that number is not an
64229                     // array type or a string type.
64230                     var yieldType = getIterationTypeOfIterable(use, 0 /* Yield */, inputType, /*errorNode*/ undefined);
64231                     var _a = !(use & 4 /* AllowsStringInputFlag */) || hasStringConstituent
64232                         ? downlevelIteration
64233                             ? [ts.Diagnostics.Type_0_is_not_an_array_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator, true]
64234                             : yieldType
64235                                 ? [ts.Diagnostics.Type_0_is_not_an_array_type_or_a_string_type_Use_compiler_option_downlevelIteration_to_allow_iterating_of_iterators, false]
64236                                 : [ts.Diagnostics.Type_0_is_not_an_array_type, true]
64237                         : downlevelIteration
64238                             ? [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]
64239                             : yieldType
64240                                 ? [ts.Diagnostics.Type_0_is_not_an_array_type_or_a_string_type_Use_compiler_option_downlevelIteration_to_allow_iterating_of_iterators, false]
64241                                 : [ts.Diagnostics.Type_0_is_not_an_array_type_or_a_string_type, true], defaultDiagnostic = _a[0], maybeMissingAwait = _a[1];
64242                     errorAndMaybeSuggestAwait(errorNode, maybeMissingAwait && !!getAwaitedTypeOfPromise(arrayType), defaultDiagnostic, typeToString(arrayType));
64243                 }
64244                 return hasStringConstituent ? stringType : undefined;
64245             }
64246             var arrayElementType = getIndexTypeOfType(arrayType, 1 /* Number */);
64247             if (hasStringConstituent && arrayElementType) {
64248                 // This is just an optimization for the case where arrayOrStringType is string | string[]
64249                 if (arrayElementType.flags & 132 /* StringLike */) {
64250                     return stringType;
64251                 }
64252                 return getUnionType([arrayElementType, stringType], 2 /* Subtype */);
64253             }
64254             return arrayElementType;
64255         }
64256         /**
64257          * Gets the requested "iteration type" from an `Iterable`-like or `AsyncIterable`-like type.
64258          */
64259         function getIterationTypeOfIterable(use, typeKind, inputType, errorNode) {
64260             if (isTypeAny(inputType)) {
64261                 return undefined;
64262             }
64263             var iterationTypes = getIterationTypesOfIterable(inputType, use, errorNode);
64264             return iterationTypes && iterationTypes[getIterationTypesKeyFromIterationTypeKind(typeKind)];
64265         }
64266         function createIterationTypes(yieldType, returnType, nextType) {
64267             // `yieldType` and `returnType` are defaulted to `neverType` they each will be combined
64268             // via `getUnionType` when merging iteration types. `nextType` is defined as `unknownType`
64269             // as it is combined via `getIntersectionType` when merging iteration types.
64270             if (yieldType === void 0) { yieldType = neverType; }
64271             if (returnType === void 0) { returnType = neverType; }
64272             if (nextType === void 0) { nextType = unknownType; }
64273             // Use the cache only for intrinsic types to keep it small as they are likely to be
64274             // more frequently created (i.e. `Iterator<number, void, unknown>`). Iteration types
64275             // are also cached on the type they are requested for, so we shouldn't need to maintain
64276             // the cache for less-frequently used types.
64277             if (yieldType.flags & 67359327 /* Intrinsic */ &&
64278                 returnType.flags & (1 /* Any */ | 131072 /* Never */ | 2 /* Unknown */ | 16384 /* Void */ | 32768 /* Undefined */) &&
64279                 nextType.flags & (1 /* Any */ | 131072 /* Never */ | 2 /* Unknown */ | 16384 /* Void */ | 32768 /* Undefined */)) {
64280                 var id = getTypeListId([yieldType, returnType, nextType]);
64281                 var iterationTypes = iterationTypesCache.get(id);
64282                 if (!iterationTypes) {
64283                     iterationTypes = { yieldType: yieldType, returnType: returnType, nextType: nextType };
64284                     iterationTypesCache.set(id, iterationTypes);
64285                 }
64286                 return iterationTypes;
64287             }
64288             return { yieldType: yieldType, returnType: returnType, nextType: nextType };
64289         }
64290         /**
64291          * Combines multiple `IterationTypes` records.
64292          *
64293          * If `array` is empty or all elements are missing or are references to `noIterationTypes`,
64294          * then `noIterationTypes` is returned. Otherwise, an `IterationTypes` record is returned
64295          * for the combined iteration types.
64296          */
64297         function combineIterationTypes(array) {
64298             var yieldTypes;
64299             var returnTypes;
64300             var nextTypes;
64301             for (var _i = 0, array_10 = array; _i < array_10.length; _i++) {
64302                 var iterationTypes = array_10[_i];
64303                 if (iterationTypes === undefined || iterationTypes === noIterationTypes) {
64304                     continue;
64305                 }
64306                 if (iterationTypes === anyIterationTypes) {
64307                     return anyIterationTypes;
64308                 }
64309                 yieldTypes = ts.append(yieldTypes, iterationTypes.yieldType);
64310                 returnTypes = ts.append(returnTypes, iterationTypes.returnType);
64311                 nextTypes = ts.append(nextTypes, iterationTypes.nextType);
64312             }
64313             if (yieldTypes || returnTypes || nextTypes) {
64314                 return createIterationTypes(yieldTypes && getUnionType(yieldTypes), returnTypes && getUnionType(returnTypes), nextTypes && getIntersectionType(nextTypes));
64315             }
64316             return noIterationTypes;
64317         }
64318         function getCachedIterationTypes(type, cacheKey) {
64319             return type[cacheKey];
64320         }
64321         function setCachedIterationTypes(type, cacheKey, cachedTypes) {
64322             return type[cacheKey] = cachedTypes;
64323         }
64324         /**
64325          * Gets the *yield*, *return*, and *next* types from an `Iterable`-like or `AsyncIterable`-like type.
64326          *
64327          * At every level that involves analyzing return types of signatures, we union the return types of all the signatures.
64328          *
64329          * Another thing to note is that at any step of this process, we could run into a dead end,
64330          * meaning either the property is missing, or we run into the anyType. If either of these things
64331          * happens, we return `undefined` to signal that we could not find the iteration type. If a property
64332          * is missing, and the previous step did not result in `any`, then we also give an error if the
64333          * caller requested it. Then the caller can decide what to do in the case where there is no iterated
64334          * type.
64335          *
64336          * For a **for-of** statement, `yield*` (in a normal generator), spread, array
64337          * destructuring, or normal generator we will only ever look for a `[Symbol.iterator]()`
64338          * method.
64339          *
64340          * For an async generator we will only ever look at the `[Symbol.asyncIterator]()` method.
64341          *
64342          * For a **for-await-of** statement or a `yield*` in an async generator we will look for
64343          * the `[Symbol.asyncIterator]()` method first, and then the `[Symbol.iterator]()` method.
64344          */
64345         function getIterationTypesOfIterable(type, use, errorNode) {
64346             if (isTypeAny(type)) {
64347                 return anyIterationTypes;
64348             }
64349             if (!(type.flags & 1048576 /* Union */)) {
64350                 var iterationTypes_1 = getIterationTypesOfIterableWorker(type, use, errorNode);
64351                 if (iterationTypes_1 === noIterationTypes) {
64352                     if (errorNode) {
64353                         reportTypeNotIterableError(errorNode, type, !!(use & 2 /* AllowsAsyncIterablesFlag */));
64354                     }
64355                     return undefined;
64356                 }
64357                 return iterationTypes_1;
64358             }
64359             var cacheKey = use & 2 /* AllowsAsyncIterablesFlag */ ? "iterationTypesOfAsyncIterable" : "iterationTypesOfIterable";
64360             var cachedTypes = getCachedIterationTypes(type, cacheKey);
64361             if (cachedTypes)
64362                 return cachedTypes === noIterationTypes ? undefined : cachedTypes;
64363             var allIterationTypes;
64364             for (var _i = 0, _a = type.types; _i < _a.length; _i++) {
64365                 var constituent = _a[_i];
64366                 var iterationTypes_2 = getIterationTypesOfIterableWorker(constituent, use, errorNode);
64367                 if (iterationTypes_2 === noIterationTypes) {
64368                     if (errorNode) {
64369                         reportTypeNotIterableError(errorNode, type, !!(use & 2 /* AllowsAsyncIterablesFlag */));
64370                         errorNode = undefined;
64371                     }
64372                 }
64373                 else {
64374                     allIterationTypes = ts.append(allIterationTypes, iterationTypes_2);
64375                 }
64376             }
64377             var iterationTypes = allIterationTypes ? combineIterationTypes(allIterationTypes) : noIterationTypes;
64378             setCachedIterationTypes(type, cacheKey, iterationTypes);
64379             return iterationTypes === noIterationTypes ? undefined : iterationTypes;
64380         }
64381         function getAsyncFromSyncIterationTypes(iterationTypes, errorNode) {
64382             if (iterationTypes === noIterationTypes)
64383                 return noIterationTypes;
64384             if (iterationTypes === anyIterationTypes)
64385                 return anyIterationTypes;
64386             var yieldType = iterationTypes.yieldType, returnType = iterationTypes.returnType, nextType = iterationTypes.nextType;
64387             return createIterationTypes(getAwaitedType(yieldType, errorNode) || anyType, getAwaitedType(returnType, errorNode) || anyType, nextType);
64388         }
64389         /**
64390          * Gets the *yield*, *return*, and *next* types from a non-union type.
64391          *
64392          * If we are unable to find the *yield*, *return*, and *next* types, `noIterationTypes` is
64393          * returned to indicate to the caller that it should report an error. Otherwise, an
64394          * `IterationTypes` record is returned.
64395          *
64396          * NOTE: You probably don't want to call this directly and should be calling
64397          * `getIterationTypesOfIterable` instead.
64398          */
64399         function getIterationTypesOfIterableWorker(type, use, errorNode) {
64400             if (isTypeAny(type)) {
64401                 return anyIterationTypes;
64402             }
64403             if (use & 2 /* AllowsAsyncIterablesFlag */) {
64404                 var iterationTypes = getIterationTypesOfIterableCached(type, asyncIterationTypesResolver) ||
64405                     getIterationTypesOfIterableFast(type, asyncIterationTypesResolver);
64406                 if (iterationTypes) {
64407                     return iterationTypes;
64408                 }
64409             }
64410             if (use & 1 /* AllowsSyncIterablesFlag */) {
64411                 var iterationTypes = getIterationTypesOfIterableCached(type, syncIterationTypesResolver) ||
64412                     getIterationTypesOfIterableFast(type, syncIterationTypesResolver);
64413                 if (iterationTypes) {
64414                     if (use & 2 /* AllowsAsyncIterablesFlag */) {
64415                         // for a sync iterable in an async context, only use the cached types if they are valid.
64416                         if (iterationTypes !== noIterationTypes) {
64417                             return setCachedIterationTypes(type, "iterationTypesOfAsyncIterable", getAsyncFromSyncIterationTypes(iterationTypes, errorNode));
64418                         }
64419                     }
64420                     else {
64421                         return iterationTypes;
64422                     }
64423                 }
64424             }
64425             if (use & 2 /* AllowsAsyncIterablesFlag */) {
64426                 var iterationTypes = getIterationTypesOfIterableSlow(type, asyncIterationTypesResolver, errorNode);
64427                 if (iterationTypes !== noIterationTypes) {
64428                     return iterationTypes;
64429                 }
64430             }
64431             if (use & 1 /* AllowsSyncIterablesFlag */) {
64432                 var iterationTypes = getIterationTypesOfIterableSlow(type, syncIterationTypesResolver, errorNode);
64433                 if (iterationTypes !== noIterationTypes) {
64434                     if (use & 2 /* AllowsAsyncIterablesFlag */) {
64435                         return setCachedIterationTypes(type, "iterationTypesOfAsyncIterable", iterationTypes
64436                             ? getAsyncFromSyncIterationTypes(iterationTypes, errorNode)
64437                             : noIterationTypes);
64438                     }
64439                     else {
64440                         return iterationTypes;
64441                     }
64442                 }
64443             }
64444             return noIterationTypes;
64445         }
64446         /**
64447          * Gets the *yield*, *return*, and *next* types of an `Iterable`-like or
64448          * `AsyncIterable`-like type from the cache.
64449          *
64450          * NOTE: You probably don't want to call this directly and should be calling
64451          * `getIterationTypesOfIterable` instead.
64452          */
64453         function getIterationTypesOfIterableCached(type, resolver) {
64454             return getCachedIterationTypes(type, resolver.iterableCacheKey);
64455         }
64456         function getIterationTypesOfGlobalIterableType(globalType, resolver) {
64457             var globalIterationTypes = getIterationTypesOfIterableCached(globalType, resolver) ||
64458                 getIterationTypesOfIterableSlow(globalType, resolver, /*errorNode*/ undefined);
64459             return globalIterationTypes === noIterationTypes ? defaultIterationTypes : globalIterationTypes;
64460         }
64461         /**
64462          * Gets the *yield*, *return*, and *next* types of an `Iterable`-like or `AsyncIterable`-like
64463          * type from from common heuristics.
64464          *
64465          * If we previously analyzed this type and found no iteration types, `noIterationTypes` is
64466          * returned. If we found iteration types, an `IterationTypes` record is returned.
64467          * Otherwise, we return `undefined` to indicate to the caller it should perform a more
64468          * exhaustive analysis.
64469          *
64470          * NOTE: You probably don't want to call this directly and should be calling
64471          * `getIterationTypesOfIterable` instead.
64472          */
64473         function getIterationTypesOfIterableFast(type, resolver) {
64474             // As an optimization, if the type is an instantiation of one of the following global types, then
64475             // just grab its related type argument:
64476             // - `Iterable<T>` or `AsyncIterable<T>`
64477             // - `IterableIterator<T>` or `AsyncIterableIterator<T>`
64478             var globalType;
64479             if (isReferenceToType(type, globalType = resolver.getGlobalIterableType(/*reportErrors*/ false)) ||
64480                 isReferenceToType(type, globalType = resolver.getGlobalIterableIteratorType(/*reportErrors*/ false))) {
64481                 var yieldType = getTypeArguments(type)[0];
64482                 // The "return" and "next" types of `Iterable` and `IterableIterator` are defined by the
64483                 // iteration types of their `[Symbol.iterator]()` method. The same is true for their async cousins.
64484                 // While we define these as `any` and `undefined` in our libs by default, a custom lib *could* use
64485                 // different definitions.
64486                 var _a = getIterationTypesOfGlobalIterableType(globalType, resolver), returnType = _a.returnType, nextType = _a.nextType;
64487                 return setCachedIterationTypes(type, resolver.iterableCacheKey, createIterationTypes(yieldType, returnType, nextType));
64488             }
64489             // As an optimization, if the type is an instantiation of the following global type, then
64490             // just grab its related type arguments:
64491             // - `Generator<T, TReturn, TNext>` or `AsyncGenerator<T, TReturn, TNext>`
64492             if (isReferenceToType(type, resolver.getGlobalGeneratorType(/*reportErrors*/ false))) {
64493                 var _b = getTypeArguments(type), yieldType = _b[0], returnType = _b[1], nextType = _b[2];
64494                 return setCachedIterationTypes(type, resolver.iterableCacheKey, createIterationTypes(yieldType, returnType, nextType));
64495             }
64496         }
64497         /**
64498          * Gets the *yield*, *return*, and *next* types of an `Iterable`-like or `AsyncIterable`-like
64499          * type from its members.
64500          *
64501          * If we successfully found the *yield*, *return*, and *next* types, an `IterationTypes`
64502          * record is returned. Otherwise, `noIterationTypes` is returned.
64503          *
64504          * NOTE: You probably don't want to call this directly and should be calling
64505          * `getIterationTypesOfIterable` instead.
64506          */
64507         function getIterationTypesOfIterableSlow(type, resolver, errorNode) {
64508             var _a;
64509             var method = getPropertyOfType(type, ts.getPropertyNameForKnownSymbolName(resolver.iteratorSymbolName));
64510             var methodType = method && !(method.flags & 16777216 /* Optional */) ? getTypeOfSymbol(method) : undefined;
64511             if (isTypeAny(methodType)) {
64512                 return setCachedIterationTypes(type, resolver.iterableCacheKey, anyIterationTypes);
64513             }
64514             var signatures = methodType ? getSignaturesOfType(methodType, 0 /* Call */) : undefined;
64515             if (!ts.some(signatures)) {
64516                 return setCachedIterationTypes(type, resolver.iterableCacheKey, noIterationTypes);
64517             }
64518             var iteratorType = getUnionType(ts.map(signatures, getReturnTypeOfSignature), 2 /* Subtype */);
64519             var iterationTypes = (_a = getIterationTypesOfIterator(iteratorType, resolver, errorNode)) !== null && _a !== void 0 ? _a : noIterationTypes;
64520             return setCachedIterationTypes(type, resolver.iterableCacheKey, iterationTypes);
64521         }
64522         function reportTypeNotIterableError(errorNode, type, allowAsyncIterables) {
64523             var message = allowAsyncIterables
64524                 ? ts.Diagnostics.Type_0_must_have_a_Symbol_asyncIterator_method_that_returns_an_async_iterator
64525                 : ts.Diagnostics.Type_0_must_have_a_Symbol_iterator_method_that_returns_an_iterator;
64526             errorAndMaybeSuggestAwait(errorNode, !!getAwaitedTypeOfPromise(type), message, typeToString(type));
64527         }
64528         /**
64529          * Gets the *yield*, *return*, and *next* types from an `Iterator`-like or `AsyncIterator`-like type.
64530          *
64531          * If we successfully found the *yield*, *return*, and *next* types, an `IterationTypes`
64532          * record is returned. Otherwise, `undefined` is returned.
64533          */
64534         function getIterationTypesOfIterator(type, resolver, errorNode) {
64535             if (isTypeAny(type)) {
64536                 return anyIterationTypes;
64537             }
64538             var iterationTypes = getIterationTypesOfIteratorCached(type, resolver) ||
64539                 getIterationTypesOfIteratorFast(type, resolver) ||
64540                 getIterationTypesOfIteratorSlow(type, resolver, errorNode);
64541             return iterationTypes === noIterationTypes ? undefined : iterationTypes;
64542         }
64543         /**
64544          * Gets the iteration types of an `Iterator`-like or `AsyncIterator`-like type from the
64545          * cache.
64546          *
64547          * NOTE: You probably don't want to call this directly and should be calling
64548          * `getIterationTypesOfIterator` instead.
64549          */
64550         function getIterationTypesOfIteratorCached(type, resolver) {
64551             return getCachedIterationTypes(type, resolver.iteratorCacheKey);
64552         }
64553         /**
64554          * Gets the iteration types of an `Iterator`-like or `AsyncIterator`-like type from the
64555          * cache or from common heuristics.
64556          *
64557          * If we previously analyzed this type and found no iteration types, `noIterationTypes` is
64558          * returned. If we found iteration types, an `IterationTypes` record is returned.
64559          * Otherwise, we return `undefined` to indicate to the caller it should perform a more
64560          * exhaustive analysis.
64561          *
64562          * NOTE: You probably don't want to call this directly and should be calling
64563          * `getIterationTypesOfIterator` instead.
64564          */
64565         function getIterationTypesOfIteratorFast(type, resolver) {
64566             // As an optimization, if the type is an instantiation of one of the following global types,
64567             // then just grab its related type argument:
64568             // - `IterableIterator<T>` or `AsyncIterableIterator<T>`
64569             // - `Iterator<T, TReturn, TNext>` or `AsyncIterator<T, TReturn, TNext>`
64570             // - `Generator<T, TReturn, TNext>` or `AsyncGenerator<T, TReturn, TNext>`
64571             var globalType = resolver.getGlobalIterableIteratorType(/*reportErrors*/ false);
64572             if (isReferenceToType(type, globalType)) {
64573                 var yieldType = getTypeArguments(type)[0];
64574                 // The "return" and "next" types of `IterableIterator` and `AsyncIterableIterator` are defined by the
64575                 // iteration types of their `next`, `return`, and `throw` methods. While we define these as `any`
64576                 // and `undefined` in our libs by default, a custom lib *could* use different definitions.
64577                 var globalIterationTypes = getIterationTypesOfIteratorCached(globalType, resolver) ||
64578                     getIterationTypesOfIteratorSlow(globalType, resolver, /*errorNode*/ undefined);
64579                 var _a = globalIterationTypes === noIterationTypes ? defaultIterationTypes : globalIterationTypes, returnType = _a.returnType, nextType = _a.nextType;
64580                 return setCachedIterationTypes(type, resolver.iteratorCacheKey, createIterationTypes(yieldType, returnType, nextType));
64581             }
64582             if (isReferenceToType(type, resolver.getGlobalIteratorType(/*reportErrors*/ false)) ||
64583                 isReferenceToType(type, resolver.getGlobalGeneratorType(/*reportErrors*/ false))) {
64584                 var _b = getTypeArguments(type), yieldType = _b[0], returnType = _b[1], nextType = _b[2];
64585                 return setCachedIterationTypes(type, resolver.iteratorCacheKey, createIterationTypes(yieldType, returnType, nextType));
64586             }
64587         }
64588         function isIteratorResult(type, kind) {
64589             // From https://tc39.github.io/ecma262/#sec-iteratorresult-interface:
64590             // > [done] is the result status of an iterator `next` method call. If the end of the iterator was reached `done` is `true`.
64591             // > If the end was not reached `done` is `false` and a value is available.
64592             // > If a `done` property (either own or inherited) does not exist, it is consider to have the value `false`.
64593             var doneType = getTypeOfPropertyOfType(type, "done") || falseType;
64594             return isTypeAssignableTo(kind === 0 /* Yield */ ? falseType : trueType, doneType);
64595         }
64596         function isYieldIteratorResult(type) {
64597             return isIteratorResult(type, 0 /* Yield */);
64598         }
64599         function isReturnIteratorResult(type) {
64600             return isIteratorResult(type, 1 /* Return */);
64601         }
64602         /**
64603          * Gets the *yield* and *return* types of an `IteratorResult`-like type.
64604          *
64605          * If we are unable to determine a *yield* or a *return* type, `noIterationTypes` is
64606          * returned to indicate to the caller that it should handle the error. Otherwise, an
64607          * `IterationTypes` record is returned.
64608          */
64609         function getIterationTypesOfIteratorResult(type) {
64610             if (isTypeAny(type)) {
64611                 return anyIterationTypes;
64612             }
64613             var cachedTypes = getCachedIterationTypes(type, "iterationTypesOfIteratorResult");
64614             if (cachedTypes) {
64615                 return cachedTypes;
64616             }
64617             // As an optimization, if the type is an instantiation of one of the global `IteratorYieldResult<T>`
64618             // or `IteratorReturnResult<TReturn>` types, then just grab its type argument.
64619             if (isReferenceToType(type, getGlobalIteratorYieldResultType(/*reportErrors*/ false))) {
64620                 var yieldType_1 = getTypeArguments(type)[0];
64621                 return setCachedIterationTypes(type, "iterationTypesOfIteratorResult", createIterationTypes(yieldType_1, /*returnType*/ undefined, /*nextType*/ undefined));
64622             }
64623             if (isReferenceToType(type, getGlobalIteratorReturnResultType(/*reportErrors*/ false))) {
64624                 var returnType_1 = getTypeArguments(type)[0];
64625                 return setCachedIterationTypes(type, "iterationTypesOfIteratorResult", createIterationTypes(/*yieldType*/ undefined, returnType_1, /*nextType*/ undefined));
64626             }
64627             // Choose any constituents that can produce the requested iteration type.
64628             var yieldIteratorResult = filterType(type, isYieldIteratorResult);
64629             var yieldType = yieldIteratorResult !== neverType ? getTypeOfPropertyOfType(yieldIteratorResult, "value") : undefined;
64630             var returnIteratorResult = filterType(type, isReturnIteratorResult);
64631             var returnType = returnIteratorResult !== neverType ? getTypeOfPropertyOfType(returnIteratorResult, "value") : undefined;
64632             if (!yieldType && !returnType) {
64633                 return setCachedIterationTypes(type, "iterationTypesOfIteratorResult", noIterationTypes);
64634             }
64635             // From https://tc39.github.io/ecma262/#sec-iteratorresult-interface
64636             // > ... If the iterator does not have a return value, `value` is `undefined`. In that case, the
64637             // > `value` property may be absent from the conforming object if it does not inherit an explicit
64638             // > `value` property.
64639             return setCachedIterationTypes(type, "iterationTypesOfIteratorResult", createIterationTypes(yieldType, returnType || voidType, /*nextType*/ undefined));
64640         }
64641         /**
64642          * Gets the *yield*, *return*, and *next* types of a the `next()`, `return()`, or
64643          * `throw()` method of an `Iterator`-like or `AsyncIterator`-like type.
64644          *
64645          * If we successfully found the *yield*, *return*, and *next* types, an `IterationTypes`
64646          * record is returned. Otherwise, we return `undefined`.
64647          */
64648         function getIterationTypesOfMethod(type, resolver, methodName, errorNode) {
64649             var method = getPropertyOfType(type, methodName);
64650             // Ignore 'return' or 'throw' if they are missing.
64651             if (!method && methodName !== "next") {
64652                 return undefined;
64653             }
64654             var methodType = method && !(methodName === "next" && (method.flags & 16777216 /* Optional */))
64655                 ? methodName === "next" ? getTypeOfSymbol(method) : getTypeWithFacts(getTypeOfSymbol(method), 2097152 /* NEUndefinedOrNull */)
64656                 : undefined;
64657             if (isTypeAny(methodType)) {
64658                 // `return()` and `throw()` don't provide a *next* type.
64659                 return methodName === "next" ? anyIterationTypes : anyIterationTypesExceptNext;
64660             }
64661             // Both async and non-async iterators *must* have a `next` method.
64662             var methodSignatures = methodType ? getSignaturesOfType(methodType, 0 /* Call */) : ts.emptyArray;
64663             if (methodSignatures.length === 0) {
64664                 if (errorNode) {
64665                     var diagnostic = methodName === "next"
64666                         ? resolver.mustHaveANextMethodDiagnostic
64667                         : resolver.mustBeAMethodDiagnostic;
64668                     error(errorNode, diagnostic, methodName);
64669                 }
64670                 return methodName === "next" ? anyIterationTypes : undefined;
64671             }
64672             // Extract the first parameter and return type of each signature.
64673             var methodParameterTypes;
64674             var methodReturnTypes;
64675             for (var _i = 0, methodSignatures_1 = methodSignatures; _i < methodSignatures_1.length; _i++) {
64676                 var signature = methodSignatures_1[_i];
64677                 if (methodName !== "throw" && ts.some(signature.parameters)) {
64678                     methodParameterTypes = ts.append(methodParameterTypes, getTypeAtPosition(signature, 0));
64679                 }
64680                 methodReturnTypes = ts.append(methodReturnTypes, getReturnTypeOfSignature(signature));
64681             }
64682             // Resolve the *next* or *return* type from the first parameter of a `next()` or
64683             // `return()` method, respectively.
64684             var returnTypes;
64685             var nextType;
64686             if (methodName !== "throw") {
64687                 var methodParameterType = methodParameterTypes ? getUnionType(methodParameterTypes) : unknownType;
64688                 if (methodName === "next") {
64689                     // The value of `next(value)` is *not* awaited by async generators
64690                     nextType = methodParameterType;
64691                 }
64692                 else if (methodName === "return") {
64693                     // The value of `return(value)` *is* awaited by async generators
64694                     var resolvedMethodParameterType = resolver.resolveIterationType(methodParameterType, errorNode) || anyType;
64695                     returnTypes = ts.append(returnTypes, resolvedMethodParameterType);
64696                 }
64697             }
64698             // Resolve the *yield* and *return* types from the return type of the method (i.e. `IteratorResult`)
64699             var yieldType;
64700             var methodReturnType = methodReturnTypes ? getUnionType(methodReturnTypes, 2 /* Subtype */) : neverType;
64701             var resolvedMethodReturnType = resolver.resolveIterationType(methodReturnType, errorNode) || anyType;
64702             var iterationTypes = getIterationTypesOfIteratorResult(resolvedMethodReturnType);
64703             if (iterationTypes === noIterationTypes) {
64704                 if (errorNode) {
64705                     error(errorNode, resolver.mustHaveAValueDiagnostic, methodName);
64706                 }
64707                 yieldType = anyType;
64708                 returnTypes = ts.append(returnTypes, anyType);
64709             }
64710             else {
64711                 yieldType = iterationTypes.yieldType;
64712                 returnTypes = ts.append(returnTypes, iterationTypes.returnType);
64713             }
64714             return createIterationTypes(yieldType, getUnionType(returnTypes), nextType);
64715         }
64716         /**
64717          * Gets the *yield*, *return*, and *next* types of an `Iterator`-like or `AsyncIterator`-like
64718          * type from its members.
64719          *
64720          * If we successfully found the *yield*, *return*, and *next* types, an `IterationTypes`
64721          * record is returned. Otherwise, `noIterationTypes` is returned.
64722          *
64723          * NOTE: You probably don't want to call this directly and should be calling
64724          * `getIterationTypesOfIterator` instead.
64725          */
64726         function getIterationTypesOfIteratorSlow(type, resolver, errorNode) {
64727             var iterationTypes = combineIterationTypes([
64728                 getIterationTypesOfMethod(type, resolver, "next", errorNode),
64729                 getIterationTypesOfMethod(type, resolver, "return", errorNode),
64730                 getIterationTypesOfMethod(type, resolver, "throw", errorNode),
64731             ]);
64732             return setCachedIterationTypes(type, resolver.iteratorCacheKey, iterationTypes);
64733         }
64734         /**
64735          * Gets the requested "iteration type" from a type that is either `Iterable`-like, `Iterator`-like,
64736          * `IterableIterator`-like, or `Generator`-like (for a non-async generator); or `AsyncIterable`-like,
64737          * `AsyncIterator`-like, `AsyncIterableIterator`-like, or `AsyncGenerator`-like (for an async generator).
64738          */
64739         function getIterationTypeOfGeneratorFunctionReturnType(kind, returnType, isAsyncGenerator) {
64740             if (isTypeAny(returnType)) {
64741                 return undefined;
64742             }
64743             var iterationTypes = getIterationTypesOfGeneratorFunctionReturnType(returnType, isAsyncGenerator);
64744             return iterationTypes && iterationTypes[getIterationTypesKeyFromIterationTypeKind(kind)];
64745         }
64746         function getIterationTypesOfGeneratorFunctionReturnType(type, isAsyncGenerator) {
64747             if (isTypeAny(type)) {
64748                 return anyIterationTypes;
64749             }
64750             var use = isAsyncGenerator ? 2 /* AsyncGeneratorReturnType */ : 1 /* GeneratorReturnType */;
64751             var resolver = isAsyncGenerator ? asyncIterationTypesResolver : syncIterationTypesResolver;
64752             return getIterationTypesOfIterable(type, use, /*errorNode*/ undefined) ||
64753                 getIterationTypesOfIterator(type, resolver, /*errorNode*/ undefined);
64754         }
64755         function checkBreakOrContinueStatement(node) {
64756             // Grammar checking
64757             if (!checkGrammarStatementInAmbientContext(node))
64758                 checkGrammarBreakOrContinueStatement(node);
64759             // TODO: Check that target label is valid
64760         }
64761         function unwrapReturnType(returnType, functionFlags) {
64762             var _a, _b;
64763             var isGenerator = !!(functionFlags & 1 /* Generator */);
64764             var isAsync = !!(functionFlags & 2 /* Async */);
64765             return isGenerator ? (_a = getIterationTypeOfGeneratorFunctionReturnType(1 /* Return */, returnType, isAsync)) !== null && _a !== void 0 ? _a : errorType :
64766                 isAsync ? (_b = getAwaitedType(returnType)) !== null && _b !== void 0 ? _b : errorType :
64767                     returnType;
64768         }
64769         function isUnwrappedReturnTypeVoidOrAny(func, returnType) {
64770             var unwrappedReturnType = unwrapReturnType(returnType, ts.getFunctionFlags(func));
64771             return !!unwrappedReturnType && maybeTypeOfKind(unwrappedReturnType, 16384 /* Void */ | 3 /* AnyOrUnknown */);
64772         }
64773         function checkReturnStatement(node) {
64774             var _a;
64775             // Grammar checking
64776             if (checkGrammarStatementInAmbientContext(node)) {
64777                 return;
64778             }
64779             var func = ts.getContainingFunction(node);
64780             if (!func) {
64781                 grammarErrorOnFirstToken(node, ts.Diagnostics.A_return_statement_can_only_be_used_within_a_function_body);
64782                 return;
64783             }
64784             var signature = getSignatureFromDeclaration(func);
64785             var returnType = getReturnTypeOfSignature(signature);
64786             var functionFlags = ts.getFunctionFlags(func);
64787             if (strictNullChecks || node.expression || returnType.flags & 131072 /* Never */) {
64788                 var exprType = node.expression ? checkExpressionCached(node.expression) : undefinedType;
64789                 if (func.kind === 164 /* SetAccessor */) {
64790                     if (node.expression) {
64791                         error(node, ts.Diagnostics.Setters_cannot_return_a_value);
64792                     }
64793                 }
64794                 else if (func.kind === 162 /* Constructor */) {
64795                     if (node.expression && !checkTypeAssignableToAndOptionallyElaborate(exprType, returnType, node, node.expression)) {
64796                         error(node, ts.Diagnostics.Return_type_of_constructor_signature_must_be_assignable_to_the_instance_type_of_the_class);
64797                     }
64798                 }
64799                 else if (getReturnTypeFromAnnotation(func)) {
64800                     var unwrappedReturnType = (_a = unwrapReturnType(returnType, functionFlags)) !== null && _a !== void 0 ? _a : returnType;
64801                     var unwrappedExprType = functionFlags & 2 /* Async */
64802                         ? 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)
64803                         : exprType;
64804                     if (unwrappedReturnType) {
64805                         // If the function has a return type, but promisedType is
64806                         // undefined, an error will be reported in checkAsyncFunctionReturnType
64807                         // so we don't need to report one here.
64808                         checkTypeAssignableToAndOptionallyElaborate(unwrappedExprType, unwrappedReturnType, node, node.expression);
64809                     }
64810                 }
64811             }
64812             else if (func.kind !== 162 /* Constructor */ && compilerOptions.noImplicitReturns && !isUnwrappedReturnTypeVoidOrAny(func, returnType)) {
64813                 // The function has a return type, but the return statement doesn't have an expression.
64814                 error(node, ts.Diagnostics.Not_all_code_paths_return_a_value);
64815             }
64816         }
64817         function checkWithStatement(node) {
64818             // Grammar checking for withStatement
64819             if (!checkGrammarStatementInAmbientContext(node)) {
64820                 if (node.flags & 32768 /* AwaitContext */) {
64821                     grammarErrorOnFirstToken(node, ts.Diagnostics.with_statements_are_not_allowed_in_an_async_function_block);
64822                 }
64823             }
64824             checkExpression(node.expression);
64825             var sourceFile = ts.getSourceFileOfNode(node);
64826             if (!hasParseDiagnostics(sourceFile)) {
64827                 var start = ts.getSpanOfTokenAtPosition(sourceFile, node.pos).start;
64828                 var end = node.statement.pos;
64829                 grammarErrorAtPos(sourceFile, start, end - start, ts.Diagnostics.The_with_statement_is_not_supported_All_symbols_in_a_with_block_will_have_type_any);
64830             }
64831         }
64832         function checkSwitchStatement(node) {
64833             // Grammar checking
64834             checkGrammarStatementInAmbientContext(node);
64835             var firstDefaultClause;
64836             var hasDuplicateDefaultClause = false;
64837             var expressionType = checkExpression(node.expression);
64838             var expressionIsLiteral = isLiteralType(expressionType);
64839             ts.forEach(node.caseBlock.clauses, function (clause) {
64840                 // Grammar check for duplicate default clauses, skip if we already report duplicate default clause
64841                 if (clause.kind === 278 /* DefaultClause */ && !hasDuplicateDefaultClause) {
64842                     if (firstDefaultClause === undefined) {
64843                         firstDefaultClause = clause;
64844                     }
64845                     else {
64846                         grammarErrorOnNode(clause, ts.Diagnostics.A_default_clause_cannot_appear_more_than_once_in_a_switch_statement);
64847                         hasDuplicateDefaultClause = true;
64848                     }
64849                 }
64850                 if (produceDiagnostics && clause.kind === 277 /* CaseClause */) {
64851                     // TypeScript 1.0 spec (April 2014): 5.9
64852                     // In a 'switch' statement, each 'case' expression must be of a type that is comparable
64853                     // to or from the type of the 'switch' expression.
64854                     var caseType = checkExpression(clause.expression);
64855                     var caseIsLiteral = isLiteralType(caseType);
64856                     var comparedExpressionType = expressionType;
64857                     if (!caseIsLiteral || !expressionIsLiteral) {
64858                         caseType = caseIsLiteral ? getBaseTypeOfLiteralType(caseType) : caseType;
64859                         comparedExpressionType = getBaseTypeOfLiteralType(expressionType);
64860                     }
64861                     if (!isTypeEqualityComparableTo(comparedExpressionType, caseType)) {
64862                         // expressionType is not comparable to caseType, try the reversed check and report errors if it fails
64863                         checkTypeComparableTo(caseType, comparedExpressionType, clause.expression, /*headMessage*/ undefined);
64864                     }
64865                 }
64866                 ts.forEach(clause.statements, checkSourceElement);
64867                 if (compilerOptions.noFallthroughCasesInSwitch && clause.fallthroughFlowNode && isReachableFlowNode(clause.fallthroughFlowNode)) {
64868                     error(clause, ts.Diagnostics.Fallthrough_case_in_switch);
64869                 }
64870             });
64871             if (node.caseBlock.locals) {
64872                 registerForUnusedIdentifiersCheck(node.caseBlock);
64873             }
64874         }
64875         function checkLabeledStatement(node) {
64876             // Grammar checking
64877             if (!checkGrammarStatementInAmbientContext(node)) {
64878                 ts.findAncestor(node.parent, function (current) {
64879                     if (ts.isFunctionLike(current)) {
64880                         return "quit";
64881                     }
64882                     if (current.kind === 238 /* LabeledStatement */ && current.label.escapedText === node.label.escapedText) {
64883                         grammarErrorOnNode(node.label, ts.Diagnostics.Duplicate_label_0, ts.getTextOfNode(node.label));
64884                         return true;
64885                     }
64886                     return false;
64887                 });
64888             }
64889             // ensure that label is unique
64890             checkSourceElement(node.statement);
64891         }
64892         function checkThrowStatement(node) {
64893             // Grammar checking
64894             if (!checkGrammarStatementInAmbientContext(node)) {
64895                 if (node.expression === undefined) {
64896                     grammarErrorAfterFirstToken(node, ts.Diagnostics.Line_break_not_permitted_here);
64897                 }
64898             }
64899             if (node.expression) {
64900                 checkExpression(node.expression);
64901             }
64902         }
64903         function checkTryStatement(node) {
64904             // Grammar checking
64905             checkGrammarStatementInAmbientContext(node);
64906             checkBlock(node.tryBlock);
64907             var catchClause = node.catchClause;
64908             if (catchClause) {
64909                 // Grammar checking
64910                 if (catchClause.variableDeclaration) {
64911                     if (catchClause.variableDeclaration.type) {
64912                         grammarErrorOnFirstToken(catchClause.variableDeclaration.type, ts.Diagnostics.Catch_clause_variable_cannot_have_a_type_annotation);
64913                     }
64914                     else if (catchClause.variableDeclaration.initializer) {
64915                         grammarErrorOnFirstToken(catchClause.variableDeclaration.initializer, ts.Diagnostics.Catch_clause_variable_cannot_have_an_initializer);
64916                     }
64917                     else {
64918                         var blockLocals_1 = catchClause.block.locals;
64919                         if (blockLocals_1) {
64920                             ts.forEachKey(catchClause.locals, function (caughtName) {
64921                                 var blockLocal = blockLocals_1.get(caughtName);
64922                                 if (blockLocal && (blockLocal.flags & 2 /* BlockScopedVariable */) !== 0) {
64923                                     grammarErrorOnNode(blockLocal.valueDeclaration, ts.Diagnostics.Cannot_redeclare_identifier_0_in_catch_clause, caughtName);
64924                                 }
64925                             });
64926                         }
64927                     }
64928                 }
64929                 checkBlock(catchClause.block);
64930             }
64931             if (node.finallyBlock) {
64932                 checkBlock(node.finallyBlock);
64933             }
64934         }
64935         function checkIndexConstraints(type) {
64936             var declaredNumberIndexer = getIndexDeclarationOfSymbol(type.symbol, 1 /* Number */);
64937             var declaredStringIndexer = getIndexDeclarationOfSymbol(type.symbol, 0 /* String */);
64938             var stringIndexType = getIndexTypeOfType(type, 0 /* String */);
64939             var numberIndexType = getIndexTypeOfType(type, 1 /* Number */);
64940             if (stringIndexType || numberIndexType) {
64941                 ts.forEach(getPropertiesOfObjectType(type), function (prop) {
64942                     var propType = getTypeOfSymbol(prop);
64943                     checkIndexConstraintForProperty(prop, propType, type, declaredStringIndexer, stringIndexType, 0 /* String */);
64944                     checkIndexConstraintForProperty(prop, propType, type, declaredNumberIndexer, numberIndexType, 1 /* Number */);
64945                 });
64946                 var classDeclaration = type.symbol.valueDeclaration;
64947                 if (ts.getObjectFlags(type) & 1 /* Class */ && ts.isClassLike(classDeclaration)) {
64948                     for (var _i = 0, _a = classDeclaration.members; _i < _a.length; _i++) {
64949                         var member = _a[_i];
64950                         // Only process instance properties with computed names here.
64951                         // Static properties cannot be in conflict with indexers,
64952                         // and properties with literal names were already checked.
64953                         if (!ts.hasModifier(member, 32 /* Static */) && hasNonBindableDynamicName(member)) {
64954                             var symbol = getSymbolOfNode(member);
64955                             var propType = getTypeOfSymbol(symbol);
64956                             checkIndexConstraintForProperty(symbol, propType, type, declaredStringIndexer, stringIndexType, 0 /* String */);
64957                             checkIndexConstraintForProperty(symbol, propType, type, declaredNumberIndexer, numberIndexType, 1 /* Number */);
64958                         }
64959                     }
64960                 }
64961             }
64962             var errorNode;
64963             if (stringIndexType && numberIndexType) {
64964                 errorNode = declaredNumberIndexer || declaredStringIndexer;
64965                 // condition 'errorNode === undefined' may appear if types does not declare nor string neither number indexer
64966                 if (!errorNode && (ts.getObjectFlags(type) & 2 /* Interface */)) {
64967                     var someBaseTypeHasBothIndexers = ts.forEach(getBaseTypes(type), function (base) { return getIndexTypeOfType(base, 0 /* String */) && getIndexTypeOfType(base, 1 /* Number */); });
64968                     errorNode = someBaseTypeHasBothIndexers ? undefined : type.symbol.declarations[0];
64969                 }
64970             }
64971             if (errorNode && !isTypeAssignableTo(numberIndexType, stringIndexType)) { // TODO: GH#18217
64972                 error(errorNode, ts.Diagnostics.Numeric_index_type_0_is_not_assignable_to_string_index_type_1, typeToString(numberIndexType), typeToString(stringIndexType));
64973             }
64974             function checkIndexConstraintForProperty(prop, propertyType, containingType, indexDeclaration, indexType, indexKind) {
64975                 // ESSymbol properties apply to neither string nor numeric indexers.
64976                 if (!indexType || ts.isKnownSymbol(prop)) {
64977                     return;
64978                 }
64979                 var propDeclaration = prop.valueDeclaration;
64980                 var name = propDeclaration && ts.getNameOfDeclaration(propDeclaration);
64981                 if (name && ts.isPrivateIdentifier(name)) {
64982                     return;
64983                 }
64984                 // index is numeric and property name is not valid numeric literal
64985                 if (indexKind === 1 /* Number */ && !(name ? isNumericName(name) : isNumericLiteralName(prop.escapedName))) {
64986                     return;
64987                 }
64988                 // perform property check if property or indexer is declared in 'type'
64989                 // this allows us to rule out cases when both property and indexer are inherited from the base class
64990                 var errorNode;
64991                 if (propDeclaration && name &&
64992                     (propDeclaration.kind === 209 /* BinaryExpression */ ||
64993                         name.kind === 154 /* ComputedPropertyName */ ||
64994                         prop.parent === containingType.symbol)) {
64995                     errorNode = propDeclaration;
64996                 }
64997                 else if (indexDeclaration) {
64998                     errorNode = indexDeclaration;
64999                 }
65000                 else if (ts.getObjectFlags(containingType) & 2 /* Interface */) {
65001                     // for interfaces property and indexer might be inherited from different bases
65002                     // check if any base class already has both property and indexer.
65003                     // check should be performed only if 'type' is the first type that brings property\indexer together
65004                     var someBaseClassHasBothPropertyAndIndexer = ts.forEach(getBaseTypes(containingType), function (base) { return getPropertyOfObjectType(base, prop.escapedName) && getIndexTypeOfType(base, indexKind); });
65005                     errorNode = someBaseClassHasBothPropertyAndIndexer ? undefined : containingType.symbol.declarations[0];
65006                 }
65007                 if (errorNode && !isTypeAssignableTo(propertyType, indexType)) {
65008                     var errorMessage = indexKind === 0 /* String */
65009                         ? ts.Diagnostics.Property_0_of_type_1_is_not_assignable_to_string_index_type_2
65010                         : ts.Diagnostics.Property_0_of_type_1_is_not_assignable_to_numeric_index_type_2;
65011                     error(errorNode, errorMessage, symbolToString(prop), typeToString(propertyType), typeToString(indexType));
65012                 }
65013             }
65014         }
65015         function checkTypeNameIsReserved(name, message) {
65016             // TS 1.0 spec (April 2014): 3.6.1
65017             // The predefined type keywords are reserved and cannot be used as names of user defined types.
65018             switch (name.escapedText) {
65019                 case "any":
65020                 case "unknown":
65021                 case "number":
65022                 case "bigint":
65023                 case "boolean":
65024                 case "string":
65025                 case "symbol":
65026                 case "void":
65027                 case "object":
65028                     error(name, message, name.escapedText);
65029             }
65030         }
65031         /**
65032          * The name cannot be used as 'Object' of user defined types with special target.
65033          */
65034         function checkClassNameCollisionWithObject(name) {
65035             if (languageVersion === 1 /* ES5 */ && name.escapedText === "Object"
65036                 && moduleKind < ts.ModuleKind.ES2015) {
65037                 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
65038             }
65039         }
65040         /**
65041          * Check each type parameter and check that type parameters have no duplicate type parameter declarations
65042          */
65043         function checkTypeParameters(typeParameterDeclarations) {
65044             if (typeParameterDeclarations) {
65045                 var seenDefault = false;
65046                 for (var i = 0; i < typeParameterDeclarations.length; i++) {
65047                     var node = typeParameterDeclarations[i];
65048                     checkTypeParameter(node);
65049                     if (produceDiagnostics) {
65050                         if (node.default) {
65051                             seenDefault = true;
65052                             checkTypeParametersNotReferenced(node.default, typeParameterDeclarations, i);
65053                         }
65054                         else if (seenDefault) {
65055                             error(node, ts.Diagnostics.Required_type_parameters_may_not_follow_optional_type_parameters);
65056                         }
65057                         for (var j = 0; j < i; j++) {
65058                             if (typeParameterDeclarations[j].symbol === node.symbol) {
65059                                 error(node.name, ts.Diagnostics.Duplicate_identifier_0, ts.declarationNameToString(node.name));
65060                             }
65061                         }
65062                     }
65063                 }
65064             }
65065         }
65066         /** Check that type parameter defaults only reference previously declared type parameters */
65067         function checkTypeParametersNotReferenced(root, typeParameters, index) {
65068             visit(root);
65069             function visit(node) {
65070                 if (node.kind === 169 /* TypeReference */) {
65071                     var type = getTypeFromTypeReference(node);
65072                     if (type.flags & 262144 /* TypeParameter */) {
65073                         for (var i = index; i < typeParameters.length; i++) {
65074                             if (type.symbol === getSymbolOfNode(typeParameters[i])) {
65075                                 error(node, ts.Diagnostics.Type_parameter_defaults_can_only_reference_previously_declared_type_parameters);
65076                             }
65077                         }
65078                     }
65079                 }
65080                 ts.forEachChild(node, visit);
65081             }
65082         }
65083         /** Check that type parameter lists are identical across multiple declarations */
65084         function checkTypeParameterListsIdentical(symbol) {
65085             if (symbol.declarations.length === 1) {
65086                 return;
65087             }
65088             var links = getSymbolLinks(symbol);
65089             if (!links.typeParametersChecked) {
65090                 links.typeParametersChecked = true;
65091                 var declarations = getClassOrInterfaceDeclarationsOfSymbol(symbol);
65092                 if (declarations.length <= 1) {
65093                     return;
65094                 }
65095                 var type = getDeclaredTypeOfSymbol(symbol);
65096                 if (!areTypeParametersIdentical(declarations, type.localTypeParameters)) {
65097                     // Report an error on every conflicting declaration.
65098                     var name = symbolToString(symbol);
65099                     for (var _i = 0, declarations_6 = declarations; _i < declarations_6.length; _i++) {
65100                         var declaration = declarations_6[_i];
65101                         error(declaration.name, ts.Diagnostics.All_declarations_of_0_must_have_identical_type_parameters, name);
65102                     }
65103                 }
65104             }
65105         }
65106         function areTypeParametersIdentical(declarations, targetParameters) {
65107             var maxTypeArgumentCount = ts.length(targetParameters);
65108             var minTypeArgumentCount = getMinTypeArgumentCount(targetParameters);
65109             for (var _i = 0, declarations_7 = declarations; _i < declarations_7.length; _i++) {
65110                 var declaration = declarations_7[_i];
65111                 // If this declaration has too few or too many type parameters, we report an error
65112                 var sourceParameters = ts.getEffectiveTypeParameterDeclarations(declaration);
65113                 var numTypeParameters = sourceParameters.length;
65114                 if (numTypeParameters < minTypeArgumentCount || numTypeParameters > maxTypeArgumentCount) {
65115                     return false;
65116                 }
65117                 for (var i = 0; i < numTypeParameters; i++) {
65118                     var source = sourceParameters[i];
65119                     var target = targetParameters[i];
65120                     // If the type parameter node does not have the same as the resolved type
65121                     // parameter at this position, we report an error.
65122                     if (source.name.escapedText !== target.symbol.escapedName) {
65123                         return false;
65124                     }
65125                     // If the type parameter node does not have an identical constraint as the resolved
65126                     // type parameter at this position, we report an error.
65127                     var constraint = ts.getEffectiveConstraintOfTypeParameter(source);
65128                     var sourceConstraint = constraint && getTypeFromTypeNode(constraint);
65129                     var targetConstraint = getConstraintOfTypeParameter(target);
65130                     // relax check if later interface augmentation has no constraint, it's more broad and is OK to merge with
65131                     // a more constrained interface (this could be generalized to a full hierarchy check, but that's maybe overkill)
65132                     if (sourceConstraint && targetConstraint && !isTypeIdenticalTo(sourceConstraint, targetConstraint)) {
65133                         return false;
65134                     }
65135                     // If the type parameter node has a default and it is not identical to the default
65136                     // for the type parameter at this position, we report an error.
65137                     var sourceDefault = source.default && getTypeFromTypeNode(source.default);
65138                     var targetDefault = getDefaultFromTypeParameter(target);
65139                     if (sourceDefault && targetDefault && !isTypeIdenticalTo(sourceDefault, targetDefault)) {
65140                         return false;
65141                     }
65142                 }
65143             }
65144             return true;
65145         }
65146         function checkClassExpression(node) {
65147             checkClassLikeDeclaration(node);
65148             checkNodeDeferred(node);
65149             return getTypeOfSymbol(getSymbolOfNode(node));
65150         }
65151         function checkClassExpressionDeferred(node) {
65152             ts.forEach(node.members, checkSourceElement);
65153             registerForUnusedIdentifiersCheck(node);
65154         }
65155         function checkClassDeclaration(node) {
65156             if (!node.name && !ts.hasModifier(node, 512 /* Default */)) {
65157                 grammarErrorOnFirstToken(node, ts.Diagnostics.A_class_declaration_without_the_default_modifier_must_have_a_name);
65158             }
65159             checkClassLikeDeclaration(node);
65160             ts.forEach(node.members, checkSourceElement);
65161             registerForUnusedIdentifiersCheck(node);
65162         }
65163         function checkClassLikeDeclaration(node) {
65164             checkGrammarClassLikeDeclaration(node);
65165             checkDecorators(node);
65166             if (node.name) {
65167                 checkTypeNameIsReserved(node.name, ts.Diagnostics.Class_name_cannot_be_0);
65168                 checkCollisionWithRequireExportsInGeneratedCode(node, node.name);
65169                 checkCollisionWithGlobalPromiseInGeneratedCode(node, node.name);
65170                 if (!(node.flags & 8388608 /* Ambient */)) {
65171                     checkClassNameCollisionWithObject(node.name);
65172                 }
65173             }
65174             checkTypeParameters(ts.getEffectiveTypeParameterDeclarations(node));
65175             checkExportsOnMergedDeclarations(node);
65176             var symbol = getSymbolOfNode(node);
65177             var type = getDeclaredTypeOfSymbol(symbol);
65178             var typeWithThis = getTypeWithThisArgument(type);
65179             var staticType = getTypeOfSymbol(symbol);
65180             checkTypeParameterListsIdentical(symbol);
65181             checkClassForDuplicateDeclarations(node);
65182             // Only check for reserved static identifiers on non-ambient context.
65183             if (!(node.flags & 8388608 /* Ambient */)) {
65184                 checkClassForStaticPropertyNameConflicts(node);
65185             }
65186             var baseTypeNode = ts.getEffectiveBaseTypeNode(node);
65187             if (baseTypeNode) {
65188                 ts.forEach(baseTypeNode.typeArguments, checkSourceElement);
65189                 if (languageVersion < 2 /* ES2015 */) {
65190                     checkExternalEmitHelpers(baseTypeNode.parent, 1 /* Extends */);
65191                 }
65192                 // check both @extends and extends if both are specified.
65193                 var extendsNode = ts.getClassExtendsHeritageElement(node);
65194                 if (extendsNode && extendsNode !== baseTypeNode) {
65195                     checkExpression(extendsNode.expression);
65196                 }
65197                 var baseTypes = getBaseTypes(type);
65198                 if (baseTypes.length && produceDiagnostics) {
65199                     var baseType_1 = baseTypes[0];
65200                     var baseConstructorType = getBaseConstructorTypeOfClass(type);
65201                     var staticBaseType = getApparentType(baseConstructorType);
65202                     checkBaseTypeAccessibility(staticBaseType, baseTypeNode);
65203                     checkSourceElement(baseTypeNode.expression);
65204                     if (ts.some(baseTypeNode.typeArguments)) {
65205                         ts.forEach(baseTypeNode.typeArguments, checkSourceElement);
65206                         for (var _i = 0, _a = getConstructorsForTypeArguments(staticBaseType, baseTypeNode.typeArguments, baseTypeNode); _i < _a.length; _i++) {
65207                             var constructor = _a[_i];
65208                             if (!checkTypeArgumentConstraints(baseTypeNode, constructor.typeParameters)) {
65209                                 break;
65210                             }
65211                         }
65212                     }
65213                     var baseWithThis = getTypeWithThisArgument(baseType_1, type.thisType);
65214                     if (!checkTypeAssignableTo(typeWithThis, baseWithThis, /*errorNode*/ undefined)) {
65215                         issueMemberSpecificError(node, typeWithThis, baseWithThis, ts.Diagnostics.Class_0_incorrectly_extends_base_class_1);
65216                     }
65217                     else {
65218                         // Report static side error only when instance type is assignable
65219                         checkTypeAssignableTo(staticType, getTypeWithoutSignatures(staticBaseType), node.name || node, ts.Diagnostics.Class_static_side_0_incorrectly_extends_base_class_static_side_1);
65220                     }
65221                     if (baseConstructorType.flags & 8650752 /* TypeVariable */ && !isMixinConstructorType(staticType)) {
65222                         error(node.name || node, ts.Diagnostics.A_mixin_class_must_have_a_constructor_with_a_single_rest_parameter_of_type_any);
65223                     }
65224                     if (!(staticBaseType.symbol && staticBaseType.symbol.flags & 32 /* Class */) && !(baseConstructorType.flags & 8650752 /* TypeVariable */)) {
65225                         // When the static base type is a "class-like" constructor function (but not actually a class), we verify
65226                         // that all instantiated base constructor signatures return the same type.
65227                         var constructors = getInstantiatedConstructorsForTypeArguments(staticBaseType, baseTypeNode.typeArguments, baseTypeNode);
65228                         if (ts.forEach(constructors, function (sig) { return !isJSConstructor(sig.declaration) && !isTypeIdenticalTo(getReturnTypeOfSignature(sig), baseType_1); })) {
65229                             error(baseTypeNode.expression, ts.Diagnostics.Base_constructors_must_all_have_the_same_return_type);
65230                         }
65231                     }
65232                     checkKindsOfPropertyMemberOverrides(type, baseType_1);
65233                 }
65234             }
65235             var implementedTypeNodes = ts.getEffectiveImplementsTypeNodes(node);
65236             if (implementedTypeNodes) {
65237                 for (var _b = 0, implementedTypeNodes_1 = implementedTypeNodes; _b < implementedTypeNodes_1.length; _b++) {
65238                     var typeRefNode = implementedTypeNodes_1[_b];
65239                     if (!ts.isEntityNameExpression(typeRefNode.expression)) {
65240                         error(typeRefNode.expression, ts.Diagnostics.A_class_can_only_implement_an_identifier_Slashqualified_name_with_optional_type_arguments);
65241                     }
65242                     checkTypeReferenceNode(typeRefNode);
65243                     if (produceDiagnostics) {
65244                         var t = getReducedType(getTypeFromTypeNode(typeRefNode));
65245                         if (t !== errorType) {
65246                             if (isValidBaseType(t)) {
65247                                 var genericDiag = t.symbol && t.symbol.flags & 32 /* Class */ ?
65248                                     ts.Diagnostics.Class_0_incorrectly_implements_class_1_Did_you_mean_to_extend_1_and_inherit_its_members_as_a_subclass :
65249                                     ts.Diagnostics.Class_0_incorrectly_implements_interface_1;
65250                                 var baseWithThis = getTypeWithThisArgument(t, type.thisType);
65251                                 if (!checkTypeAssignableTo(typeWithThis, baseWithThis, /*errorNode*/ undefined)) {
65252                                     issueMemberSpecificError(node, typeWithThis, baseWithThis, genericDiag);
65253                                 }
65254                             }
65255                             else {
65256                                 error(typeRefNode, ts.Diagnostics.A_class_can_only_implement_an_object_type_or_intersection_of_object_types_with_statically_known_members);
65257                             }
65258                         }
65259                     }
65260                 }
65261             }
65262             if (produceDiagnostics) {
65263                 checkIndexConstraints(type);
65264                 checkTypeForDuplicateIndexSignatures(node);
65265                 checkPropertyInitialization(node);
65266             }
65267         }
65268         function issueMemberSpecificError(node, typeWithThis, baseWithThis, broadDiag) {
65269             // iterate over all implemented properties and issue errors on each one which isn't compatible, rather than the class as a whole, if possible
65270             var issuedMemberError = false;
65271             var _loop_19 = function (member) {
65272                 if (ts.hasStaticModifier(member)) {
65273                     return "continue";
65274                 }
65275                 var declaredProp = member.name && getSymbolAtLocation(member.name) || getSymbolAtLocation(member);
65276                 if (declaredProp) {
65277                     var prop = getPropertyOfType(typeWithThis, declaredProp.escapedName);
65278                     var baseProp = getPropertyOfType(baseWithThis, declaredProp.escapedName);
65279                     if (prop && baseProp) {
65280                         var rootChain = function () { return ts.chainDiagnosticMessages(
65281                         /*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)); };
65282                         if (!checkTypeAssignableTo(getTypeOfSymbol(prop), getTypeOfSymbol(baseProp), member.name || member, /*message*/ undefined, rootChain)) {
65283                             issuedMemberError = true;
65284                         }
65285                     }
65286                 }
65287             };
65288             for (var _i = 0, _a = node.members; _i < _a.length; _i++) {
65289                 var member = _a[_i];
65290                 _loop_19(member);
65291             }
65292             if (!issuedMemberError) {
65293                 // check again with diagnostics to generate a less-specific error
65294                 checkTypeAssignableTo(typeWithThis, baseWithThis, node.name || node, broadDiag);
65295             }
65296         }
65297         function checkBaseTypeAccessibility(type, node) {
65298             var signatures = getSignaturesOfType(type, 1 /* Construct */);
65299             if (signatures.length) {
65300                 var declaration = signatures[0].declaration;
65301                 if (declaration && ts.hasModifier(declaration, 8 /* Private */)) {
65302                     var typeClassDeclaration = ts.getClassLikeDeclarationOfSymbol(type.symbol);
65303                     if (!isNodeWithinClass(node, typeClassDeclaration)) {
65304                         error(node, ts.Diagnostics.Cannot_extend_a_class_0_Class_constructor_is_marked_as_private, getFullyQualifiedName(type.symbol));
65305                     }
65306                 }
65307             }
65308         }
65309         function getTargetSymbol(s) {
65310             // if symbol is instantiated its flags are not copied from the 'target'
65311             // so we'll need to get back original 'target' symbol to work with correct set of flags
65312             return ts.getCheckFlags(s) & 1 /* Instantiated */ ? s.target : s;
65313         }
65314         function getClassOrInterfaceDeclarationsOfSymbol(symbol) {
65315             return ts.filter(symbol.declarations, function (d) {
65316                 return d.kind === 245 /* ClassDeclaration */ || d.kind === 246 /* InterfaceDeclaration */;
65317             });
65318         }
65319         function checkKindsOfPropertyMemberOverrides(type, baseType) {
65320             // TypeScript 1.0 spec (April 2014): 8.2.3
65321             // A derived class inherits all members from its base class it doesn't override.
65322             // Inheritance means that a derived class implicitly contains all non - overridden members of the base class.
65323             // Both public and private property members are inherited, but only public property members can be overridden.
65324             // A property member in a derived class is said to override a property member in a base class
65325             // when the derived class property member has the same name and kind(instance or static)
65326             // as the base class property member.
65327             // The type of an overriding property member must be assignable(section 3.8.4)
65328             // to the type of the overridden property member, or otherwise a compile - time error occurs.
65329             // Base class instance member functions can be overridden by derived class instance member functions,
65330             // but not by other kinds of members.
65331             // Base class instance member variables and accessors can be overridden by
65332             // derived class instance member variables and accessors, but not by other kinds of members.
65333             // NOTE: assignability is checked in checkClassDeclaration
65334             var baseProperties = getPropertiesOfType(baseType);
65335             basePropertyCheck: for (var _i = 0, baseProperties_1 = baseProperties; _i < baseProperties_1.length; _i++) {
65336                 var baseProperty = baseProperties_1[_i];
65337                 var base = getTargetSymbol(baseProperty);
65338                 if (base.flags & 4194304 /* Prototype */) {
65339                     continue;
65340                 }
65341                 var baseSymbol = getPropertyOfObjectType(type, base.escapedName);
65342                 if (!baseSymbol) {
65343                     continue;
65344                 }
65345                 var derived = getTargetSymbol(baseSymbol);
65346                 var baseDeclarationFlags = ts.getDeclarationModifierFlagsFromSymbol(base);
65347                 ts.Debug.assert(!!derived, "derived should point to something, even if it is the base class' declaration.");
65348                 // In order to resolve whether the inherited method was overridden in the base class or not,
65349                 // we compare the Symbols obtained. Since getTargetSymbol returns the symbol on the *uninstantiated*
65350                 // type declaration, derived and base resolve to the same symbol even in the case of generic classes.
65351                 if (derived === base) {
65352                     // derived class inherits base without override/redeclaration
65353                     var derivedClassDecl = ts.getClassLikeDeclarationOfSymbol(type.symbol);
65354                     // It is an error to inherit an abstract member without implementing it or being declared abstract.
65355                     // If there is no declaration for the derived class (as in the case of class expressions),
65356                     // then the class cannot be declared abstract.
65357                     if (baseDeclarationFlags & 128 /* Abstract */ && (!derivedClassDecl || !ts.hasModifier(derivedClassDecl, 128 /* Abstract */))) {
65358                         // Searches other base types for a declaration that would satisfy the inherited abstract member.
65359                         // (The class may have more than one base type via declaration merging with an interface with the
65360                         // same name.)
65361                         for (var _a = 0, _b = getBaseTypes(type); _a < _b.length; _a++) {
65362                             var otherBaseType = _b[_a];
65363                             if (otherBaseType === baseType)
65364                                 continue;
65365                             var baseSymbol_1 = getPropertyOfObjectType(otherBaseType, base.escapedName);
65366                             var derivedElsewhere = baseSymbol_1 && getTargetSymbol(baseSymbol_1);
65367                             if (derivedElsewhere && derivedElsewhere !== base) {
65368                                 continue basePropertyCheck;
65369                             }
65370                         }
65371                         if (derivedClassDecl.kind === 214 /* ClassExpression */) {
65372                             error(derivedClassDecl, ts.Diagnostics.Non_abstract_class_expression_does_not_implement_inherited_abstract_member_0_from_class_1, symbolToString(baseProperty), typeToString(baseType));
65373                         }
65374                         else {
65375                             error(derivedClassDecl, ts.Diagnostics.Non_abstract_class_0_does_not_implement_inherited_abstract_member_1_from_class_2, typeToString(type), symbolToString(baseProperty), typeToString(baseType));
65376                         }
65377                     }
65378                 }
65379                 else {
65380                     // derived overrides base.
65381                     var derivedDeclarationFlags = ts.getDeclarationModifierFlagsFromSymbol(derived);
65382                     if (baseDeclarationFlags & 8 /* Private */ || derivedDeclarationFlags & 8 /* Private */) {
65383                         // either base or derived property is private - not override, skip it
65384                         continue;
65385                     }
65386                     var errorMessage = void 0;
65387                     var basePropertyFlags = base.flags & 98308 /* PropertyOrAccessor */;
65388                     var derivedPropertyFlags = derived.flags & 98308 /* PropertyOrAccessor */;
65389                     if (basePropertyFlags && derivedPropertyFlags) {
65390                         // property/accessor is overridden with property/accessor
65391                         if (!compilerOptions.useDefineForClassFields
65392                             || baseDeclarationFlags & 128 /* Abstract */ && !(base.valueDeclaration && ts.isPropertyDeclaration(base.valueDeclaration) && base.valueDeclaration.initializer)
65393                             || base.valueDeclaration && base.valueDeclaration.parent.kind === 246 /* InterfaceDeclaration */
65394                             || derived.valueDeclaration && ts.isBinaryExpression(derived.valueDeclaration)) {
65395                             // when the base property is abstract or from an interface, base/derived flags don't need to match
65396                             // same when the derived property is from an assignment
65397                             continue;
65398                         }
65399                         var overriddenInstanceProperty = basePropertyFlags !== 4 /* Property */ && derivedPropertyFlags === 4 /* Property */;
65400                         var overriddenInstanceAccessor = basePropertyFlags === 4 /* Property */ && derivedPropertyFlags !== 4 /* Property */;
65401                         if (overriddenInstanceProperty || overriddenInstanceAccessor) {
65402                             var errorMessage_1 = overriddenInstanceProperty ?
65403                                 ts.Diagnostics._0_is_defined_as_an_accessor_in_class_1_but_is_overridden_here_in_2_as_an_instance_property :
65404                                 ts.Diagnostics._0_is_defined_as_a_property_in_class_1_but_is_overridden_here_in_2_as_an_accessor;
65405                             error(ts.getNameOfDeclaration(derived.valueDeclaration) || derived.valueDeclaration, errorMessage_1, symbolToString(base), typeToString(baseType), typeToString(type));
65406                         }
65407                         else {
65408                             var uninitialized = ts.find(derived.declarations, function (d) { return d.kind === 159 /* PropertyDeclaration */ && !d.initializer; });
65409                             if (uninitialized
65410                                 && !(derived.flags & 33554432 /* Transient */)
65411                                 && !(baseDeclarationFlags & 128 /* Abstract */)
65412                                 && !(derivedDeclarationFlags & 128 /* Abstract */)
65413                                 && !derived.declarations.some(function (d) { return !!(d.flags & 8388608 /* Ambient */); })) {
65414                                 var constructor = findConstructorDeclaration(ts.getClassLikeDeclarationOfSymbol(type.symbol));
65415                                 var propName = uninitialized.name;
65416                                 if (uninitialized.exclamationToken
65417                                     || !constructor
65418                                     || !ts.isIdentifier(propName)
65419                                     || !strictNullChecks
65420                                     || !isPropertyInitializedInConstructor(propName, type, constructor)) {
65421                                     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;
65422                                     error(ts.getNameOfDeclaration(derived.valueDeclaration) || derived.valueDeclaration, errorMessage_2, symbolToString(base), typeToString(baseType));
65423                                 }
65424                             }
65425                         }
65426                         // correct case
65427                         continue;
65428                     }
65429                     else if (isPrototypeProperty(base)) {
65430                         if (isPrototypeProperty(derived) || derived.flags & 4 /* Property */) {
65431                             // method is overridden with method or property -- correct case
65432                             continue;
65433                         }
65434                         else {
65435                             ts.Debug.assert(!!(derived.flags & 98304 /* Accessor */));
65436                             errorMessage = ts.Diagnostics.Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_accessor;
65437                         }
65438                     }
65439                     else if (base.flags & 98304 /* Accessor */) {
65440                         errorMessage = ts.Diagnostics.Class_0_defines_instance_member_accessor_1_but_extended_class_2_defines_it_as_instance_member_function;
65441                     }
65442                     else {
65443                         errorMessage = ts.Diagnostics.Class_0_defines_instance_member_property_1_but_extended_class_2_defines_it_as_instance_member_function;
65444                     }
65445                     error(ts.getNameOfDeclaration(derived.valueDeclaration) || derived.valueDeclaration, errorMessage, typeToString(baseType), symbolToString(base), typeToString(type));
65446                 }
65447             }
65448         }
65449         function getNonInterhitedProperties(type, baseTypes, properties) {
65450             if (!ts.length(baseTypes)) {
65451                 return properties;
65452             }
65453             var seen = ts.createUnderscoreEscapedMap();
65454             ts.forEach(properties, function (p) { seen.set(p.escapedName, p); });
65455             for (var _i = 0, baseTypes_2 = baseTypes; _i < baseTypes_2.length; _i++) {
65456                 var base = baseTypes_2[_i];
65457                 var properties_5 = getPropertiesOfType(getTypeWithThisArgument(base, type.thisType));
65458                 for (var _a = 0, properties_4 = properties_5; _a < properties_4.length; _a++) {
65459                     var prop = properties_4[_a];
65460                     var existing = seen.get(prop.escapedName);
65461                     if (existing && !isPropertyIdenticalTo(existing, prop)) {
65462                         seen.delete(prop.escapedName);
65463                     }
65464                 }
65465             }
65466             return ts.arrayFrom(seen.values());
65467         }
65468         function checkInheritedPropertiesAreIdentical(type, typeNode) {
65469             var baseTypes = getBaseTypes(type);
65470             if (baseTypes.length < 2) {
65471                 return true;
65472             }
65473             var seen = ts.createUnderscoreEscapedMap();
65474             ts.forEach(resolveDeclaredMembers(type).declaredProperties, function (p) { seen.set(p.escapedName, { prop: p, containingType: type }); });
65475             var ok = true;
65476             for (var _i = 0, baseTypes_3 = baseTypes; _i < baseTypes_3.length; _i++) {
65477                 var base = baseTypes_3[_i];
65478                 var properties = getPropertiesOfType(getTypeWithThisArgument(base, type.thisType));
65479                 for (var _a = 0, properties_6 = properties; _a < properties_6.length; _a++) {
65480                     var prop = properties_6[_a];
65481                     var existing = seen.get(prop.escapedName);
65482                     if (!existing) {
65483                         seen.set(prop.escapedName, { prop: prop, containingType: base });
65484                     }
65485                     else {
65486                         var isInheritedProperty = existing.containingType !== type;
65487                         if (isInheritedProperty && !isPropertyIdenticalTo(existing.prop, prop)) {
65488                             ok = false;
65489                             var typeName1 = typeToString(existing.containingType);
65490                             var typeName2 = typeToString(base);
65491                             var errorInfo = ts.chainDiagnosticMessages(/*details*/ undefined, ts.Diagnostics.Named_property_0_of_types_1_and_2_are_not_identical, symbolToString(prop), typeName1, typeName2);
65492                             errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Interface_0_cannot_simultaneously_extend_types_1_and_2, typeToString(type), typeName1, typeName2);
65493                             diagnostics.add(ts.createDiagnosticForNodeFromMessageChain(typeNode, errorInfo));
65494                         }
65495                     }
65496                 }
65497             }
65498             return ok;
65499         }
65500         function checkPropertyInitialization(node) {
65501             if (!strictNullChecks || !strictPropertyInitialization || node.flags & 8388608 /* Ambient */) {
65502                 return;
65503             }
65504             var constructor = findConstructorDeclaration(node);
65505             for (var _i = 0, _a = node.members; _i < _a.length; _i++) {
65506                 var member = _a[_i];
65507                 if (ts.getModifierFlags(member) & 2 /* Ambient */) {
65508                     continue;
65509                 }
65510                 if (isInstancePropertyWithoutInitializer(member)) {
65511                     var propName = member.name;
65512                     if (ts.isIdentifier(propName) || ts.isPrivateIdentifier(propName)) {
65513                         var type = getTypeOfSymbol(getSymbolOfNode(member));
65514                         if (!(type.flags & 3 /* AnyOrUnknown */ || getFalsyFlags(type) & 32768 /* Undefined */)) {
65515                             if (!constructor || !isPropertyInitializedInConstructor(propName, type, constructor)) {
65516                                 error(member.name, ts.Diagnostics.Property_0_has_no_initializer_and_is_not_definitely_assigned_in_the_constructor, ts.declarationNameToString(propName));
65517                             }
65518                         }
65519                     }
65520                 }
65521             }
65522         }
65523         function isInstancePropertyWithoutInitializer(node) {
65524             return node.kind === 159 /* PropertyDeclaration */ &&
65525                 !ts.hasModifier(node, 32 /* Static */ | 128 /* Abstract */) &&
65526                 !node.exclamationToken &&
65527                 !node.initializer;
65528         }
65529         function isPropertyInitializedInConstructor(propName, propType, constructor) {
65530             var reference = ts.createPropertyAccess(ts.createThis(), propName);
65531             reference.expression.parent = reference;
65532             reference.parent = constructor;
65533             reference.flowNode = constructor.returnFlowNode;
65534             var flowType = getFlowTypeOfReference(reference, propType, getOptionalType(propType));
65535             return !(getFalsyFlags(flowType) & 32768 /* Undefined */);
65536         }
65537         function checkInterfaceDeclaration(node) {
65538             // Grammar checking
65539             if (!checkGrammarDecoratorsAndModifiers(node))
65540                 checkGrammarInterfaceDeclaration(node);
65541             checkTypeParameters(node.typeParameters);
65542             if (produceDiagnostics) {
65543                 checkTypeNameIsReserved(node.name, ts.Diagnostics.Interface_name_cannot_be_0);
65544                 checkExportsOnMergedDeclarations(node);
65545                 var symbol = getSymbolOfNode(node);
65546                 checkTypeParameterListsIdentical(symbol);
65547                 // Only check this symbol once
65548                 var firstInterfaceDecl = ts.getDeclarationOfKind(symbol, 246 /* InterfaceDeclaration */);
65549                 if (node === firstInterfaceDecl) {
65550                     var type = getDeclaredTypeOfSymbol(symbol);
65551                     var typeWithThis = getTypeWithThisArgument(type);
65552                     // run subsequent checks only if first set succeeded
65553                     if (checkInheritedPropertiesAreIdentical(type, node.name)) {
65554                         for (var _i = 0, _a = getBaseTypes(type); _i < _a.length; _i++) {
65555                             var baseType = _a[_i];
65556                             checkTypeAssignableTo(typeWithThis, getTypeWithThisArgument(baseType, type.thisType), node.name, ts.Diagnostics.Interface_0_incorrectly_extends_interface_1);
65557                         }
65558                         checkIndexConstraints(type);
65559                     }
65560                 }
65561                 checkObjectTypeForDuplicateDeclarations(node);
65562             }
65563             ts.forEach(ts.getInterfaceBaseTypeNodes(node), function (heritageElement) {
65564                 if (!ts.isEntityNameExpression(heritageElement.expression)) {
65565                     error(heritageElement.expression, ts.Diagnostics.An_interface_can_only_extend_an_identifier_Slashqualified_name_with_optional_type_arguments);
65566                 }
65567                 checkTypeReferenceNode(heritageElement);
65568             });
65569             ts.forEach(node.members, checkSourceElement);
65570             if (produceDiagnostics) {
65571                 checkTypeForDuplicateIndexSignatures(node);
65572                 registerForUnusedIdentifiersCheck(node);
65573             }
65574         }
65575         function checkTypeAliasDeclaration(node) {
65576             // Grammar checking
65577             checkGrammarDecoratorsAndModifiers(node);
65578             checkTypeNameIsReserved(node.name, ts.Diagnostics.Type_alias_name_cannot_be_0);
65579             checkExportsOnMergedDeclarations(node);
65580             checkTypeParameters(node.typeParameters);
65581             checkSourceElement(node.type);
65582             registerForUnusedIdentifiersCheck(node);
65583         }
65584         function computeEnumMemberValues(node) {
65585             var nodeLinks = getNodeLinks(node);
65586             if (!(nodeLinks.flags & 16384 /* EnumValuesComputed */)) {
65587                 nodeLinks.flags |= 16384 /* EnumValuesComputed */;
65588                 var autoValue = 0;
65589                 for (var _i = 0, _a = node.members; _i < _a.length; _i++) {
65590                     var member = _a[_i];
65591                     var value = computeMemberValue(member, autoValue);
65592                     getNodeLinks(member).enumMemberValue = value;
65593                     autoValue = typeof value === "number" ? value + 1 : undefined;
65594                 }
65595             }
65596         }
65597         function computeMemberValue(member, autoValue) {
65598             if (ts.isComputedNonLiteralName(member.name)) {
65599                 error(member.name, ts.Diagnostics.Computed_property_names_are_not_allowed_in_enums);
65600             }
65601             else {
65602                 var text = ts.getTextOfPropertyName(member.name);
65603                 if (isNumericLiteralName(text) && !isInfinityOrNaNString(text)) {
65604                     error(member.name, ts.Diagnostics.An_enum_member_cannot_have_a_numeric_name);
65605                 }
65606             }
65607             if (member.initializer) {
65608                 return computeConstantValue(member);
65609             }
65610             // In ambient non-const numeric enum declarations, enum members without initializers are
65611             // considered computed members (as opposed to having auto-incremented values).
65612             if (member.parent.flags & 8388608 /* Ambient */ && !ts.isEnumConst(member.parent) && getEnumKind(getSymbolOfNode(member.parent)) === 0 /* Numeric */) {
65613                 return undefined;
65614             }
65615             // If the member declaration specifies no value, the member is considered a constant enum member.
65616             // If the member is the first member in the enum declaration, it is assigned the value zero.
65617             // Otherwise, it is assigned the value of the immediately preceding member plus one, and an error
65618             // occurs if the immediately preceding member is not a constant enum member.
65619             if (autoValue !== undefined) {
65620                 return autoValue;
65621             }
65622             error(member.name, ts.Diagnostics.Enum_member_must_have_initializer);
65623             return undefined;
65624         }
65625         function computeConstantValue(member) {
65626             var enumKind = getEnumKind(getSymbolOfNode(member.parent));
65627             var isConstEnum = ts.isEnumConst(member.parent);
65628             var initializer = member.initializer;
65629             var value = enumKind === 1 /* Literal */ && !isLiteralEnumMember(member) ? undefined : evaluate(initializer);
65630             if (value !== undefined) {
65631                 if (isConstEnum && typeof value === "number" && !isFinite(value)) {
65632                     error(initializer, isNaN(value) ?
65633                         ts.Diagnostics.const_enum_member_initializer_was_evaluated_to_disallowed_value_NaN :
65634                         ts.Diagnostics.const_enum_member_initializer_was_evaluated_to_a_non_finite_value);
65635                 }
65636             }
65637             else if (enumKind === 1 /* Literal */) {
65638                 error(initializer, ts.Diagnostics.Computed_values_are_not_permitted_in_an_enum_with_string_valued_members);
65639                 return 0;
65640             }
65641             else if (isConstEnum) {
65642                 error(initializer, ts.Diagnostics.const_enum_member_initializers_can_only_contain_literal_values_and_other_computed_enum_values);
65643             }
65644             else if (member.parent.flags & 8388608 /* Ambient */) {
65645                 error(initializer, ts.Diagnostics.In_ambient_enum_declarations_member_initializer_must_be_constant_expression);
65646             }
65647             else {
65648                 // Only here do we need to check that the initializer is assignable to the enum type.
65649                 var source = checkExpression(initializer);
65650                 if (!isTypeAssignableToKind(source, 296 /* NumberLike */)) {
65651                     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));
65652                 }
65653                 else {
65654                     checkTypeAssignableTo(source, getDeclaredTypeOfSymbol(getSymbolOfNode(member.parent)), initializer, /*headMessage*/ undefined);
65655                 }
65656             }
65657             return value;
65658             function evaluate(expr) {
65659                 switch (expr.kind) {
65660                     case 207 /* PrefixUnaryExpression */:
65661                         var value_2 = evaluate(expr.operand);
65662                         if (typeof value_2 === "number") {
65663                             switch (expr.operator) {
65664                                 case 39 /* PlusToken */: return value_2;
65665                                 case 40 /* MinusToken */: return -value_2;
65666                                 case 54 /* TildeToken */: return ~value_2;
65667                             }
65668                         }
65669                         break;
65670                     case 209 /* BinaryExpression */:
65671                         var left = evaluate(expr.left);
65672                         var right = evaluate(expr.right);
65673                         if (typeof left === "number" && typeof right === "number") {
65674                             switch (expr.operatorToken.kind) {
65675                                 case 51 /* BarToken */: return left | right;
65676                                 case 50 /* AmpersandToken */: return left & right;
65677                                 case 48 /* GreaterThanGreaterThanToken */: return left >> right;
65678                                 case 49 /* GreaterThanGreaterThanGreaterThanToken */: return left >>> right;
65679                                 case 47 /* LessThanLessThanToken */: return left << right;
65680                                 case 52 /* CaretToken */: return left ^ right;
65681                                 case 41 /* AsteriskToken */: return left * right;
65682                                 case 43 /* SlashToken */: return left / right;
65683                                 case 39 /* PlusToken */: return left + right;
65684                                 case 40 /* MinusToken */: return left - right;
65685                                 case 44 /* PercentToken */: return left % right;
65686                                 case 42 /* AsteriskAsteriskToken */: return Math.pow(left, right);
65687                             }
65688                         }
65689                         else if (typeof left === "string" && typeof right === "string" && expr.operatorToken.kind === 39 /* PlusToken */) {
65690                             return left + right;
65691                         }
65692                         break;
65693                     case 10 /* StringLiteral */:
65694                     case 14 /* NoSubstitutionTemplateLiteral */:
65695                         return expr.text;
65696                     case 8 /* NumericLiteral */:
65697                         checkGrammarNumericLiteral(expr);
65698                         return +expr.text;
65699                     case 200 /* ParenthesizedExpression */:
65700                         return evaluate(expr.expression);
65701                     case 75 /* Identifier */:
65702                         var identifier = expr;
65703                         if (isInfinityOrNaNString(identifier.escapedText)) {
65704                             return +(identifier.escapedText);
65705                         }
65706                         return ts.nodeIsMissing(expr) ? 0 : evaluateEnumMember(expr, getSymbolOfNode(member.parent), identifier.escapedText);
65707                     case 195 /* ElementAccessExpression */:
65708                     case 194 /* PropertyAccessExpression */:
65709                         var ex = expr;
65710                         if (isConstantMemberAccess(ex)) {
65711                             var type = getTypeOfExpression(ex.expression);
65712                             if (type.symbol && type.symbol.flags & 384 /* Enum */) {
65713                                 var name = void 0;
65714                                 if (ex.kind === 194 /* PropertyAccessExpression */) {
65715                                     name = ex.name.escapedText;
65716                                 }
65717                                 else {
65718                                     name = ts.escapeLeadingUnderscores(ts.cast(ex.argumentExpression, ts.isLiteralExpression).text);
65719                                 }
65720                                 return evaluateEnumMember(expr, type.symbol, name);
65721                             }
65722                         }
65723                         break;
65724                 }
65725                 return undefined;
65726             }
65727             function evaluateEnumMember(expr, enumSymbol, name) {
65728                 var memberSymbol = enumSymbol.exports.get(name);
65729                 if (memberSymbol) {
65730                     var declaration = memberSymbol.valueDeclaration;
65731                     if (declaration !== member) {
65732                         if (isBlockScopedNameDeclaredBeforeUse(declaration, member)) {
65733                             return getEnumMemberValue(declaration);
65734                         }
65735                         error(expr, ts.Diagnostics.A_member_initializer_in_a_enum_declaration_cannot_reference_members_declared_after_it_including_members_defined_in_other_enums);
65736                         return 0;
65737                     }
65738                     else {
65739                         error(expr, ts.Diagnostics.Property_0_is_used_before_being_assigned, symbolToString(memberSymbol));
65740                     }
65741                 }
65742                 return undefined;
65743             }
65744         }
65745         function isConstantMemberAccess(node) {
65746             return node.kind === 75 /* Identifier */ ||
65747                 node.kind === 194 /* PropertyAccessExpression */ && isConstantMemberAccess(node.expression) ||
65748                 node.kind === 195 /* ElementAccessExpression */ && isConstantMemberAccess(node.expression) &&
65749                     ts.isStringLiteralLike(node.argumentExpression);
65750         }
65751         function checkEnumDeclaration(node) {
65752             if (!produceDiagnostics) {
65753                 return;
65754             }
65755             // Grammar checking
65756             checkGrammarDecoratorsAndModifiers(node);
65757             checkTypeNameIsReserved(node.name, ts.Diagnostics.Enum_name_cannot_be_0);
65758             checkCollisionWithRequireExportsInGeneratedCode(node, node.name);
65759             checkCollisionWithGlobalPromiseInGeneratedCode(node, node.name);
65760             checkExportsOnMergedDeclarations(node);
65761             node.members.forEach(checkEnumMember);
65762             computeEnumMemberValues(node);
65763             // Spec 2014 - Section 9.3:
65764             // It isn't possible for one enum declaration to continue the automatic numbering sequence of another,
65765             // and when an enum type has multiple declarations, only one declaration is permitted to omit a value
65766             // for the first member.
65767             //
65768             // Only perform this check once per symbol
65769             var enumSymbol = getSymbolOfNode(node);
65770             var firstDeclaration = ts.getDeclarationOfKind(enumSymbol, node.kind);
65771             if (node === firstDeclaration) {
65772                 if (enumSymbol.declarations.length > 1) {
65773                     var enumIsConst_1 = ts.isEnumConst(node);
65774                     // check that const is placed\omitted on all enum declarations
65775                     ts.forEach(enumSymbol.declarations, function (decl) {
65776                         if (ts.isEnumDeclaration(decl) && ts.isEnumConst(decl) !== enumIsConst_1) {
65777                             error(ts.getNameOfDeclaration(decl), ts.Diagnostics.Enum_declarations_must_all_be_const_or_non_const);
65778                         }
65779                     });
65780                 }
65781                 var seenEnumMissingInitialInitializer_1 = false;
65782                 ts.forEach(enumSymbol.declarations, function (declaration) {
65783                     // return true if we hit a violation of the rule, false otherwise
65784                     if (declaration.kind !== 248 /* EnumDeclaration */) {
65785                         return false;
65786                     }
65787                     var enumDeclaration = declaration;
65788                     if (!enumDeclaration.members.length) {
65789                         return false;
65790                     }
65791                     var firstEnumMember = enumDeclaration.members[0];
65792                     if (!firstEnumMember.initializer) {
65793                         if (seenEnumMissingInitialInitializer_1) {
65794                             error(firstEnumMember.name, ts.Diagnostics.In_an_enum_with_multiple_declarations_only_one_declaration_can_omit_an_initializer_for_its_first_enum_element);
65795                         }
65796                         else {
65797                             seenEnumMissingInitialInitializer_1 = true;
65798                         }
65799                     }
65800                 });
65801             }
65802         }
65803         function checkEnumMember(node) {
65804             if (ts.isPrivateIdentifier(node.name)) {
65805                 error(node, ts.Diagnostics.An_enum_member_cannot_be_named_with_a_private_identifier);
65806             }
65807         }
65808         function getFirstNonAmbientClassOrFunctionDeclaration(symbol) {
65809             var declarations = symbol.declarations;
65810             for (var _i = 0, declarations_8 = declarations; _i < declarations_8.length; _i++) {
65811                 var declaration = declarations_8[_i];
65812                 if ((declaration.kind === 245 /* ClassDeclaration */ ||
65813                     (declaration.kind === 244 /* FunctionDeclaration */ && ts.nodeIsPresent(declaration.body))) &&
65814                     !(declaration.flags & 8388608 /* Ambient */)) {
65815                     return declaration;
65816                 }
65817             }
65818             return undefined;
65819         }
65820         function inSameLexicalScope(node1, node2) {
65821             var container1 = ts.getEnclosingBlockScopeContainer(node1);
65822             var container2 = ts.getEnclosingBlockScopeContainer(node2);
65823             if (isGlobalSourceFile(container1)) {
65824                 return isGlobalSourceFile(container2);
65825             }
65826             else if (isGlobalSourceFile(container2)) {
65827                 return false;
65828             }
65829             else {
65830                 return container1 === container2;
65831             }
65832         }
65833         function checkModuleDeclaration(node) {
65834             if (produceDiagnostics) {
65835                 // Grammar checking
65836                 var isGlobalAugmentation = ts.isGlobalScopeAugmentation(node);
65837                 var inAmbientContext = node.flags & 8388608 /* Ambient */;
65838                 if (isGlobalAugmentation && !inAmbientContext) {
65839                     error(node.name, ts.Diagnostics.Augmentations_for_the_global_scope_should_have_declare_modifier_unless_they_appear_in_already_ambient_context);
65840                 }
65841                 var isAmbientExternalModule = ts.isAmbientModule(node);
65842                 var contextErrorMessage = isAmbientExternalModule
65843                     ? ts.Diagnostics.An_ambient_module_declaration_is_only_allowed_at_the_top_level_in_a_file
65844                     : ts.Diagnostics.A_namespace_declaration_is_only_allowed_in_a_namespace_or_module;
65845                 if (checkGrammarModuleElementContext(node, contextErrorMessage)) {
65846                     // If we hit a module declaration in an illegal context, just bail out to avoid cascading errors.
65847                     return;
65848                 }
65849                 if (!checkGrammarDecoratorsAndModifiers(node)) {
65850                     if (!inAmbientContext && node.name.kind === 10 /* StringLiteral */) {
65851                         grammarErrorOnNode(node.name, ts.Diagnostics.Only_ambient_modules_can_use_quoted_names);
65852                     }
65853                 }
65854                 if (ts.isIdentifier(node.name)) {
65855                     checkCollisionWithRequireExportsInGeneratedCode(node, node.name);
65856                     checkCollisionWithGlobalPromiseInGeneratedCode(node, node.name);
65857                 }
65858                 checkExportsOnMergedDeclarations(node);
65859                 var symbol = getSymbolOfNode(node);
65860                 // The following checks only apply on a non-ambient instantiated module declaration.
65861                 if (symbol.flags & 512 /* ValueModule */
65862                     && !inAmbientContext
65863                     && symbol.declarations.length > 1
65864                     && isInstantiatedModule(node, !!compilerOptions.preserveConstEnums || !!compilerOptions.isolatedModules)) {
65865                     var firstNonAmbientClassOrFunc = getFirstNonAmbientClassOrFunctionDeclaration(symbol);
65866                     if (firstNonAmbientClassOrFunc) {
65867                         if (ts.getSourceFileOfNode(node) !== ts.getSourceFileOfNode(firstNonAmbientClassOrFunc)) {
65868                             error(node.name, ts.Diagnostics.A_namespace_declaration_cannot_be_in_a_different_file_from_a_class_or_function_with_which_it_is_merged);
65869                         }
65870                         else if (node.pos < firstNonAmbientClassOrFunc.pos) {
65871                             error(node.name, ts.Diagnostics.A_namespace_declaration_cannot_be_located_prior_to_a_class_or_function_with_which_it_is_merged);
65872                         }
65873                     }
65874                     // if the module merges with a class declaration in the same lexical scope,
65875                     // we need to track this to ensure the correct emit.
65876                     var mergedClass = ts.getDeclarationOfKind(symbol, 245 /* ClassDeclaration */);
65877                     if (mergedClass &&
65878                         inSameLexicalScope(node, mergedClass)) {
65879                         getNodeLinks(node).flags |= 32768 /* LexicalModuleMergesWithClass */;
65880                     }
65881                 }
65882                 if (isAmbientExternalModule) {
65883                     if (ts.isExternalModuleAugmentation(node)) {
65884                         // body of the augmentation should be checked for consistency only if augmentation was applied to its target (either global scope or module)
65885                         // otherwise we'll be swamped in cascading errors.
65886                         // We can detect if augmentation was applied using following rules:
65887                         // - augmentation for a global scope is always applied
65888                         // - augmentation for some external module is applied if symbol for augmentation is merged (it was combined with target module).
65889                         var checkBody = isGlobalAugmentation || (getSymbolOfNode(node).flags & 33554432 /* Transient */);
65890                         if (checkBody && node.body) {
65891                             for (var _i = 0, _a = node.body.statements; _i < _a.length; _i++) {
65892                                 var statement = _a[_i];
65893                                 checkModuleAugmentationElement(statement, isGlobalAugmentation);
65894                             }
65895                         }
65896                     }
65897                     else if (isGlobalSourceFile(node.parent)) {
65898                         if (isGlobalAugmentation) {
65899                             error(node.name, ts.Diagnostics.Augmentations_for_the_global_scope_can_only_be_directly_nested_in_external_modules_or_ambient_module_declarations);
65900                         }
65901                         else if (ts.isExternalModuleNameRelative(ts.getTextOfIdentifierOrLiteral(node.name))) {
65902                             error(node.name, ts.Diagnostics.Ambient_module_declaration_cannot_specify_relative_module_name);
65903                         }
65904                     }
65905                     else {
65906                         if (isGlobalAugmentation) {
65907                             error(node.name, ts.Diagnostics.Augmentations_for_the_global_scope_can_only_be_directly_nested_in_external_modules_or_ambient_module_declarations);
65908                         }
65909                         else {
65910                             // Node is not an augmentation and is not located on the script level.
65911                             // This means that this is declaration of ambient module that is located in other module or namespace which is prohibited.
65912                             error(node.name, ts.Diagnostics.Ambient_modules_cannot_be_nested_in_other_modules_or_namespaces);
65913                         }
65914                     }
65915                 }
65916             }
65917             if (node.body) {
65918                 checkSourceElement(node.body);
65919                 if (!ts.isGlobalScopeAugmentation(node)) {
65920                     registerForUnusedIdentifiersCheck(node);
65921                 }
65922             }
65923         }
65924         function checkModuleAugmentationElement(node, isGlobalAugmentation) {
65925             switch (node.kind) {
65926                 case 225 /* VariableStatement */:
65927                     // error each individual name in variable statement instead of marking the entire variable statement
65928                     for (var _i = 0, _a = node.declarationList.declarations; _i < _a.length; _i++) {
65929                         var decl = _a[_i];
65930                         checkModuleAugmentationElement(decl, isGlobalAugmentation);
65931                     }
65932                     break;
65933                 case 259 /* ExportAssignment */:
65934                 case 260 /* ExportDeclaration */:
65935                     grammarErrorOnFirstToken(node, ts.Diagnostics.Exports_and_export_assignments_are_not_permitted_in_module_augmentations);
65936                     break;
65937                 case 253 /* ImportEqualsDeclaration */:
65938                 case 254 /* ImportDeclaration */:
65939                     grammarErrorOnFirstToken(node, ts.Diagnostics.Imports_are_not_permitted_in_module_augmentations_Consider_moving_them_to_the_enclosing_external_module);
65940                     break;
65941                 case 191 /* BindingElement */:
65942                 case 242 /* VariableDeclaration */:
65943                     var name = node.name;
65944                     if (ts.isBindingPattern(name)) {
65945                         for (var _b = 0, _c = name.elements; _b < _c.length; _b++) {
65946                             var el = _c[_b];
65947                             // mark individual names in binding pattern
65948                             checkModuleAugmentationElement(el, isGlobalAugmentation);
65949                         }
65950                         break;
65951                     }
65952                 // falls through
65953                 case 245 /* ClassDeclaration */:
65954                 case 248 /* EnumDeclaration */:
65955                 case 244 /* FunctionDeclaration */:
65956                 case 246 /* InterfaceDeclaration */:
65957                 case 249 /* ModuleDeclaration */:
65958                 case 247 /* TypeAliasDeclaration */:
65959                     if (isGlobalAugmentation) {
65960                         return;
65961                     }
65962                     var symbol = getSymbolOfNode(node);
65963                     if (symbol) {
65964                         // module augmentations cannot introduce new names on the top level scope of the module
65965                         // this is done it two steps
65966                         // 1. quick check - if symbol for node is not merged - this is local symbol to this augmentation - report error
65967                         // 2. main check - report error if value declaration of the parent symbol is module augmentation)
65968                         var reportError = !(symbol.flags & 33554432 /* Transient */);
65969                         if (!reportError) {
65970                             // symbol should not originate in augmentation
65971                             reportError = !!symbol.parent && ts.isExternalModuleAugmentation(symbol.parent.declarations[0]);
65972                         }
65973                     }
65974                     break;
65975             }
65976         }
65977         function getFirstNonModuleExportsIdentifier(node) {
65978             switch (node.kind) {
65979                 case 75 /* Identifier */:
65980                     return node;
65981                 case 153 /* QualifiedName */:
65982                     do {
65983                         node = node.left;
65984                     } while (node.kind !== 75 /* Identifier */);
65985                     return node;
65986                 case 194 /* PropertyAccessExpression */:
65987                     do {
65988                         if (ts.isModuleExportsAccessExpression(node.expression) && !ts.isPrivateIdentifier(node.name)) {
65989                             return node.name;
65990                         }
65991                         node = node.expression;
65992                     } while (node.kind !== 75 /* Identifier */);
65993                     return node;
65994             }
65995         }
65996         function checkExternalImportOrExportDeclaration(node) {
65997             var moduleName = ts.getExternalModuleName(node);
65998             if (!moduleName || ts.nodeIsMissing(moduleName)) {
65999                 // Should be a parse error.
66000                 return false;
66001             }
66002             if (!ts.isStringLiteral(moduleName)) {
66003                 error(moduleName, ts.Diagnostics.String_literal_expected);
66004                 return false;
66005             }
66006             var inAmbientExternalModule = node.parent.kind === 250 /* ModuleBlock */ && ts.isAmbientModule(node.parent.parent);
66007             if (node.parent.kind !== 290 /* SourceFile */ && !inAmbientExternalModule) {
66008                 error(moduleName, node.kind === 260 /* ExportDeclaration */ ?
66009                     ts.Diagnostics.Export_declarations_are_not_permitted_in_a_namespace :
66010                     ts.Diagnostics.Import_declarations_in_a_namespace_cannot_reference_a_module);
66011                 return false;
66012             }
66013             if (inAmbientExternalModule && ts.isExternalModuleNameRelative(moduleName.text)) {
66014                 // we have already reported errors on top level imports/exports in external module augmentations in checkModuleDeclaration
66015                 // no need to do this again.
66016                 if (!isTopLevelInExternalModuleAugmentation(node)) {
66017                     // TypeScript 1.0 spec (April 2013): 12.1.6
66018                     // An ExternalImportDeclaration in an AmbientExternalModuleDeclaration may reference
66019                     // other external modules only through top - level external module names.
66020                     // Relative external module names are not permitted.
66021                     error(node, ts.Diagnostics.Import_or_export_declaration_in_an_ambient_module_declaration_cannot_reference_module_through_relative_module_name);
66022                     return false;
66023                 }
66024             }
66025             return true;
66026         }
66027         function checkAliasSymbol(node) {
66028             var symbol = getSymbolOfNode(node);
66029             var target = resolveAlias(symbol);
66030             var shouldSkipWithJSExpandoTargets = symbol.flags & 67108864 /* Assignment */;
66031             if (!shouldSkipWithJSExpandoTargets && target !== unknownSymbol) {
66032                 // For external modules symbol represents local symbol for an alias.
66033                 // This local symbol will merge any other local declarations (excluding other aliases)
66034                 // and symbol.flags will contains combined representation for all merged declaration.
66035                 // Based on symbol.flags we can compute a set of excluded meanings (meaning that resolved alias should not have,
66036                 // otherwise it will conflict with some local declaration). Note that in addition to normal flags we include matching SymbolFlags.Export*
66037                 // in order to prevent collisions with declarations that were exported from the current module (they still contribute to local names).
66038                 symbol = getMergedSymbol(symbol.exportSymbol || symbol);
66039                 var excludedMeanings = (symbol.flags & (111551 /* Value */ | 1048576 /* ExportValue */) ? 111551 /* Value */ : 0) |
66040                     (symbol.flags & 788968 /* Type */ ? 788968 /* Type */ : 0) |
66041                     (symbol.flags & 1920 /* Namespace */ ? 1920 /* Namespace */ : 0);
66042                 if (target.flags & excludedMeanings) {
66043                     var message = node.kind === 263 /* ExportSpecifier */ ?
66044                         ts.Diagnostics.Export_declaration_conflicts_with_exported_declaration_of_0 :
66045                         ts.Diagnostics.Import_declaration_conflicts_with_local_declaration_of_0;
66046                     error(node, message, symbolToString(symbol));
66047                 }
66048                 // Don't allow to re-export something with no value side when `--isolatedModules` is set.
66049                 if (compilerOptions.isolatedModules
66050                     && node.kind === 263 /* ExportSpecifier */
66051                     && !node.parent.parent.isTypeOnly
66052                     && !(target.flags & 111551 /* Value */)
66053                     && !(node.flags & 8388608 /* Ambient */)) {
66054                     error(node, ts.Diagnostics.Re_exporting_a_type_when_the_isolatedModules_flag_is_provided_requires_using_export_type);
66055                 }
66056             }
66057         }
66058         function checkImportBinding(node) {
66059             checkCollisionWithRequireExportsInGeneratedCode(node, node.name);
66060             checkCollisionWithGlobalPromiseInGeneratedCode(node, node.name);
66061             checkAliasSymbol(node);
66062         }
66063         function checkImportDeclaration(node) {
66064             if (checkGrammarModuleElementContext(node, ts.Diagnostics.An_import_declaration_can_only_be_used_in_a_namespace_or_module)) {
66065                 // If we hit an import declaration in an illegal context, just bail out to avoid cascading errors.
66066                 return;
66067             }
66068             if (!checkGrammarDecoratorsAndModifiers(node) && ts.hasModifiers(node)) {
66069                 grammarErrorOnFirstToken(node, ts.Diagnostics.An_import_declaration_cannot_have_modifiers);
66070             }
66071             if (checkExternalImportOrExportDeclaration(node)) {
66072                 var importClause = node.importClause;
66073                 if (importClause && !checkGrammarImportClause(importClause)) {
66074                     if (importClause.name) {
66075                         checkImportBinding(importClause);
66076                     }
66077                     if (importClause.namedBindings) {
66078                         if (importClause.namedBindings.kind === 256 /* NamespaceImport */) {
66079                             checkImportBinding(importClause.namedBindings);
66080                         }
66081                         else {
66082                             var moduleExisted = resolveExternalModuleName(node, node.moduleSpecifier);
66083                             if (moduleExisted) {
66084                                 ts.forEach(importClause.namedBindings.elements, checkImportBinding);
66085                             }
66086                         }
66087                     }
66088                 }
66089             }
66090         }
66091         function checkImportEqualsDeclaration(node) {
66092             if (checkGrammarModuleElementContext(node, ts.Diagnostics.An_import_declaration_can_only_be_used_in_a_namespace_or_module)) {
66093                 // If we hit an import declaration in an illegal context, just bail out to avoid cascading errors.
66094                 return;
66095             }
66096             checkGrammarDecoratorsAndModifiers(node);
66097             if (ts.isInternalModuleImportEqualsDeclaration(node) || checkExternalImportOrExportDeclaration(node)) {
66098                 checkImportBinding(node);
66099                 if (ts.hasModifier(node, 1 /* Export */)) {
66100                     markExportAsReferenced(node);
66101                 }
66102                 if (node.moduleReference.kind !== 265 /* ExternalModuleReference */) {
66103                     var target = resolveAlias(getSymbolOfNode(node));
66104                     if (target !== unknownSymbol) {
66105                         if (target.flags & 111551 /* Value */) {
66106                             // Target is a value symbol, check that it is not hidden by a local declaration with the same name
66107                             var moduleName = ts.getFirstIdentifier(node.moduleReference);
66108                             if (!(resolveEntityName(moduleName, 111551 /* Value */ | 1920 /* Namespace */).flags & 1920 /* Namespace */)) {
66109                                 error(moduleName, ts.Diagnostics.Module_0_is_hidden_by_a_local_declaration_with_the_same_name, ts.declarationNameToString(moduleName));
66110                             }
66111                         }
66112                         if (target.flags & 788968 /* Type */) {
66113                             checkTypeNameIsReserved(node.name, ts.Diagnostics.Import_name_cannot_be_0);
66114                         }
66115                     }
66116                 }
66117                 else {
66118                     if (moduleKind >= ts.ModuleKind.ES2015 && !(node.flags & 8388608 /* Ambient */)) {
66119                         // Import equals declaration is deprecated in es6 or above
66120                         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);
66121                     }
66122                 }
66123             }
66124         }
66125         function checkExportDeclaration(node) {
66126             if (checkGrammarModuleElementContext(node, ts.Diagnostics.An_export_declaration_can_only_be_used_in_a_module)) {
66127                 // If we hit an export in an illegal context, just bail out to avoid cascading errors.
66128                 return;
66129             }
66130             if (!checkGrammarDecoratorsAndModifiers(node) && ts.hasModifiers(node)) {
66131                 grammarErrorOnFirstToken(node, ts.Diagnostics.An_export_declaration_cannot_have_modifiers);
66132             }
66133             if (node.moduleSpecifier && node.exportClause && ts.isNamedExports(node.exportClause) && ts.length(node.exportClause.elements) && languageVersion === 0 /* ES3 */) {
66134                 checkExternalEmitHelpers(node, 1048576 /* CreateBinding */);
66135             }
66136             checkGrammarExportDeclaration(node);
66137             if (!node.moduleSpecifier || checkExternalImportOrExportDeclaration(node)) {
66138                 if (node.exportClause && !ts.isNamespaceExport(node.exportClause)) {
66139                     // export { x, y }
66140                     // export { x, y } from "foo"
66141                     ts.forEach(node.exportClause.elements, checkExportSpecifier);
66142                     var inAmbientExternalModule = node.parent.kind === 250 /* ModuleBlock */ && ts.isAmbientModule(node.parent.parent);
66143                     var inAmbientNamespaceDeclaration = !inAmbientExternalModule && node.parent.kind === 250 /* ModuleBlock */ &&
66144                         !node.moduleSpecifier && node.flags & 8388608 /* Ambient */;
66145                     if (node.parent.kind !== 290 /* SourceFile */ && !inAmbientExternalModule && !inAmbientNamespaceDeclaration) {
66146                         error(node, ts.Diagnostics.Export_declarations_are_not_permitted_in_a_namespace);
66147                     }
66148                 }
66149                 else {
66150                     // export * from "foo"
66151                     var moduleSymbol = resolveExternalModuleName(node, node.moduleSpecifier);
66152                     if (moduleSymbol && hasExportAssignmentSymbol(moduleSymbol)) {
66153                         error(node.moduleSpecifier, ts.Diagnostics.Module_0_uses_export_and_cannot_be_used_with_export_Asterisk, symbolToString(moduleSymbol));
66154                     }
66155                     else if (node.exportClause) {
66156                         checkAliasSymbol(node.exportClause);
66157                     }
66158                     if (moduleKind !== ts.ModuleKind.System && moduleKind < ts.ModuleKind.ES2015) {
66159                         checkExternalEmitHelpers(node, 65536 /* ExportStar */);
66160                     }
66161                 }
66162             }
66163         }
66164         function checkGrammarExportDeclaration(node) {
66165             var _a;
66166             var isTypeOnlyExportStar = node.isTypeOnly && ((_a = node.exportClause) === null || _a === void 0 ? void 0 : _a.kind) !== 261 /* NamedExports */;
66167             if (isTypeOnlyExportStar) {
66168                 grammarErrorOnNode(node, ts.Diagnostics.Only_named_exports_may_use_export_type);
66169             }
66170             return !isTypeOnlyExportStar;
66171         }
66172         function checkGrammarModuleElementContext(node, errorMessage) {
66173             var isInAppropriateContext = node.parent.kind === 290 /* SourceFile */ || node.parent.kind === 250 /* ModuleBlock */ || node.parent.kind === 249 /* ModuleDeclaration */;
66174             if (!isInAppropriateContext) {
66175                 grammarErrorOnFirstToken(node, errorMessage);
66176             }
66177             return !isInAppropriateContext;
66178         }
66179         function importClauseContainsReferencedImport(importClause) {
66180             return ts.forEachImportClauseDeclaration(importClause, function (declaration) {
66181                 return !!getSymbolOfNode(declaration).isReferenced;
66182             });
66183         }
66184         function importClauseContainsConstEnumUsedAsValue(importClause) {
66185             return ts.forEachImportClauseDeclaration(importClause, function (declaration) {
66186                 return !!getSymbolLinks(getSymbolOfNode(declaration)).constEnumReferenced;
66187             });
66188         }
66189         function checkImportsForTypeOnlyConversion(sourceFile) {
66190             for (var _i = 0, _a = sourceFile.statements; _i < _a.length; _i++) {
66191                 var statement = _a[_i];
66192                 if (ts.isImportDeclaration(statement) &&
66193                     statement.importClause &&
66194                     !statement.importClause.isTypeOnly &&
66195                     importClauseContainsReferencedImport(statement.importClause) &&
66196                     !isReferencedAliasDeclaration(statement.importClause, /*checkChildren*/ true) &&
66197                     !importClauseContainsConstEnumUsedAsValue(statement.importClause)) {
66198                     error(statement, ts.Diagnostics.This_import_is_never_used_as_a_value_and_must_use_import_type_because_the_importsNotUsedAsValues_is_set_to_error);
66199                 }
66200             }
66201         }
66202         function checkExportSpecifier(node) {
66203             checkAliasSymbol(node);
66204             if (ts.getEmitDeclarations(compilerOptions)) {
66205                 collectLinkedAliases(node.propertyName || node.name, /*setVisibility*/ true);
66206             }
66207             if (!node.parent.parent.moduleSpecifier) {
66208                 var exportedName = node.propertyName || node.name;
66209                 // find immediate value referenced by exported name (SymbolFlags.Alias is set so we don't chase down aliases)
66210                 var symbol = resolveName(exportedName, exportedName.escapedText, 111551 /* Value */ | 788968 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */, 
66211                 /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ true);
66212                 if (symbol && (symbol === undefinedSymbol || symbol === globalThisSymbol || isGlobalSourceFile(getDeclarationContainer(symbol.declarations[0])))) {
66213                     error(exportedName, ts.Diagnostics.Cannot_export_0_Only_local_declarations_can_be_exported_from_a_module, ts.idText(exportedName));
66214                 }
66215                 else {
66216                     markExportAsReferenced(node);
66217                     var target = symbol && (symbol.flags & 2097152 /* Alias */ ? resolveAlias(symbol) : symbol);
66218                     if (!target || target === unknownSymbol || target.flags & 111551 /* Value */) {
66219                         checkExpressionCached(node.propertyName || node.name);
66220                     }
66221                 }
66222             }
66223         }
66224         function checkExportAssignment(node) {
66225             if (checkGrammarModuleElementContext(node, ts.Diagnostics.An_export_assignment_can_only_be_used_in_a_module)) {
66226                 // If we hit an export assignment in an illegal context, just bail out to avoid cascading errors.
66227                 return;
66228             }
66229             var container = node.parent.kind === 290 /* SourceFile */ ? node.parent : node.parent.parent;
66230             if (container.kind === 249 /* ModuleDeclaration */ && !ts.isAmbientModule(container)) {
66231                 if (node.isExportEquals) {
66232                     error(node, ts.Diagnostics.An_export_assignment_cannot_be_used_in_a_namespace);
66233                 }
66234                 else {
66235                     error(node, ts.Diagnostics.A_default_export_can_only_be_used_in_an_ECMAScript_style_module);
66236                 }
66237                 return;
66238             }
66239             // Grammar checking
66240             if (!checkGrammarDecoratorsAndModifiers(node) && ts.hasModifiers(node)) {
66241                 grammarErrorOnFirstToken(node, ts.Diagnostics.An_export_assignment_cannot_have_modifiers);
66242             }
66243             if (node.expression.kind === 75 /* Identifier */) {
66244                 var id = node.expression;
66245                 var sym = resolveEntityName(id, 67108863 /* All */, /*ignoreErrors*/ true, /*dontResolveAlias*/ true, node);
66246                 if (sym) {
66247                     markAliasReferenced(sym, id);
66248                     // If not a value, we're interpreting the identifier as a type export, along the lines of (`export { Id as default }`)
66249                     var target = sym.flags & 2097152 /* Alias */ ? resolveAlias(sym) : sym;
66250                     if (target === unknownSymbol || target.flags & 111551 /* Value */) {
66251                         // However if it is a value, we need to check it's being used correctly
66252                         checkExpressionCached(node.expression);
66253                     }
66254                 }
66255                 if (ts.getEmitDeclarations(compilerOptions)) {
66256                     collectLinkedAliases(node.expression, /*setVisibility*/ true);
66257                 }
66258             }
66259             else {
66260                 checkExpressionCached(node.expression);
66261             }
66262             checkExternalModuleExports(container);
66263             if ((node.flags & 8388608 /* Ambient */) && !ts.isEntityNameExpression(node.expression)) {
66264                 grammarErrorOnNode(node.expression, ts.Diagnostics.The_expression_of_an_export_assignment_must_be_an_identifier_or_qualified_name_in_an_ambient_context);
66265             }
66266             if (node.isExportEquals && !(node.flags & 8388608 /* Ambient */)) {
66267                 if (moduleKind >= ts.ModuleKind.ES2015) {
66268                     // export assignment is not supported in es6 modules
66269                     grammarErrorOnNode(node, ts.Diagnostics.Export_assignment_cannot_be_used_when_targeting_ECMAScript_modules_Consider_using_export_default_or_another_module_format_instead);
66270                 }
66271                 else if (moduleKind === ts.ModuleKind.System) {
66272                     // system modules does not support export assignment
66273                     grammarErrorOnNode(node, ts.Diagnostics.Export_assignment_is_not_supported_when_module_flag_is_system);
66274                 }
66275             }
66276         }
66277         function hasExportedMembers(moduleSymbol) {
66278             return ts.forEachEntry(moduleSymbol.exports, function (_, id) { return id !== "export="; });
66279         }
66280         function checkExternalModuleExports(node) {
66281             var moduleSymbol = getSymbolOfNode(node);
66282             var links = getSymbolLinks(moduleSymbol);
66283             if (!links.exportsChecked) {
66284                 var exportEqualsSymbol = moduleSymbol.exports.get("export=");
66285                 if (exportEqualsSymbol && hasExportedMembers(moduleSymbol)) {
66286                     var declaration = getDeclarationOfAliasSymbol(exportEqualsSymbol) || exportEqualsSymbol.valueDeclaration;
66287                     if (!isTopLevelInExternalModuleAugmentation(declaration) && !ts.isInJSFile(declaration)) {
66288                         error(declaration, ts.Diagnostics.An_export_assignment_cannot_be_used_in_a_module_with_other_exported_elements);
66289                     }
66290                 }
66291                 // Checks for export * conflicts
66292                 var exports_2 = getExportsOfModule(moduleSymbol);
66293                 if (exports_2) {
66294                     exports_2.forEach(function (_a, id) {
66295                         var declarations = _a.declarations, flags = _a.flags;
66296                         if (id === "__export") {
66297                             return;
66298                         }
66299                         // ECMA262: 15.2.1.1 It is a Syntax Error if the ExportedNames of ModuleItemList contains any duplicate entries.
66300                         // (TS Exceptions: namespaces, function overloads, enums, and interfaces)
66301                         if (flags & (1920 /* Namespace */ | 64 /* Interface */ | 384 /* Enum */)) {
66302                             return;
66303                         }
66304                         var exportedDeclarationsCount = ts.countWhere(declarations, isNotOverloadAndNotAccessor);
66305                         if (flags & 524288 /* TypeAlias */ && exportedDeclarationsCount <= 2) {
66306                             // it is legal to merge type alias with other values
66307                             // so count should be either 1 (just type alias) or 2 (type alias + merged value)
66308                             return;
66309                         }
66310                         if (exportedDeclarationsCount > 1) {
66311                             for (var _i = 0, declarations_9 = declarations; _i < declarations_9.length; _i++) {
66312                                 var declaration = declarations_9[_i];
66313                                 if (isNotOverload(declaration)) {
66314                                     diagnostics.add(ts.createDiagnosticForNode(declaration, ts.Diagnostics.Cannot_redeclare_exported_variable_0, ts.unescapeLeadingUnderscores(id)));
66315                                 }
66316                             }
66317                         }
66318                     });
66319                 }
66320                 links.exportsChecked = true;
66321             }
66322         }
66323         function checkSourceElement(node) {
66324             if (node) {
66325                 var saveCurrentNode = currentNode;
66326                 currentNode = node;
66327                 instantiationCount = 0;
66328                 checkSourceElementWorker(node);
66329                 currentNode = saveCurrentNode;
66330             }
66331         }
66332         function checkSourceElementWorker(node) {
66333             if (ts.isInJSFile(node)) {
66334                 ts.forEach(node.jsDoc, function (_a) {
66335                     var tags = _a.tags;
66336                     return ts.forEach(tags, checkSourceElement);
66337                 });
66338             }
66339             var kind = node.kind;
66340             if (cancellationToken) {
66341                 // Only bother checking on a few construct kinds.  We don't want to be excessively
66342                 // hitting the cancellation token on every node we check.
66343                 switch (kind) {
66344                     case 249 /* ModuleDeclaration */:
66345                     case 245 /* ClassDeclaration */:
66346                     case 246 /* InterfaceDeclaration */:
66347                     case 244 /* FunctionDeclaration */:
66348                         cancellationToken.throwIfCancellationRequested();
66349                 }
66350             }
66351             if (kind >= 225 /* FirstStatement */ && kind <= 241 /* LastStatement */ && node.flowNode && !isReachableFlowNode(node.flowNode)) {
66352                 errorOrSuggestion(compilerOptions.allowUnreachableCode === false, node, ts.Diagnostics.Unreachable_code_detected);
66353             }
66354             switch (kind) {
66355                 case 155 /* TypeParameter */:
66356                     return checkTypeParameter(node);
66357                 case 156 /* Parameter */:
66358                     return checkParameter(node);
66359                 case 159 /* PropertyDeclaration */:
66360                     return checkPropertyDeclaration(node);
66361                 case 158 /* PropertySignature */:
66362                     return checkPropertySignature(node);
66363                 case 170 /* FunctionType */:
66364                 case 171 /* ConstructorType */:
66365                 case 165 /* CallSignature */:
66366                 case 166 /* ConstructSignature */:
66367                 case 167 /* IndexSignature */:
66368                     return checkSignatureDeclaration(node);
66369                 case 161 /* MethodDeclaration */:
66370                 case 160 /* MethodSignature */:
66371                     return checkMethodDeclaration(node);
66372                 case 162 /* Constructor */:
66373                     return checkConstructorDeclaration(node);
66374                 case 163 /* GetAccessor */:
66375                 case 164 /* SetAccessor */:
66376                     return checkAccessorDeclaration(node);
66377                 case 169 /* TypeReference */:
66378                     return checkTypeReferenceNode(node);
66379                 case 168 /* TypePredicate */:
66380                     return checkTypePredicate(node);
66381                 case 172 /* TypeQuery */:
66382                     return checkTypeQuery(node);
66383                 case 173 /* TypeLiteral */:
66384                     return checkTypeLiteral(node);
66385                 case 174 /* ArrayType */:
66386                     return checkArrayType(node);
66387                 case 175 /* TupleType */:
66388                     return checkTupleType(node);
66389                 case 178 /* UnionType */:
66390                 case 179 /* IntersectionType */:
66391                     return checkUnionOrIntersectionType(node);
66392                 case 182 /* ParenthesizedType */:
66393                 case 176 /* OptionalType */:
66394                 case 177 /* RestType */:
66395                     return checkSourceElement(node.type);
66396                 case 183 /* ThisType */:
66397                     return checkThisType(node);
66398                 case 184 /* TypeOperator */:
66399                     return checkTypeOperator(node);
66400                 case 180 /* ConditionalType */:
66401                     return checkConditionalType(node);
66402                 case 181 /* InferType */:
66403                     return checkInferType(node);
66404                 case 188 /* ImportType */:
66405                     return checkImportType(node);
66406                 case 307 /* JSDocAugmentsTag */:
66407                     return checkJSDocAugmentsTag(node);
66408                 case 308 /* JSDocImplementsTag */:
66409                     return checkJSDocImplementsTag(node);
66410                 case 322 /* JSDocTypedefTag */:
66411                 case 315 /* JSDocCallbackTag */:
66412                 case 316 /* JSDocEnumTag */:
66413                     return checkJSDocTypeAliasTag(node);
66414                 case 321 /* JSDocTemplateTag */:
66415                     return checkJSDocTemplateTag(node);
66416                 case 320 /* JSDocTypeTag */:
66417                     return checkJSDocTypeTag(node);
66418                 case 317 /* JSDocParameterTag */:
66419                     return checkJSDocParameterTag(node);
66420                 case 323 /* JSDocPropertyTag */:
66421                     return checkJSDocPropertyTag(node);
66422                 case 300 /* JSDocFunctionType */:
66423                     checkJSDocFunctionType(node);
66424                 // falls through
66425                 case 298 /* JSDocNonNullableType */:
66426                 case 297 /* JSDocNullableType */:
66427                 case 295 /* JSDocAllType */:
66428                 case 296 /* JSDocUnknownType */:
66429                 case 304 /* JSDocTypeLiteral */:
66430                     checkJSDocTypeIsInJsFile(node);
66431                     ts.forEachChild(node, checkSourceElement);
66432                     return;
66433                 case 301 /* JSDocVariadicType */:
66434                     checkJSDocVariadicType(node);
66435                     return;
66436                 case 294 /* JSDocTypeExpression */:
66437                     return checkSourceElement(node.type);
66438                 case 185 /* IndexedAccessType */:
66439                     return checkIndexedAccessType(node);
66440                 case 186 /* MappedType */:
66441                     return checkMappedType(node);
66442                 case 244 /* FunctionDeclaration */:
66443                     return checkFunctionDeclaration(node);
66444                 case 223 /* Block */:
66445                 case 250 /* ModuleBlock */:
66446                     return checkBlock(node);
66447                 case 225 /* VariableStatement */:
66448                     return checkVariableStatement(node);
66449                 case 226 /* ExpressionStatement */:
66450                     return checkExpressionStatement(node);
66451                 case 227 /* IfStatement */:
66452                     return checkIfStatement(node);
66453                 case 228 /* DoStatement */:
66454                     return checkDoStatement(node);
66455                 case 229 /* WhileStatement */:
66456                     return checkWhileStatement(node);
66457                 case 230 /* ForStatement */:
66458                     return checkForStatement(node);
66459                 case 231 /* ForInStatement */:
66460                     return checkForInStatement(node);
66461                 case 232 /* ForOfStatement */:
66462                     return checkForOfStatement(node);
66463                 case 233 /* ContinueStatement */:
66464                 case 234 /* BreakStatement */:
66465                     return checkBreakOrContinueStatement(node);
66466                 case 235 /* ReturnStatement */:
66467                     return checkReturnStatement(node);
66468                 case 236 /* WithStatement */:
66469                     return checkWithStatement(node);
66470                 case 237 /* SwitchStatement */:
66471                     return checkSwitchStatement(node);
66472                 case 238 /* LabeledStatement */:
66473                     return checkLabeledStatement(node);
66474                 case 239 /* ThrowStatement */:
66475                     return checkThrowStatement(node);
66476                 case 240 /* TryStatement */:
66477                     return checkTryStatement(node);
66478                 case 242 /* VariableDeclaration */:
66479                     return checkVariableDeclaration(node);
66480                 case 191 /* BindingElement */:
66481                     return checkBindingElement(node);
66482                 case 245 /* ClassDeclaration */:
66483                     return checkClassDeclaration(node);
66484                 case 246 /* InterfaceDeclaration */:
66485                     return checkInterfaceDeclaration(node);
66486                 case 247 /* TypeAliasDeclaration */:
66487                     return checkTypeAliasDeclaration(node);
66488                 case 248 /* EnumDeclaration */:
66489                     return checkEnumDeclaration(node);
66490                 case 249 /* ModuleDeclaration */:
66491                     return checkModuleDeclaration(node);
66492                 case 254 /* ImportDeclaration */:
66493                     return checkImportDeclaration(node);
66494                 case 253 /* ImportEqualsDeclaration */:
66495                     return checkImportEqualsDeclaration(node);
66496                 case 260 /* ExportDeclaration */:
66497                     return checkExportDeclaration(node);
66498                 case 259 /* ExportAssignment */:
66499                     return checkExportAssignment(node);
66500                 case 224 /* EmptyStatement */:
66501                 case 241 /* DebuggerStatement */:
66502                     checkGrammarStatementInAmbientContext(node);
66503                     return;
66504                 case 264 /* MissingDeclaration */:
66505                     return checkMissingDeclaration(node);
66506             }
66507         }
66508         function checkJSDocTypeIsInJsFile(node) {
66509             if (!ts.isInJSFile(node)) {
66510                 grammarErrorOnNode(node, ts.Diagnostics.JSDoc_types_can_only_be_used_inside_documentation_comments);
66511             }
66512         }
66513         function checkJSDocVariadicType(node) {
66514             checkJSDocTypeIsInJsFile(node);
66515             checkSourceElement(node.type);
66516             // Only legal location is in the *last* parameter tag or last parameter of a JSDoc function.
66517             var parent = node.parent;
66518             if (ts.isParameter(parent) && ts.isJSDocFunctionType(parent.parent)) {
66519                 if (ts.last(parent.parent.parameters) !== parent) {
66520                     error(node, ts.Diagnostics.A_rest_parameter_must_be_last_in_a_parameter_list);
66521                 }
66522                 return;
66523             }
66524             if (!ts.isJSDocTypeExpression(parent)) {
66525                 error(node, ts.Diagnostics.JSDoc_may_only_appear_in_the_last_parameter_of_a_signature);
66526             }
66527             var paramTag = node.parent.parent;
66528             if (!ts.isJSDocParameterTag(paramTag)) {
66529                 error(node, ts.Diagnostics.JSDoc_may_only_appear_in_the_last_parameter_of_a_signature);
66530                 return;
66531             }
66532             var param = ts.getParameterSymbolFromJSDoc(paramTag);
66533             if (!param) {
66534                 // We will error in `checkJSDocParameterTag`.
66535                 return;
66536             }
66537             var host = ts.getHostSignatureFromJSDoc(paramTag);
66538             if (!host || ts.last(host.parameters).symbol !== param) {
66539                 error(node, ts.Diagnostics.A_rest_parameter_must_be_last_in_a_parameter_list);
66540             }
66541         }
66542         function getTypeFromJSDocVariadicType(node) {
66543             var type = getTypeFromTypeNode(node.type);
66544             var parent = node.parent;
66545             var paramTag = node.parent.parent;
66546             if (ts.isJSDocTypeExpression(node.parent) && ts.isJSDocParameterTag(paramTag)) {
66547                 // Else we will add a diagnostic, see `checkJSDocVariadicType`.
66548                 var host_1 = ts.getHostSignatureFromJSDoc(paramTag);
66549                 if (host_1) {
66550                     /*
66551                     Only return an array type if the corresponding parameter is marked as a rest parameter, or if there are no parameters.
66552                     So in the following situation we will not create an array type:
66553                         /** @param {...number} a * /
66554                         function f(a) {}
66555                     Because `a` will just be of type `number | undefined`. A synthetic `...args` will also be added, which *will* get an array type.
66556                     */
66557                     var lastParamDeclaration = ts.lastOrUndefined(host_1.parameters);
66558                     var symbol = ts.getParameterSymbolFromJSDoc(paramTag);
66559                     if (!lastParamDeclaration ||
66560                         symbol && lastParamDeclaration.symbol === symbol && ts.isRestParameter(lastParamDeclaration)) {
66561                         return createArrayType(type);
66562                     }
66563                 }
66564             }
66565             if (ts.isParameter(parent) && ts.isJSDocFunctionType(parent.parent)) {
66566                 return createArrayType(type);
66567             }
66568             return addOptionality(type);
66569         }
66570         // Function and class expression bodies are checked after all statements in the enclosing body. This is
66571         // to ensure constructs like the following are permitted:
66572         //     const foo = function () {
66573         //        const s = foo();
66574         //        return "hello";
66575         //     }
66576         // Here, performing a full type check of the body of the function expression whilst in the process of
66577         // determining the type of foo would cause foo to be given type any because of the recursive reference.
66578         // Delaying the type check of the body ensures foo has been assigned a type.
66579         function checkNodeDeferred(node) {
66580             var enclosingFile = ts.getSourceFileOfNode(node);
66581             var links = getNodeLinks(enclosingFile);
66582             if (!(links.flags & 1 /* TypeChecked */)) {
66583                 links.deferredNodes = links.deferredNodes || ts.createMap();
66584                 var id = "" + getNodeId(node);
66585                 links.deferredNodes.set(id, node);
66586             }
66587         }
66588         function checkDeferredNodes(context) {
66589             var links = getNodeLinks(context);
66590             if (links.deferredNodes) {
66591                 links.deferredNodes.forEach(checkDeferredNode);
66592             }
66593         }
66594         function checkDeferredNode(node) {
66595             var saveCurrentNode = currentNode;
66596             currentNode = node;
66597             instantiationCount = 0;
66598             switch (node.kind) {
66599                 case 196 /* CallExpression */:
66600                 case 197 /* NewExpression */:
66601                 case 198 /* TaggedTemplateExpression */:
66602                 case 157 /* Decorator */:
66603                 case 268 /* JsxOpeningElement */:
66604                     // These node kinds are deferred checked when overload resolution fails
66605                     // To save on work, we ensure the arguments are checked just once, in
66606                     // a deferred way
66607                     resolveUntypedCall(node);
66608                     break;
66609                 case 201 /* FunctionExpression */:
66610                 case 202 /* ArrowFunction */:
66611                 case 161 /* MethodDeclaration */:
66612                 case 160 /* MethodSignature */:
66613                     checkFunctionExpressionOrObjectLiteralMethodDeferred(node);
66614                     break;
66615                 case 163 /* GetAccessor */:
66616                 case 164 /* SetAccessor */:
66617                     checkAccessorDeclaration(node);
66618                     break;
66619                 case 214 /* ClassExpression */:
66620                     checkClassExpressionDeferred(node);
66621                     break;
66622                 case 267 /* JsxSelfClosingElement */:
66623                     checkJsxSelfClosingElementDeferred(node);
66624                     break;
66625                 case 266 /* JsxElement */:
66626                     checkJsxElementDeferred(node);
66627                     break;
66628             }
66629             currentNode = saveCurrentNode;
66630         }
66631         function checkSourceFile(node) {
66632             ts.performance.mark("beforeCheck");
66633             checkSourceFileWorker(node);
66634             ts.performance.mark("afterCheck");
66635             ts.performance.measure("Check", "beforeCheck", "afterCheck");
66636         }
66637         function unusedIsError(kind, isAmbient) {
66638             if (isAmbient) {
66639                 return false;
66640             }
66641             switch (kind) {
66642                 case 0 /* Local */:
66643                     return !!compilerOptions.noUnusedLocals;
66644                 case 1 /* Parameter */:
66645                     return !!compilerOptions.noUnusedParameters;
66646                 default:
66647                     return ts.Debug.assertNever(kind);
66648             }
66649         }
66650         function getPotentiallyUnusedIdentifiers(sourceFile) {
66651             return allPotentiallyUnusedIdentifiers.get(sourceFile.path) || ts.emptyArray;
66652         }
66653         // Fully type check a source file and collect the relevant diagnostics.
66654         function checkSourceFileWorker(node) {
66655             var links = getNodeLinks(node);
66656             if (!(links.flags & 1 /* TypeChecked */)) {
66657                 if (ts.skipTypeChecking(node, compilerOptions, host)) {
66658                     return;
66659                 }
66660                 // Grammar checking
66661                 checkGrammarSourceFile(node);
66662                 ts.clear(potentialThisCollisions);
66663                 ts.clear(potentialNewTargetCollisions);
66664                 ts.clear(potentialWeakMapCollisions);
66665                 ts.forEach(node.statements, checkSourceElement);
66666                 checkSourceElement(node.endOfFileToken);
66667                 checkDeferredNodes(node);
66668                 if (ts.isExternalOrCommonJsModule(node)) {
66669                     registerForUnusedIdentifiersCheck(node);
66670                 }
66671                 if (!node.isDeclarationFile && (compilerOptions.noUnusedLocals || compilerOptions.noUnusedParameters)) {
66672                     checkUnusedIdentifiers(getPotentiallyUnusedIdentifiers(node), function (containingNode, kind, diag) {
66673                         if (!ts.containsParseError(containingNode) && unusedIsError(kind, !!(containingNode.flags & 8388608 /* Ambient */))) {
66674                             diagnostics.add(diag);
66675                         }
66676                     });
66677                 }
66678                 if (compilerOptions.importsNotUsedAsValues === 2 /* Error */ &&
66679                     !node.isDeclarationFile &&
66680                     ts.isExternalModule(node)) {
66681                     checkImportsForTypeOnlyConversion(node);
66682                 }
66683                 if (ts.isExternalOrCommonJsModule(node)) {
66684                     checkExternalModuleExports(node);
66685                 }
66686                 if (potentialThisCollisions.length) {
66687                     ts.forEach(potentialThisCollisions, checkIfThisIsCapturedInEnclosingScope);
66688                     ts.clear(potentialThisCollisions);
66689                 }
66690                 if (potentialNewTargetCollisions.length) {
66691                     ts.forEach(potentialNewTargetCollisions, checkIfNewTargetIsCapturedInEnclosingScope);
66692                     ts.clear(potentialNewTargetCollisions);
66693                 }
66694                 if (potentialWeakMapCollisions.length) {
66695                     ts.forEach(potentialWeakMapCollisions, checkWeakMapCollision);
66696                     ts.clear(potentialWeakMapCollisions);
66697                 }
66698                 links.flags |= 1 /* TypeChecked */;
66699             }
66700         }
66701         function getDiagnostics(sourceFile, ct) {
66702             try {
66703                 // Record the cancellation token so it can be checked later on during checkSourceElement.
66704                 // Do this in a finally block so we can ensure that it gets reset back to nothing after
66705                 // this call is done.
66706                 cancellationToken = ct;
66707                 return getDiagnosticsWorker(sourceFile);
66708             }
66709             finally {
66710                 cancellationToken = undefined;
66711             }
66712         }
66713         function getDiagnosticsWorker(sourceFile) {
66714             throwIfNonDiagnosticsProducing();
66715             if (sourceFile) {
66716                 // Some global diagnostics are deferred until they are needed and
66717                 // may not be reported in the first call to getGlobalDiagnostics.
66718                 // We should catch these changes and report them.
66719                 var previousGlobalDiagnostics = diagnostics.getGlobalDiagnostics();
66720                 var previousGlobalDiagnosticsSize = previousGlobalDiagnostics.length;
66721                 checkSourceFile(sourceFile);
66722                 var semanticDiagnostics = diagnostics.getDiagnostics(sourceFile.fileName);
66723                 var currentGlobalDiagnostics = diagnostics.getGlobalDiagnostics();
66724                 if (currentGlobalDiagnostics !== previousGlobalDiagnostics) {
66725                     // If the arrays are not the same reference, new diagnostics were added.
66726                     var deferredGlobalDiagnostics = ts.relativeComplement(previousGlobalDiagnostics, currentGlobalDiagnostics, ts.compareDiagnostics);
66727                     return ts.concatenate(deferredGlobalDiagnostics, semanticDiagnostics);
66728                 }
66729                 else if (previousGlobalDiagnosticsSize === 0 && currentGlobalDiagnostics.length > 0) {
66730                     // If the arrays are the same reference, but the length has changed, a single
66731                     // new diagnostic was added as DiagnosticCollection attempts to reuse the
66732                     // same array.
66733                     return ts.concatenate(currentGlobalDiagnostics, semanticDiagnostics);
66734                 }
66735                 return semanticDiagnostics;
66736             }
66737             // Global diagnostics are always added when a file is not provided to
66738             // getDiagnostics
66739             ts.forEach(host.getSourceFiles(), checkSourceFile);
66740             return diagnostics.getDiagnostics();
66741         }
66742         function getGlobalDiagnostics() {
66743             throwIfNonDiagnosticsProducing();
66744             return diagnostics.getGlobalDiagnostics();
66745         }
66746         function throwIfNonDiagnosticsProducing() {
66747             if (!produceDiagnostics) {
66748                 throw new Error("Trying to get diagnostics from a type checker that does not produce them.");
66749             }
66750         }
66751         // Language service support
66752         function getSymbolsInScope(location, meaning) {
66753             if (location.flags & 16777216 /* InWithStatement */) {
66754                 // We cannot answer semantic questions within a with block, do not proceed any further
66755                 return [];
66756             }
66757             var symbols = ts.createSymbolTable();
66758             var isStatic = false;
66759             populateSymbols();
66760             symbols.delete("this" /* This */); // Not a symbol, a keyword
66761             return symbolsToArray(symbols);
66762             function populateSymbols() {
66763                 while (location) {
66764                     if (location.locals && !isGlobalSourceFile(location)) {
66765                         copySymbols(location.locals, meaning);
66766                     }
66767                     switch (location.kind) {
66768                         case 290 /* SourceFile */:
66769                             if (!ts.isExternalOrCommonJsModule(location))
66770                                 break;
66771                         // falls through
66772                         case 249 /* ModuleDeclaration */:
66773                             copySymbols(getSymbolOfNode(location).exports, meaning & 2623475 /* ModuleMember */);
66774                             break;
66775                         case 248 /* EnumDeclaration */:
66776                             copySymbols(getSymbolOfNode(location).exports, meaning & 8 /* EnumMember */);
66777                             break;
66778                         case 214 /* ClassExpression */:
66779                             var className = location.name;
66780                             if (className) {
66781                                 copySymbol(location.symbol, meaning);
66782                             }
66783                         // this fall-through is necessary because we would like to handle
66784                         // type parameter inside class expression similar to how we handle it in classDeclaration and interface Declaration.
66785                         // falls through
66786                         case 245 /* ClassDeclaration */:
66787                         case 246 /* InterfaceDeclaration */:
66788                             // If we didn't come from static member of class or interface,
66789                             // add the type parameters into the symbol table
66790                             // (type parameters of classDeclaration/classExpression and interface are in member property of the symbol.
66791                             // Note: that the memberFlags come from previous iteration.
66792                             if (!isStatic) {
66793                                 copySymbols(getMembersOfSymbol(getSymbolOfNode(location)), meaning & 788968 /* Type */);
66794                             }
66795                             break;
66796                         case 201 /* FunctionExpression */:
66797                             var funcName = location.name;
66798                             if (funcName) {
66799                                 copySymbol(location.symbol, meaning);
66800                             }
66801                             break;
66802                     }
66803                     if (ts.introducesArgumentsExoticObject(location)) {
66804                         copySymbol(argumentsSymbol, meaning);
66805                     }
66806                     isStatic = ts.hasModifier(location, 32 /* Static */);
66807                     location = location.parent;
66808                 }
66809                 copySymbols(globals, meaning);
66810             }
66811             /**
66812              * Copy the given symbol into symbol tables if the symbol has the given meaning
66813              * and it doesn't already existed in the symbol table
66814              * @param key a key for storing in symbol table; if undefined, use symbol.name
66815              * @param symbol the symbol to be added into symbol table
66816              * @param meaning meaning of symbol to filter by before adding to symbol table
66817              */
66818             function copySymbol(symbol, meaning) {
66819                 if (ts.getCombinedLocalAndExportSymbolFlags(symbol) & meaning) {
66820                     var id = symbol.escapedName;
66821                     // We will copy all symbol regardless of its reserved name because
66822                     // symbolsToArray will check whether the key is a reserved name and
66823                     // it will not copy symbol with reserved name to the array
66824                     if (!symbols.has(id)) {
66825                         symbols.set(id, symbol);
66826                     }
66827                 }
66828             }
66829             function copySymbols(source, meaning) {
66830                 if (meaning) {
66831                     source.forEach(function (symbol) {
66832                         copySymbol(symbol, meaning);
66833                     });
66834                 }
66835             }
66836         }
66837         function isTypeDeclarationName(name) {
66838             return name.kind === 75 /* Identifier */ &&
66839                 isTypeDeclaration(name.parent) &&
66840                 name.parent.name === name;
66841         }
66842         function isTypeDeclaration(node) {
66843             switch (node.kind) {
66844                 case 155 /* TypeParameter */:
66845                 case 245 /* ClassDeclaration */:
66846                 case 246 /* InterfaceDeclaration */:
66847                 case 247 /* TypeAliasDeclaration */:
66848                 case 248 /* EnumDeclaration */:
66849                     return true;
66850                 case 255 /* ImportClause */:
66851                     return node.isTypeOnly;
66852                 case 258 /* ImportSpecifier */:
66853                 case 263 /* ExportSpecifier */:
66854                     return node.parent.parent.isTypeOnly;
66855                 default:
66856                     return false;
66857             }
66858         }
66859         // True if the given identifier is part of a type reference
66860         function isTypeReferenceIdentifier(node) {
66861             while (node.parent.kind === 153 /* QualifiedName */) {
66862                 node = node.parent;
66863             }
66864             return node.parent.kind === 169 /* TypeReference */;
66865         }
66866         function isHeritageClauseElementIdentifier(node) {
66867             while (node.parent.kind === 194 /* PropertyAccessExpression */) {
66868                 node = node.parent;
66869             }
66870             return node.parent.kind === 216 /* ExpressionWithTypeArguments */;
66871         }
66872         function forEachEnclosingClass(node, callback) {
66873             var result;
66874             while (true) {
66875                 node = ts.getContainingClass(node);
66876                 if (!node)
66877                     break;
66878                 if (result = callback(node))
66879                     break;
66880             }
66881             return result;
66882         }
66883         function isNodeUsedDuringClassInitialization(node) {
66884             return !!ts.findAncestor(node, function (element) {
66885                 if (ts.isConstructorDeclaration(element) && ts.nodeIsPresent(element.body) || ts.isPropertyDeclaration(element)) {
66886                     return true;
66887                 }
66888                 else if (ts.isClassLike(element) || ts.isFunctionLikeDeclaration(element)) {
66889                     return "quit";
66890                 }
66891                 return false;
66892             });
66893         }
66894         function isNodeWithinClass(node, classDeclaration) {
66895             return !!forEachEnclosingClass(node, function (n) { return n === classDeclaration; });
66896         }
66897         function getLeftSideOfImportEqualsOrExportAssignment(nodeOnRightSide) {
66898             while (nodeOnRightSide.parent.kind === 153 /* QualifiedName */) {
66899                 nodeOnRightSide = nodeOnRightSide.parent;
66900             }
66901             if (nodeOnRightSide.parent.kind === 253 /* ImportEqualsDeclaration */) {
66902                 return nodeOnRightSide.parent.moduleReference === nodeOnRightSide ? nodeOnRightSide.parent : undefined;
66903             }
66904             if (nodeOnRightSide.parent.kind === 259 /* ExportAssignment */) {
66905                 return nodeOnRightSide.parent.expression === nodeOnRightSide ? nodeOnRightSide.parent : undefined;
66906             }
66907             return undefined;
66908         }
66909         function isInRightSideOfImportOrExportAssignment(node) {
66910             return getLeftSideOfImportEqualsOrExportAssignment(node) !== undefined;
66911         }
66912         function getSpecialPropertyAssignmentSymbolFromEntityName(entityName) {
66913             var specialPropertyAssignmentKind = ts.getAssignmentDeclarationKind(entityName.parent.parent);
66914             switch (specialPropertyAssignmentKind) {
66915                 case 1 /* ExportsProperty */:
66916                 case 3 /* PrototypeProperty */:
66917                     return getSymbolOfNode(entityName.parent);
66918                 case 4 /* ThisProperty */:
66919                 case 2 /* ModuleExports */:
66920                 case 5 /* Property */:
66921                     return getSymbolOfNode(entityName.parent.parent);
66922             }
66923         }
66924         function isImportTypeQualifierPart(node) {
66925             var parent = node.parent;
66926             while (ts.isQualifiedName(parent)) {
66927                 node = parent;
66928                 parent = parent.parent;
66929             }
66930             if (parent && parent.kind === 188 /* ImportType */ && parent.qualifier === node) {
66931                 return parent;
66932             }
66933             return undefined;
66934         }
66935         function getSymbolOfNameOrPropertyAccessExpression(name) {
66936             if (ts.isDeclarationName(name)) {
66937                 return getSymbolOfNode(name.parent);
66938             }
66939             if (ts.isInJSFile(name) &&
66940                 name.parent.kind === 194 /* PropertyAccessExpression */ &&
66941                 name.parent === name.parent.parent.left) {
66942                 // Check if this is a special property assignment
66943                 if (!ts.isPrivateIdentifier(name)) {
66944                     var specialPropertyAssignmentSymbol = getSpecialPropertyAssignmentSymbolFromEntityName(name);
66945                     if (specialPropertyAssignmentSymbol) {
66946                         return specialPropertyAssignmentSymbol;
66947                     }
66948                 }
66949             }
66950             if (name.parent.kind === 259 /* ExportAssignment */ && ts.isEntityNameExpression(name)) {
66951                 // Even an entity name expression that doesn't resolve as an entityname may still typecheck as a property access expression
66952                 var success = resolveEntityName(name, 
66953                 /*all meanings*/ 111551 /* Value */ | 788968 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */, /*ignoreErrors*/ true);
66954                 if (success && success !== unknownSymbol) {
66955                     return success;
66956                 }
66957             }
66958             else if (!ts.isPropertyAccessExpression(name) && !ts.isPrivateIdentifier(name) && isInRightSideOfImportOrExportAssignment(name)) {
66959                 // Since we already checked for ExportAssignment, this really could only be an Import
66960                 var importEqualsDeclaration = ts.getAncestor(name, 253 /* ImportEqualsDeclaration */);
66961                 ts.Debug.assert(importEqualsDeclaration !== undefined);
66962                 return getSymbolOfPartOfRightHandSideOfImportEquals(name, /*dontResolveAlias*/ true);
66963             }
66964             if (!ts.isPropertyAccessExpression(name) && !ts.isPrivateIdentifier(name)) {
66965                 var possibleImportNode = isImportTypeQualifierPart(name);
66966                 if (possibleImportNode) {
66967                     getTypeFromTypeNode(possibleImportNode);
66968                     var sym = getNodeLinks(name).resolvedSymbol;
66969                     return sym === unknownSymbol ? undefined : sym;
66970                 }
66971             }
66972             while (ts.isRightSideOfQualifiedNameOrPropertyAccess(name)) {
66973                 name = name.parent;
66974             }
66975             if (isHeritageClauseElementIdentifier(name)) {
66976                 var meaning = 0 /* None */;
66977                 // In an interface or class, we're definitely interested in a type.
66978                 if (name.parent.kind === 216 /* ExpressionWithTypeArguments */) {
66979                     meaning = 788968 /* Type */;
66980                     // In a class 'extends' clause we are also looking for a value.
66981                     if (ts.isExpressionWithTypeArgumentsInClassExtendsClause(name.parent)) {
66982                         meaning |= 111551 /* Value */;
66983                     }
66984                 }
66985                 else {
66986                     meaning = 1920 /* Namespace */;
66987                 }
66988                 meaning |= 2097152 /* Alias */;
66989                 var entityNameSymbol = ts.isEntityNameExpression(name) ? resolveEntityName(name, meaning) : undefined;
66990                 if (entityNameSymbol) {
66991                     return entityNameSymbol;
66992                 }
66993             }
66994             if (name.parent.kind === 317 /* JSDocParameterTag */) {
66995                 return ts.getParameterSymbolFromJSDoc(name.parent);
66996             }
66997             if (name.parent.kind === 155 /* TypeParameter */ && name.parent.parent.kind === 321 /* JSDocTemplateTag */) {
66998                 ts.Debug.assert(!ts.isInJSFile(name)); // Otherwise `isDeclarationName` would have been true.
66999                 var typeParameter = ts.getTypeParameterFromJsDoc(name.parent);
67000                 return typeParameter && typeParameter.symbol;
67001             }
67002             if (ts.isExpressionNode(name)) {
67003                 if (ts.nodeIsMissing(name)) {
67004                     // Missing entity name.
67005                     return undefined;
67006                 }
67007                 if (name.kind === 75 /* Identifier */) {
67008                     if (ts.isJSXTagName(name) && isJsxIntrinsicIdentifier(name)) {
67009                         var symbol = getIntrinsicTagSymbol(name.parent);
67010                         return symbol === unknownSymbol ? undefined : symbol;
67011                     }
67012                     return resolveEntityName(name, 111551 /* Value */, /*ignoreErrors*/ false, /*dontResolveAlias*/ true);
67013                 }
67014                 else if (name.kind === 194 /* PropertyAccessExpression */ || name.kind === 153 /* QualifiedName */) {
67015                     var links = getNodeLinks(name);
67016                     if (links.resolvedSymbol) {
67017                         return links.resolvedSymbol;
67018                     }
67019                     if (name.kind === 194 /* PropertyAccessExpression */) {
67020                         checkPropertyAccessExpression(name);
67021                     }
67022                     else {
67023                         checkQualifiedName(name);
67024                     }
67025                     return links.resolvedSymbol;
67026                 }
67027             }
67028             else if (isTypeReferenceIdentifier(name)) {
67029                 var meaning = name.parent.kind === 169 /* TypeReference */ ? 788968 /* Type */ : 1920 /* Namespace */;
67030                 return resolveEntityName(name, meaning, /*ignoreErrors*/ false, /*dontResolveAlias*/ true);
67031             }
67032             if (name.parent.kind === 168 /* TypePredicate */) {
67033                 return resolveEntityName(name, /*meaning*/ 1 /* FunctionScopedVariable */);
67034             }
67035             // Do we want to return undefined here?
67036             return undefined;
67037         }
67038         function getSymbolAtLocation(node, ignoreErrors) {
67039             if (node.kind === 290 /* SourceFile */) {
67040                 return ts.isExternalModule(node) ? getMergedSymbol(node.symbol) : undefined;
67041             }
67042             var parent = node.parent;
67043             var grandParent = parent.parent;
67044             if (node.flags & 16777216 /* InWithStatement */) {
67045                 // We cannot answer semantic questions within a with block, do not proceed any further
67046                 return undefined;
67047             }
67048             if (isDeclarationNameOrImportPropertyName(node)) {
67049                 // This is a declaration, call getSymbolOfNode
67050                 var parentSymbol = getSymbolOfNode(parent);
67051                 return ts.isImportOrExportSpecifier(node.parent) && node.parent.propertyName === node
67052                     ? getImmediateAliasedSymbol(parentSymbol)
67053                     : parentSymbol;
67054             }
67055             else if (ts.isLiteralComputedPropertyDeclarationName(node)) {
67056                 return getSymbolOfNode(parent.parent);
67057             }
67058             if (node.kind === 75 /* Identifier */) {
67059                 if (isInRightSideOfImportOrExportAssignment(node)) {
67060                     return getSymbolOfNameOrPropertyAccessExpression(node);
67061                 }
67062                 else if (parent.kind === 191 /* BindingElement */ &&
67063                     grandParent.kind === 189 /* ObjectBindingPattern */ &&
67064                     node === parent.propertyName) {
67065                     var typeOfPattern = getTypeOfNode(grandParent);
67066                     var propertyDeclaration = getPropertyOfType(typeOfPattern, node.escapedText);
67067                     if (propertyDeclaration) {
67068                         return propertyDeclaration;
67069                     }
67070                 }
67071             }
67072             switch (node.kind) {
67073                 case 75 /* Identifier */:
67074                 case 76 /* PrivateIdentifier */:
67075                 case 194 /* PropertyAccessExpression */:
67076                 case 153 /* QualifiedName */:
67077                     return getSymbolOfNameOrPropertyAccessExpression(node);
67078                 case 104 /* ThisKeyword */:
67079                     var container = ts.getThisContainer(node, /*includeArrowFunctions*/ false);
67080                     if (ts.isFunctionLike(container)) {
67081                         var sig = getSignatureFromDeclaration(container);
67082                         if (sig.thisParameter) {
67083                             return sig.thisParameter;
67084                         }
67085                     }
67086                     if (ts.isInExpressionContext(node)) {
67087                         return checkExpression(node).symbol;
67088                     }
67089                 // falls through
67090                 case 183 /* ThisType */:
67091                     return getTypeFromThisTypeNode(node).symbol;
67092                 case 102 /* SuperKeyword */:
67093                     return checkExpression(node).symbol;
67094                 case 129 /* ConstructorKeyword */:
67095                     // constructor keyword for an overload, should take us to the definition if it exist
67096                     var constructorDeclaration = node.parent;
67097                     if (constructorDeclaration && constructorDeclaration.kind === 162 /* Constructor */) {
67098                         return constructorDeclaration.parent.symbol;
67099                     }
67100                     return undefined;
67101                 case 10 /* StringLiteral */:
67102                 case 14 /* NoSubstitutionTemplateLiteral */:
67103                     // 1). import x = require("./mo/*gotToDefinitionHere*/d")
67104                     // 2). External module name in an import declaration
67105                     // 3). Dynamic import call or require in javascript
67106                     // 4). type A = import("./f/*gotToDefinitionHere*/oo")
67107                     if ((ts.isExternalModuleImportEqualsDeclaration(node.parent.parent) && ts.getExternalModuleImportEqualsDeclarationExpression(node.parent.parent) === node) ||
67108                         ((node.parent.kind === 254 /* ImportDeclaration */ || node.parent.kind === 260 /* ExportDeclaration */) && node.parent.moduleSpecifier === node) ||
67109                         ((ts.isInJSFile(node) && ts.isRequireCall(node.parent, /*checkArgumentIsStringLiteralLike*/ false)) || ts.isImportCall(node.parent)) ||
67110                         (ts.isLiteralTypeNode(node.parent) && ts.isLiteralImportTypeNode(node.parent.parent) && node.parent.parent.argument === node.parent)) {
67111                         return resolveExternalModuleName(node, node, ignoreErrors);
67112                     }
67113                     if (ts.isCallExpression(parent) && ts.isBindableObjectDefinePropertyCall(parent) && parent.arguments[1] === node) {
67114                         return getSymbolOfNode(parent);
67115                     }
67116                 // falls through
67117                 case 8 /* NumericLiteral */:
67118                     // index access
67119                     var objectType = ts.isElementAccessExpression(parent)
67120                         ? parent.argumentExpression === node ? getTypeOfExpression(parent.expression) : undefined
67121                         : ts.isLiteralTypeNode(parent) && ts.isIndexedAccessTypeNode(grandParent)
67122                             ? getTypeFromTypeNode(grandParent.objectType)
67123                             : undefined;
67124                     return objectType && getPropertyOfType(objectType, ts.escapeLeadingUnderscores(node.text));
67125                 case 84 /* DefaultKeyword */:
67126                 case 94 /* FunctionKeyword */:
67127                 case 38 /* EqualsGreaterThanToken */:
67128                 case 80 /* ClassKeyword */:
67129                     return getSymbolOfNode(node.parent);
67130                 case 188 /* ImportType */:
67131                     return ts.isLiteralImportTypeNode(node) ? getSymbolAtLocation(node.argument.literal, ignoreErrors) : undefined;
67132                 case 89 /* ExportKeyword */:
67133                     return ts.isExportAssignment(node.parent) ? ts.Debug.checkDefined(node.parent.symbol) : undefined;
67134                 default:
67135                     return undefined;
67136             }
67137         }
67138         function getShorthandAssignmentValueSymbol(location) {
67139             if (location && location.kind === 282 /* ShorthandPropertyAssignment */) {
67140                 return resolveEntityName(location.name, 111551 /* Value */ | 2097152 /* Alias */);
67141             }
67142             return undefined;
67143         }
67144         /** Returns the target of an export specifier without following aliases */
67145         function getExportSpecifierLocalTargetSymbol(node) {
67146             return node.parent.parent.moduleSpecifier ?
67147                 getExternalModuleMember(node.parent.parent, node) :
67148                 resolveEntityName(node.propertyName || node.name, 111551 /* Value */ | 788968 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */);
67149         }
67150         function getTypeOfNode(node) {
67151             if (node.flags & 16777216 /* InWithStatement */) {
67152                 // We cannot answer semantic questions within a with block, do not proceed any further
67153                 return errorType;
67154             }
67155             var classDecl = ts.tryGetClassImplementingOrExtendingExpressionWithTypeArguments(node);
67156             var classType = classDecl && getDeclaredTypeOfClassOrInterface(getSymbolOfNode(classDecl.class));
67157             if (ts.isPartOfTypeNode(node)) {
67158                 var typeFromTypeNode = getTypeFromTypeNode(node);
67159                 return classType ? getTypeWithThisArgument(typeFromTypeNode, classType.thisType) : typeFromTypeNode;
67160             }
67161             if (ts.isExpressionNode(node)) {
67162                 return getRegularTypeOfExpression(node);
67163             }
67164             if (classType && !classDecl.isImplements) {
67165                 // A SyntaxKind.ExpressionWithTypeArguments is considered a type node, except when it occurs in the
67166                 // extends clause of a class. We handle that case here.
67167                 var baseType = ts.firstOrUndefined(getBaseTypes(classType));
67168                 return baseType ? getTypeWithThisArgument(baseType, classType.thisType) : errorType;
67169             }
67170             if (isTypeDeclaration(node)) {
67171                 // In this case, we call getSymbolOfNode instead of getSymbolAtLocation because it is a declaration
67172                 var symbol = getSymbolOfNode(node);
67173                 return getDeclaredTypeOfSymbol(symbol);
67174             }
67175             if (isTypeDeclarationName(node)) {
67176                 var symbol = getSymbolAtLocation(node);
67177                 return symbol ? getDeclaredTypeOfSymbol(symbol) : errorType;
67178             }
67179             if (ts.isDeclaration(node)) {
67180                 // In this case, we call getSymbolOfNode instead of getSymbolAtLocation because it is a declaration
67181                 var symbol = getSymbolOfNode(node);
67182                 return getTypeOfSymbol(symbol);
67183             }
67184             if (isDeclarationNameOrImportPropertyName(node)) {
67185                 var symbol = getSymbolAtLocation(node);
67186                 if (symbol) {
67187                     return getTypeOfSymbol(symbol);
67188                 }
67189                 return errorType;
67190             }
67191             if (ts.isBindingPattern(node)) {
67192                 return getTypeForVariableLikeDeclaration(node.parent, /*includeOptionality*/ true) || errorType;
67193             }
67194             if (isInRightSideOfImportOrExportAssignment(node)) {
67195                 var symbol = getSymbolAtLocation(node);
67196                 if (symbol) {
67197                     var declaredType = getDeclaredTypeOfSymbol(symbol);
67198                     return declaredType !== errorType ? declaredType : getTypeOfSymbol(symbol);
67199                 }
67200             }
67201             return errorType;
67202         }
67203         // Gets the type of object literal or array literal of destructuring assignment.
67204         // { a } from
67205         //     for ( { a } of elems) {
67206         //     }
67207         // [ a ] from
67208         //     [a] = [ some array ...]
67209         function getTypeOfAssignmentPattern(expr) {
67210             ts.Debug.assert(expr.kind === 193 /* ObjectLiteralExpression */ || expr.kind === 192 /* ArrayLiteralExpression */);
67211             // If this is from "for of"
67212             //     for ( { a } of elems) {
67213             //     }
67214             if (expr.parent.kind === 232 /* ForOfStatement */) {
67215                 var iteratedType = checkRightHandSideOfForOf(expr.parent);
67216                 return checkDestructuringAssignment(expr, iteratedType || errorType);
67217             }
67218             // If this is from "for" initializer
67219             //     for ({a } = elems[0];.....) { }
67220             if (expr.parent.kind === 209 /* BinaryExpression */) {
67221                 var iteratedType = getTypeOfExpression(expr.parent.right);
67222                 return checkDestructuringAssignment(expr, iteratedType || errorType);
67223             }
67224             // If this is from nested object binding pattern
67225             //     for ({ skills: { primary, secondary } } = multiRobot, i = 0; i < 1; i++) {
67226             if (expr.parent.kind === 281 /* PropertyAssignment */) {
67227                 var node_4 = ts.cast(expr.parent.parent, ts.isObjectLiteralExpression);
67228                 var typeOfParentObjectLiteral = getTypeOfAssignmentPattern(node_4) || errorType;
67229                 var propertyIndex = ts.indexOfNode(node_4.properties, expr.parent);
67230                 return checkObjectLiteralDestructuringPropertyAssignment(node_4, typeOfParentObjectLiteral, propertyIndex);
67231             }
67232             // Array literal assignment - array destructuring pattern
67233             var node = ts.cast(expr.parent, ts.isArrayLiteralExpression);
67234             //    [{ property1: p1, property2 }] = elems;
67235             var typeOfArrayLiteral = getTypeOfAssignmentPattern(node) || errorType;
67236             var elementType = checkIteratedTypeOrElementType(65 /* Destructuring */, typeOfArrayLiteral, undefinedType, expr.parent) || errorType;
67237             return checkArrayLiteralDestructuringElementAssignment(node, typeOfArrayLiteral, node.elements.indexOf(expr), elementType);
67238         }
67239         // Gets the property symbol corresponding to the property in destructuring assignment
67240         // 'property1' from
67241         //     for ( { property1: a } of elems) {
67242         //     }
67243         // 'property1' at location 'a' from:
67244         //     [a] = [ property1, property2 ]
67245         function getPropertySymbolOfDestructuringAssignment(location) {
67246             // Get the type of the object or array literal and then look for property of given name in the type
67247             var typeOfObjectLiteral = getTypeOfAssignmentPattern(ts.cast(location.parent.parent, ts.isAssignmentPattern));
67248             return typeOfObjectLiteral && getPropertyOfType(typeOfObjectLiteral, location.escapedText);
67249         }
67250         function getRegularTypeOfExpression(expr) {
67251             if (ts.isRightSideOfQualifiedNameOrPropertyAccess(expr)) {
67252                 expr = expr.parent;
67253             }
67254             return getRegularTypeOfLiteralType(getTypeOfExpression(expr));
67255         }
67256         /**
67257          * Gets either the static or instance type of a class element, based on
67258          * whether the element is declared as "static".
67259          */
67260         function getParentTypeOfClassElement(node) {
67261             var classSymbol = getSymbolOfNode(node.parent);
67262             return ts.hasModifier(node, 32 /* Static */)
67263                 ? getTypeOfSymbol(classSymbol)
67264                 : getDeclaredTypeOfSymbol(classSymbol);
67265         }
67266         function getClassElementPropertyKeyType(element) {
67267             var name = element.name;
67268             switch (name.kind) {
67269                 case 75 /* Identifier */:
67270                     return getLiteralType(ts.idText(name));
67271                 case 8 /* NumericLiteral */:
67272                 case 10 /* StringLiteral */:
67273                     return getLiteralType(name.text);
67274                 case 154 /* ComputedPropertyName */:
67275                     var nameType = checkComputedPropertyName(name);
67276                     return isTypeAssignableToKind(nameType, 12288 /* ESSymbolLike */) ? nameType : stringType;
67277                 default:
67278                     return ts.Debug.fail("Unsupported property name.");
67279             }
67280         }
67281         // Return the list of properties of the given type, augmented with properties from Function
67282         // if the type has call or construct signatures
67283         function getAugmentedPropertiesOfType(type) {
67284             type = getApparentType(type);
67285             var propsByName = ts.createSymbolTable(getPropertiesOfType(type));
67286             var functionType = getSignaturesOfType(type, 0 /* Call */).length ? globalCallableFunctionType :
67287                 getSignaturesOfType(type, 1 /* Construct */).length ? globalNewableFunctionType :
67288                     undefined;
67289             if (functionType) {
67290                 ts.forEach(getPropertiesOfType(functionType), function (p) {
67291                     if (!propsByName.has(p.escapedName)) {
67292                         propsByName.set(p.escapedName, p);
67293                     }
67294                 });
67295             }
67296             return getNamedMembers(propsByName);
67297         }
67298         function typeHasCallOrConstructSignatures(type) {
67299             return ts.typeHasCallOrConstructSignatures(type, checker);
67300         }
67301         function getRootSymbols(symbol) {
67302             var roots = getImmediateRootSymbols(symbol);
67303             return roots ? ts.flatMap(roots, getRootSymbols) : [symbol];
67304         }
67305         function getImmediateRootSymbols(symbol) {
67306             if (ts.getCheckFlags(symbol) & 6 /* Synthetic */) {
67307                 return ts.mapDefined(getSymbolLinks(symbol).containingType.types, function (type) { return getPropertyOfType(type, symbol.escapedName); });
67308             }
67309             else if (symbol.flags & 33554432 /* Transient */) {
67310                 var _a = symbol, leftSpread = _a.leftSpread, rightSpread = _a.rightSpread, syntheticOrigin = _a.syntheticOrigin;
67311                 return leftSpread ? [leftSpread, rightSpread]
67312                     : syntheticOrigin ? [syntheticOrigin]
67313                         : ts.singleElementArray(tryGetAliasTarget(symbol));
67314             }
67315             return undefined;
67316         }
67317         function tryGetAliasTarget(symbol) {
67318             var target;
67319             var next = symbol;
67320             while (next = getSymbolLinks(next).target) {
67321                 target = next;
67322             }
67323             return target;
67324         }
67325         // Emitter support
67326         function isArgumentsLocalBinding(nodeIn) {
67327             if (!ts.isGeneratedIdentifier(nodeIn)) {
67328                 var node = ts.getParseTreeNode(nodeIn, ts.isIdentifier);
67329                 if (node) {
67330                     var isPropertyName_1 = node.parent.kind === 194 /* PropertyAccessExpression */ && node.parent.name === node;
67331                     return !isPropertyName_1 && getReferencedValueSymbol(node) === argumentsSymbol;
67332                 }
67333             }
67334             return false;
67335         }
67336         function moduleExportsSomeValue(moduleReferenceExpression) {
67337             var moduleSymbol = resolveExternalModuleName(moduleReferenceExpression.parent, moduleReferenceExpression);
67338             if (!moduleSymbol || ts.isShorthandAmbientModuleSymbol(moduleSymbol)) {
67339                 // If the module is not found or is shorthand, assume that it may export a value.
67340                 return true;
67341             }
67342             var hasExportAssignment = hasExportAssignmentSymbol(moduleSymbol);
67343             // if module has export assignment then 'resolveExternalModuleSymbol' will return resolved symbol for export assignment
67344             // otherwise it will return moduleSymbol itself
67345             moduleSymbol = resolveExternalModuleSymbol(moduleSymbol);
67346             var symbolLinks = getSymbolLinks(moduleSymbol);
67347             if (symbolLinks.exportsSomeValue === undefined) {
67348                 // for export assignments - check if resolved symbol for RHS is itself a value
67349                 // otherwise - check if at least one export is value
67350                 symbolLinks.exportsSomeValue = hasExportAssignment
67351                     ? !!(moduleSymbol.flags & 111551 /* Value */)
67352                     : ts.forEachEntry(getExportsOfModule(moduleSymbol), isValue);
67353             }
67354             return symbolLinks.exportsSomeValue;
67355             function isValue(s) {
67356                 s = resolveSymbol(s);
67357                 return s && !!(s.flags & 111551 /* Value */);
67358             }
67359         }
67360         function isNameOfModuleOrEnumDeclaration(node) {
67361             return ts.isModuleOrEnumDeclaration(node.parent) && node === node.parent.name;
67362         }
67363         // When resolved as an expression identifier, if the given node references an exported entity, return the declaration
67364         // node of the exported entity's container. Otherwise, return undefined.
67365         function getReferencedExportContainer(nodeIn, prefixLocals) {
67366             var node = ts.getParseTreeNode(nodeIn, ts.isIdentifier);
67367             if (node) {
67368                 // When resolving the export container for the name of a module or enum
67369                 // declaration, we need to start resolution at the declaration's container.
67370                 // Otherwise, we could incorrectly resolve the export container as the
67371                 // declaration if it contains an exported member with the same name.
67372                 var symbol = getReferencedValueSymbol(node, /*startInDeclarationContainer*/ isNameOfModuleOrEnumDeclaration(node));
67373                 if (symbol) {
67374                     if (symbol.flags & 1048576 /* ExportValue */) {
67375                         // If we reference an exported entity within the same module declaration, then whether
67376                         // we prefix depends on the kind of entity. SymbolFlags.ExportHasLocal encompasses all the
67377                         // kinds that we do NOT prefix.
67378                         var exportSymbol = getMergedSymbol(symbol.exportSymbol);
67379                         if (!prefixLocals && exportSymbol.flags & 944 /* ExportHasLocal */ && !(exportSymbol.flags & 3 /* Variable */)) {
67380                             return undefined;
67381                         }
67382                         symbol = exportSymbol;
67383                     }
67384                     var parentSymbol_1 = getParentOfSymbol(symbol);
67385                     if (parentSymbol_1) {
67386                         if (parentSymbol_1.flags & 512 /* ValueModule */ && parentSymbol_1.valueDeclaration.kind === 290 /* SourceFile */) {
67387                             var symbolFile = parentSymbol_1.valueDeclaration;
67388                             var referenceFile = ts.getSourceFileOfNode(node);
67389                             // If `node` accesses an export and that export isn't in the same file, then symbol is a namespace export, so return undefined.
67390                             var symbolIsUmdExport = symbolFile !== referenceFile;
67391                             return symbolIsUmdExport ? undefined : symbolFile;
67392                         }
67393                         return ts.findAncestor(node.parent, function (n) { return ts.isModuleOrEnumDeclaration(n) && getSymbolOfNode(n) === parentSymbol_1; });
67394                     }
67395                 }
67396             }
67397         }
67398         // When resolved as an expression identifier, if the given node references an import, return the declaration of
67399         // that import. Otherwise, return undefined.
67400         function getReferencedImportDeclaration(nodeIn) {
67401             var node = ts.getParseTreeNode(nodeIn, ts.isIdentifier);
67402             if (node) {
67403                 var symbol = getReferencedValueSymbol(node);
67404                 // We should only get the declaration of an alias if there isn't a local value
67405                 // declaration for the symbol
67406                 if (isNonLocalAlias(symbol, /*excludes*/ 111551 /* Value */) && !getTypeOnlyAliasDeclaration(symbol)) {
67407                     return getDeclarationOfAliasSymbol(symbol);
67408                 }
67409             }
67410             return undefined;
67411         }
67412         function isSymbolOfDestructuredElementOfCatchBinding(symbol) {
67413             return ts.isBindingElement(symbol.valueDeclaration)
67414                 && ts.walkUpBindingElementsAndPatterns(symbol.valueDeclaration).parent.kind === 280 /* CatchClause */;
67415         }
67416         function isSymbolOfDeclarationWithCollidingName(symbol) {
67417             if (symbol.flags & 418 /* BlockScoped */ && !ts.isSourceFile(symbol.valueDeclaration)) {
67418                 var links = getSymbolLinks(symbol);
67419                 if (links.isDeclarationWithCollidingName === undefined) {
67420                     var container = ts.getEnclosingBlockScopeContainer(symbol.valueDeclaration);
67421                     if (ts.isStatementWithLocals(container) || isSymbolOfDestructuredElementOfCatchBinding(symbol)) {
67422                         var nodeLinks_1 = getNodeLinks(symbol.valueDeclaration);
67423                         if (resolveName(container.parent, symbol.escapedName, 111551 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false)) {
67424                             // redeclaration - always should be renamed
67425                             links.isDeclarationWithCollidingName = true;
67426                         }
67427                         else if (nodeLinks_1.flags & 262144 /* CapturedBlockScopedBinding */) {
67428                             // binding is captured in the function
67429                             // should be renamed if:
67430                             // - binding is not top level - top level bindings never collide with anything
67431                             // AND
67432                             //   - binding is not declared in loop, should be renamed to avoid name reuse across siblings
67433                             //     let a, b
67434                             //     { let x = 1; a = () => x; }
67435                             //     { let x = 100; b = () => x; }
67436                             //     console.log(a()); // should print '1'
67437                             //     console.log(b()); // should print '100'
67438                             //     OR
67439                             //   - binding is declared inside loop but not in inside initializer of iteration statement or directly inside loop body
67440                             //     * variables from initializer are passed to rewritten loop body as parameters so they are not captured directly
67441                             //     * variables that are declared immediately in loop body will become top level variable after loop is rewritten and thus
67442                             //       they will not collide with anything
67443                             var isDeclaredInLoop = nodeLinks_1.flags & 524288 /* BlockScopedBindingInLoop */;
67444                             var inLoopInitializer = ts.isIterationStatement(container, /*lookInLabeledStatements*/ false);
67445                             var inLoopBodyBlock = container.kind === 223 /* Block */ && ts.isIterationStatement(container.parent, /*lookInLabeledStatements*/ false);
67446                             links.isDeclarationWithCollidingName = !ts.isBlockScopedContainerTopLevel(container) && (!isDeclaredInLoop || (!inLoopInitializer && !inLoopBodyBlock));
67447                         }
67448                         else {
67449                             links.isDeclarationWithCollidingName = false;
67450                         }
67451                     }
67452                 }
67453                 return links.isDeclarationWithCollidingName;
67454             }
67455             return false;
67456         }
67457         // When resolved as an expression identifier, if the given node references a nested block scoped entity with
67458         // a name that either hides an existing name or might hide it when compiled downlevel,
67459         // return the declaration of that entity. Otherwise, return undefined.
67460         function getReferencedDeclarationWithCollidingName(nodeIn) {
67461             if (!ts.isGeneratedIdentifier(nodeIn)) {
67462                 var node = ts.getParseTreeNode(nodeIn, ts.isIdentifier);
67463                 if (node) {
67464                     var symbol = getReferencedValueSymbol(node);
67465                     if (symbol && isSymbolOfDeclarationWithCollidingName(symbol)) {
67466                         return symbol.valueDeclaration;
67467                     }
67468                 }
67469             }
67470             return undefined;
67471         }
67472         // Return true if the given node is a declaration of a nested block scoped entity with a name that either hides an
67473         // existing name or might hide a name when compiled downlevel
67474         function isDeclarationWithCollidingName(nodeIn) {
67475             var node = ts.getParseTreeNode(nodeIn, ts.isDeclaration);
67476             if (node) {
67477                 var symbol = getSymbolOfNode(node);
67478                 if (symbol) {
67479                     return isSymbolOfDeclarationWithCollidingName(symbol);
67480                 }
67481             }
67482             return false;
67483         }
67484         function isValueAliasDeclaration(node) {
67485             switch (node.kind) {
67486                 case 253 /* ImportEqualsDeclaration */:
67487                     return isAliasResolvedToValue(getSymbolOfNode(node) || unknownSymbol);
67488                 case 255 /* ImportClause */:
67489                 case 256 /* NamespaceImport */:
67490                 case 258 /* ImportSpecifier */:
67491                 case 263 /* ExportSpecifier */:
67492                     var symbol = getSymbolOfNode(node) || unknownSymbol;
67493                     return isAliasResolvedToValue(symbol) && !getTypeOnlyAliasDeclaration(symbol);
67494                 case 260 /* ExportDeclaration */:
67495                     var exportClause = node.exportClause;
67496                     return !!exportClause && (ts.isNamespaceExport(exportClause) ||
67497                         ts.some(exportClause.elements, isValueAliasDeclaration));
67498                 case 259 /* ExportAssignment */:
67499                     return node.expression && node.expression.kind === 75 /* Identifier */ ?
67500                         isAliasResolvedToValue(getSymbolOfNode(node) || unknownSymbol) :
67501                         true;
67502             }
67503             return false;
67504         }
67505         function isTopLevelValueImportEqualsWithEntityName(nodeIn) {
67506             var node = ts.getParseTreeNode(nodeIn, ts.isImportEqualsDeclaration);
67507             if (node === undefined || node.parent.kind !== 290 /* SourceFile */ || !ts.isInternalModuleImportEqualsDeclaration(node)) {
67508                 // parent is not source file or it is not reference to internal module
67509                 return false;
67510             }
67511             var isValue = isAliasResolvedToValue(getSymbolOfNode(node));
67512             return isValue && node.moduleReference && !ts.nodeIsMissing(node.moduleReference);
67513         }
67514         function isAliasResolvedToValue(symbol) {
67515             var target = resolveAlias(symbol);
67516             if (target === unknownSymbol) {
67517                 return true;
67518             }
67519             // const enums and modules that contain only const enums are not considered values from the emit perspective
67520             // unless 'preserveConstEnums' option is set to true
67521             return !!(target.flags & 111551 /* Value */) &&
67522                 (compilerOptions.preserveConstEnums || !isConstEnumOrConstEnumOnlyModule(target));
67523         }
67524         function isConstEnumOrConstEnumOnlyModule(s) {
67525             return isConstEnumSymbol(s) || !!s.constEnumOnlyModule;
67526         }
67527         function isReferencedAliasDeclaration(node, checkChildren) {
67528             if (isAliasSymbolDeclaration(node)) {
67529                 var symbol = getSymbolOfNode(node);
67530                 if (symbol && getSymbolLinks(symbol).referenced) {
67531                     return true;
67532                 }
67533                 var target = getSymbolLinks(symbol).target; // TODO: GH#18217
67534                 if (target && ts.getModifierFlags(node) & 1 /* Export */ &&
67535                     target.flags & 111551 /* Value */ &&
67536                     (compilerOptions.preserveConstEnums || !isConstEnumOrConstEnumOnlyModule(target))) {
67537                     // An `export import ... =` of a value symbol is always considered referenced
67538                     return true;
67539                 }
67540             }
67541             if (checkChildren) {
67542                 return !!ts.forEachChild(node, function (node) { return isReferencedAliasDeclaration(node, checkChildren); });
67543             }
67544             return false;
67545         }
67546         function isImplementationOfOverload(node) {
67547             if (ts.nodeIsPresent(node.body)) {
67548                 if (ts.isGetAccessor(node) || ts.isSetAccessor(node))
67549                     return false; // Get or set accessors can never be overload implementations, but can have up to 2 signatures
67550                 var symbol = getSymbolOfNode(node);
67551                 var signaturesOfSymbol = getSignaturesOfSymbol(symbol);
67552                 // If this function body corresponds to function with multiple signature, it is implementation of overload
67553                 // e.g.: function foo(a: string): string;
67554                 //       function foo(a: number): number;
67555                 //       function foo(a: any) { // This is implementation of the overloads
67556                 //           return a;
67557                 //       }
67558                 return signaturesOfSymbol.length > 1 ||
67559                     // If there is single signature for the symbol, it is overload if that signature isn't coming from the node
67560                     // e.g.: function foo(a: string): string;
67561                     //       function foo(a: any) { // This is implementation of the overloads
67562                     //           return a;
67563                     //       }
67564                     (signaturesOfSymbol.length === 1 && signaturesOfSymbol[0].declaration !== node);
67565             }
67566             return false;
67567         }
67568         function isRequiredInitializedParameter(parameter) {
67569             return !!strictNullChecks &&
67570                 !isOptionalParameter(parameter) &&
67571                 !ts.isJSDocParameterTag(parameter) &&
67572                 !!parameter.initializer &&
67573                 !ts.hasModifier(parameter, 92 /* ParameterPropertyModifier */);
67574         }
67575         function isOptionalUninitializedParameterProperty(parameter) {
67576             return strictNullChecks &&
67577                 isOptionalParameter(parameter) &&
67578                 !parameter.initializer &&
67579                 ts.hasModifier(parameter, 92 /* ParameterPropertyModifier */);
67580         }
67581         function isExpandoFunctionDeclaration(node) {
67582             var declaration = ts.getParseTreeNode(node, ts.isFunctionDeclaration);
67583             if (!declaration) {
67584                 return false;
67585             }
67586             var symbol = getSymbolOfNode(declaration);
67587             if (!symbol || !(symbol.flags & 16 /* Function */)) {
67588                 return false;
67589             }
67590             return !!ts.forEachEntry(getExportsOfSymbol(symbol), function (p) { return p.flags & 111551 /* Value */ && p.valueDeclaration && ts.isPropertyAccessExpression(p.valueDeclaration); });
67591         }
67592         function getPropertiesOfContainerFunction(node) {
67593             var declaration = ts.getParseTreeNode(node, ts.isFunctionDeclaration);
67594             if (!declaration) {
67595                 return ts.emptyArray;
67596             }
67597             var symbol = getSymbolOfNode(declaration);
67598             return symbol && getPropertiesOfType(getTypeOfSymbol(symbol)) || ts.emptyArray;
67599         }
67600         function getNodeCheckFlags(node) {
67601             return getNodeLinks(node).flags || 0;
67602         }
67603         function getEnumMemberValue(node) {
67604             computeEnumMemberValues(node.parent);
67605             return getNodeLinks(node).enumMemberValue;
67606         }
67607         function canHaveConstantValue(node) {
67608             switch (node.kind) {
67609                 case 284 /* EnumMember */:
67610                 case 194 /* PropertyAccessExpression */:
67611                 case 195 /* ElementAccessExpression */:
67612                     return true;
67613             }
67614             return false;
67615         }
67616         function getConstantValue(node) {
67617             if (node.kind === 284 /* EnumMember */) {
67618                 return getEnumMemberValue(node);
67619             }
67620             var symbol = getNodeLinks(node).resolvedSymbol;
67621             if (symbol && (symbol.flags & 8 /* EnumMember */)) {
67622                 // inline property\index accesses only for const enums
67623                 var member = symbol.valueDeclaration;
67624                 if (ts.isEnumConst(member.parent)) {
67625                     return getEnumMemberValue(member);
67626                 }
67627             }
67628             return undefined;
67629         }
67630         function isFunctionType(type) {
67631             return !!(type.flags & 524288 /* Object */) && getSignaturesOfType(type, 0 /* Call */).length > 0;
67632         }
67633         function getTypeReferenceSerializationKind(typeNameIn, location) {
67634             // ensure both `typeName` and `location` are parse tree nodes.
67635             var typeName = ts.getParseTreeNode(typeNameIn, ts.isEntityName);
67636             if (!typeName)
67637                 return ts.TypeReferenceSerializationKind.Unknown;
67638             if (location) {
67639                 location = ts.getParseTreeNode(location);
67640                 if (!location)
67641                     return ts.TypeReferenceSerializationKind.Unknown;
67642             }
67643             // Resolve the symbol as a value to ensure the type can be reached at runtime during emit.
67644             var valueSymbol = resolveEntityName(typeName, 111551 /* Value */, /*ignoreErrors*/ true, /*dontResolveAlias*/ false, location);
67645             // Resolve the symbol as a type so that we can provide a more useful hint for the type serializer.
67646             var typeSymbol = resolveEntityName(typeName, 788968 /* Type */, /*ignoreErrors*/ true, /*dontResolveAlias*/ false, location);
67647             if (valueSymbol && valueSymbol === typeSymbol) {
67648                 var globalPromiseSymbol = getGlobalPromiseConstructorSymbol(/*reportErrors*/ false);
67649                 if (globalPromiseSymbol && valueSymbol === globalPromiseSymbol) {
67650                     return ts.TypeReferenceSerializationKind.Promise;
67651                 }
67652                 var constructorType = getTypeOfSymbol(valueSymbol);
67653                 if (constructorType && isConstructorType(constructorType)) {
67654                     return ts.TypeReferenceSerializationKind.TypeWithConstructSignatureAndValue;
67655                 }
67656             }
67657             // We might not be able to resolve type symbol so use unknown type in that case (eg error case)
67658             if (!typeSymbol) {
67659                 return ts.TypeReferenceSerializationKind.Unknown;
67660             }
67661             var type = getDeclaredTypeOfSymbol(typeSymbol);
67662             if (type === errorType) {
67663                 return ts.TypeReferenceSerializationKind.Unknown;
67664             }
67665             else if (type.flags & 3 /* AnyOrUnknown */) {
67666                 return ts.TypeReferenceSerializationKind.ObjectType;
67667             }
67668             else if (isTypeAssignableToKind(type, 16384 /* Void */ | 98304 /* Nullable */ | 131072 /* Never */)) {
67669                 return ts.TypeReferenceSerializationKind.VoidNullableOrNeverType;
67670             }
67671             else if (isTypeAssignableToKind(type, 528 /* BooleanLike */)) {
67672                 return ts.TypeReferenceSerializationKind.BooleanType;
67673             }
67674             else if (isTypeAssignableToKind(type, 296 /* NumberLike */)) {
67675                 return ts.TypeReferenceSerializationKind.NumberLikeType;
67676             }
67677             else if (isTypeAssignableToKind(type, 2112 /* BigIntLike */)) {
67678                 return ts.TypeReferenceSerializationKind.BigIntLikeType;
67679             }
67680             else if (isTypeAssignableToKind(type, 132 /* StringLike */)) {
67681                 return ts.TypeReferenceSerializationKind.StringLikeType;
67682             }
67683             else if (isTupleType(type)) {
67684                 return ts.TypeReferenceSerializationKind.ArrayLikeType;
67685             }
67686             else if (isTypeAssignableToKind(type, 12288 /* ESSymbolLike */)) {
67687                 return ts.TypeReferenceSerializationKind.ESSymbolType;
67688             }
67689             else if (isFunctionType(type)) {
67690                 return ts.TypeReferenceSerializationKind.TypeWithCallSignature;
67691             }
67692             else if (isArrayType(type)) {
67693                 return ts.TypeReferenceSerializationKind.ArrayLikeType;
67694             }
67695             else {
67696                 return ts.TypeReferenceSerializationKind.ObjectType;
67697             }
67698         }
67699         function createTypeOfDeclaration(declarationIn, enclosingDeclaration, flags, tracker, addUndefined) {
67700             var declaration = ts.getParseTreeNode(declarationIn, ts.isVariableLikeOrAccessor);
67701             if (!declaration) {
67702                 return ts.createToken(125 /* AnyKeyword */);
67703             }
67704             // Get type of the symbol if this is the valid symbol otherwise get type at location
67705             var symbol = getSymbolOfNode(declaration);
67706             var type = symbol && !(symbol.flags & (2048 /* TypeLiteral */ | 131072 /* Signature */))
67707                 ? getWidenedLiteralType(getTypeOfSymbol(symbol))
67708                 : errorType;
67709             if (type.flags & 8192 /* UniqueESSymbol */ &&
67710                 type.symbol === symbol) {
67711                 flags |= 1048576 /* AllowUniqueESSymbolType */;
67712             }
67713             if (addUndefined) {
67714                 type = getOptionalType(type);
67715             }
67716             return nodeBuilder.typeToTypeNode(type, enclosingDeclaration, flags | 1024 /* MultilineObjectLiterals */, tracker);
67717         }
67718         function createReturnTypeOfSignatureDeclaration(signatureDeclarationIn, enclosingDeclaration, flags, tracker) {
67719             var signatureDeclaration = ts.getParseTreeNode(signatureDeclarationIn, ts.isFunctionLike);
67720             if (!signatureDeclaration) {
67721                 return ts.createToken(125 /* AnyKeyword */);
67722             }
67723             var signature = getSignatureFromDeclaration(signatureDeclaration);
67724             return nodeBuilder.typeToTypeNode(getReturnTypeOfSignature(signature), enclosingDeclaration, flags | 1024 /* MultilineObjectLiterals */, tracker);
67725         }
67726         function createTypeOfExpression(exprIn, enclosingDeclaration, flags, tracker) {
67727             var expr = ts.getParseTreeNode(exprIn, ts.isExpression);
67728             if (!expr) {
67729                 return ts.createToken(125 /* AnyKeyword */);
67730             }
67731             var type = getWidenedType(getRegularTypeOfExpression(expr));
67732             return nodeBuilder.typeToTypeNode(type, enclosingDeclaration, flags | 1024 /* MultilineObjectLiterals */, tracker);
67733         }
67734         function hasGlobalName(name) {
67735             return globals.has(ts.escapeLeadingUnderscores(name));
67736         }
67737         function getReferencedValueSymbol(reference, startInDeclarationContainer) {
67738             var resolvedSymbol = getNodeLinks(reference).resolvedSymbol;
67739             if (resolvedSymbol) {
67740                 return resolvedSymbol;
67741             }
67742             var location = reference;
67743             if (startInDeclarationContainer) {
67744                 // When resolving the name of a declaration as a value, we need to start resolution
67745                 // at a point outside of the declaration.
67746                 var parent = reference.parent;
67747                 if (ts.isDeclaration(parent) && reference === parent.name) {
67748                     location = getDeclarationContainer(parent);
67749                 }
67750             }
67751             return resolveName(location, reference.escapedText, 111551 /* Value */ | 1048576 /* ExportValue */ | 2097152 /* Alias */, /*nodeNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ true);
67752         }
67753         function getReferencedValueDeclaration(referenceIn) {
67754             if (!ts.isGeneratedIdentifier(referenceIn)) {
67755                 var reference = ts.getParseTreeNode(referenceIn, ts.isIdentifier);
67756                 if (reference) {
67757                     var symbol = getReferencedValueSymbol(reference);
67758                     if (symbol) {
67759                         return getExportSymbolOfValueSymbolIfExported(symbol).valueDeclaration;
67760                     }
67761                 }
67762             }
67763             return undefined;
67764         }
67765         function isLiteralConstDeclaration(node) {
67766             if (ts.isDeclarationReadonly(node) || ts.isVariableDeclaration(node) && ts.isVarConst(node)) {
67767                 return isFreshLiteralType(getTypeOfSymbol(getSymbolOfNode(node)));
67768             }
67769             return false;
67770         }
67771         function literalTypeToNode(type, enclosing, tracker) {
67772             var enumResult = type.flags & 1024 /* EnumLiteral */ ? nodeBuilder.symbolToExpression(type.symbol, 111551 /* Value */, enclosing, /*flags*/ undefined, tracker)
67773                 : type === trueType ? ts.createTrue() : type === falseType && ts.createFalse();
67774             return enumResult || ts.createLiteral(type.value);
67775         }
67776         function createLiteralConstValue(node, tracker) {
67777             var type = getTypeOfSymbol(getSymbolOfNode(node));
67778             return literalTypeToNode(type, node, tracker);
67779         }
67780         function getJsxFactoryEntity(location) {
67781             return location ? (getJsxNamespace(location), (ts.getSourceFileOfNode(location).localJsxFactory || _jsxFactoryEntity)) : _jsxFactoryEntity;
67782         }
67783         function createResolver() {
67784             // this variable and functions that use it are deliberately moved here from the outer scope
67785             // to avoid scope pollution
67786             var resolvedTypeReferenceDirectives = host.getResolvedTypeReferenceDirectives();
67787             var fileToDirective;
67788             if (resolvedTypeReferenceDirectives) {
67789                 // populate reverse mapping: file path -> type reference directive that was resolved to this file
67790                 fileToDirective = ts.createMap();
67791                 resolvedTypeReferenceDirectives.forEach(function (resolvedDirective, key) {
67792                     if (!resolvedDirective || !resolvedDirective.resolvedFileName) {
67793                         return;
67794                     }
67795                     var file = host.getSourceFile(resolvedDirective.resolvedFileName);
67796                     if (file) {
67797                         // Add the transitive closure of path references loaded by this file (as long as they are not)
67798                         // part of an existing type reference.
67799                         addReferencedFilesToTypeDirective(file, key);
67800                     }
67801                 });
67802             }
67803             return {
67804                 getReferencedExportContainer: getReferencedExportContainer,
67805                 getReferencedImportDeclaration: getReferencedImportDeclaration,
67806                 getReferencedDeclarationWithCollidingName: getReferencedDeclarationWithCollidingName,
67807                 isDeclarationWithCollidingName: isDeclarationWithCollidingName,
67808                 isValueAliasDeclaration: function (node) {
67809                     node = ts.getParseTreeNode(node);
67810                     // Synthesized nodes are always treated like values.
67811                     return node ? isValueAliasDeclaration(node) : true;
67812                 },
67813                 hasGlobalName: hasGlobalName,
67814                 isReferencedAliasDeclaration: function (node, checkChildren) {
67815                     node = ts.getParseTreeNode(node);
67816                     // Synthesized nodes are always treated as referenced.
67817                     return node ? isReferencedAliasDeclaration(node, checkChildren) : true;
67818                 },
67819                 getNodeCheckFlags: function (node) {
67820                     node = ts.getParseTreeNode(node);
67821                     return node ? getNodeCheckFlags(node) : 0;
67822                 },
67823                 isTopLevelValueImportEqualsWithEntityName: isTopLevelValueImportEqualsWithEntityName,
67824                 isDeclarationVisible: isDeclarationVisible,
67825                 isImplementationOfOverload: isImplementationOfOverload,
67826                 isRequiredInitializedParameter: isRequiredInitializedParameter,
67827                 isOptionalUninitializedParameterProperty: isOptionalUninitializedParameterProperty,
67828                 isExpandoFunctionDeclaration: isExpandoFunctionDeclaration,
67829                 getPropertiesOfContainerFunction: getPropertiesOfContainerFunction,
67830                 createTypeOfDeclaration: createTypeOfDeclaration,
67831                 createReturnTypeOfSignatureDeclaration: createReturnTypeOfSignatureDeclaration,
67832                 createTypeOfExpression: createTypeOfExpression,
67833                 createLiteralConstValue: createLiteralConstValue,
67834                 isSymbolAccessible: isSymbolAccessible,
67835                 isEntityNameVisible: isEntityNameVisible,
67836                 getConstantValue: function (nodeIn) {
67837                     var node = ts.getParseTreeNode(nodeIn, canHaveConstantValue);
67838                     return node ? getConstantValue(node) : undefined;
67839                 },
67840                 collectLinkedAliases: collectLinkedAliases,
67841                 getReferencedValueDeclaration: getReferencedValueDeclaration,
67842                 getTypeReferenceSerializationKind: getTypeReferenceSerializationKind,
67843                 isOptionalParameter: isOptionalParameter,
67844                 moduleExportsSomeValue: moduleExportsSomeValue,
67845                 isArgumentsLocalBinding: isArgumentsLocalBinding,
67846                 getExternalModuleFileFromDeclaration: getExternalModuleFileFromDeclaration,
67847                 getTypeReferenceDirectivesForEntityName: getTypeReferenceDirectivesForEntityName,
67848                 getTypeReferenceDirectivesForSymbol: getTypeReferenceDirectivesForSymbol,
67849                 isLiteralConstDeclaration: isLiteralConstDeclaration,
67850                 isLateBound: function (nodeIn) {
67851                     var node = ts.getParseTreeNode(nodeIn, ts.isDeclaration);
67852                     var symbol = node && getSymbolOfNode(node);
67853                     return !!(symbol && ts.getCheckFlags(symbol) & 4096 /* Late */);
67854                 },
67855                 getJsxFactoryEntity: getJsxFactoryEntity,
67856                 getAllAccessorDeclarations: function (accessor) {
67857                     accessor = ts.getParseTreeNode(accessor, ts.isGetOrSetAccessorDeclaration); // TODO: GH#18217
67858                     var otherKind = accessor.kind === 164 /* SetAccessor */ ? 163 /* GetAccessor */ : 164 /* SetAccessor */;
67859                     var otherAccessor = ts.getDeclarationOfKind(getSymbolOfNode(accessor), otherKind);
67860                     var firstAccessor = otherAccessor && (otherAccessor.pos < accessor.pos) ? otherAccessor : accessor;
67861                     var secondAccessor = otherAccessor && (otherAccessor.pos < accessor.pos) ? accessor : otherAccessor;
67862                     var setAccessor = accessor.kind === 164 /* SetAccessor */ ? accessor : otherAccessor;
67863                     var getAccessor = accessor.kind === 163 /* GetAccessor */ ? accessor : otherAccessor;
67864                     return {
67865                         firstAccessor: firstAccessor,
67866                         secondAccessor: secondAccessor,
67867                         setAccessor: setAccessor,
67868                         getAccessor: getAccessor
67869                     };
67870                 },
67871                 getSymbolOfExternalModuleSpecifier: function (moduleName) { return resolveExternalModuleNameWorker(moduleName, moduleName, /*moduleNotFoundError*/ undefined); },
67872                 isBindingCapturedByNode: function (node, decl) {
67873                     var parseNode = ts.getParseTreeNode(node);
67874                     var parseDecl = ts.getParseTreeNode(decl);
67875                     return !!parseNode && !!parseDecl && (ts.isVariableDeclaration(parseDecl) || ts.isBindingElement(parseDecl)) && isBindingCapturedByNode(parseNode, parseDecl);
67876                 },
67877                 getDeclarationStatementsForSourceFile: function (node, flags, tracker, bundled) {
67878                     var n = ts.getParseTreeNode(node);
67879                     ts.Debug.assert(n && n.kind === 290 /* SourceFile */, "Non-sourcefile node passed into getDeclarationsForSourceFile");
67880                     var sym = getSymbolOfNode(node);
67881                     if (!sym) {
67882                         return !node.locals ? [] : nodeBuilder.symbolTableToDeclarationStatements(node.locals, node, flags, tracker, bundled);
67883                     }
67884                     return !sym.exports ? [] : nodeBuilder.symbolTableToDeclarationStatements(sym.exports, node, flags, tracker, bundled);
67885                 },
67886                 isImportRequiredByAugmentation: isImportRequiredByAugmentation,
67887             };
67888             function isImportRequiredByAugmentation(node) {
67889                 var file = ts.getSourceFileOfNode(node);
67890                 if (!file.symbol)
67891                     return false;
67892                 var importTarget = getExternalModuleFileFromDeclaration(node);
67893                 if (!importTarget)
67894                     return false;
67895                 if (importTarget === file)
67896                     return false;
67897                 var exports = getExportsOfModule(file.symbol);
67898                 for (var _i = 0, _a = ts.arrayFrom(exports.values()); _i < _a.length; _i++) {
67899                     var s = _a[_i];
67900                     if (s.mergeId) {
67901                         var merged = getMergedSymbol(s);
67902                         for (var _b = 0, _c = merged.declarations; _b < _c.length; _b++) {
67903                             var d = _c[_b];
67904                             var declFile = ts.getSourceFileOfNode(d);
67905                             if (declFile === importTarget) {
67906                                 return true;
67907                             }
67908                         }
67909                     }
67910                 }
67911                 return false;
67912             }
67913             function isInHeritageClause(node) {
67914                 return node.parent && node.parent.kind === 216 /* ExpressionWithTypeArguments */ && node.parent.parent && node.parent.parent.kind === 279 /* HeritageClause */;
67915             }
67916             // defined here to avoid outer scope pollution
67917             function getTypeReferenceDirectivesForEntityName(node) {
67918                 // program does not have any files with type reference directives - bail out
67919                 if (!fileToDirective) {
67920                     return undefined;
67921                 }
67922                 // property access can only be used as values, or types when within an expression with type arguments inside a heritage clause
67923                 // qualified names can only be used as types\namespaces
67924                 // identifiers are treated as values only if they appear in type queries
67925                 var meaning = 788968 /* Type */ | 1920 /* Namespace */;
67926                 if ((node.kind === 75 /* Identifier */ && isInTypeQuery(node)) || (node.kind === 194 /* PropertyAccessExpression */ && !isInHeritageClause(node))) {
67927                     meaning = 111551 /* Value */ | 1048576 /* ExportValue */;
67928                 }
67929                 var symbol = resolveEntityName(node, meaning, /*ignoreErrors*/ true);
67930                 return symbol && symbol !== unknownSymbol ? getTypeReferenceDirectivesForSymbol(symbol, meaning) : undefined;
67931             }
67932             // defined here to avoid outer scope pollution
67933             function getTypeReferenceDirectivesForSymbol(symbol, meaning) {
67934                 // program does not have any files with type reference directives - bail out
67935                 if (!fileToDirective) {
67936                     return undefined;
67937                 }
67938                 if (!isSymbolFromTypeDeclarationFile(symbol)) {
67939                     return undefined;
67940                 }
67941                 // check what declarations in the symbol can contribute to the target meaning
67942                 var typeReferenceDirectives;
67943                 for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) {
67944                     var decl = _a[_i];
67945                     // check meaning of the local symbol to see if declaration needs to be analyzed further
67946                     if (decl.symbol && decl.symbol.flags & meaning) {
67947                         var file = ts.getSourceFileOfNode(decl);
67948                         var typeReferenceDirective = fileToDirective.get(file.path);
67949                         if (typeReferenceDirective) {
67950                             (typeReferenceDirectives || (typeReferenceDirectives = [])).push(typeReferenceDirective);
67951                         }
67952                         else {
67953                             // found at least one entry that does not originate from type reference directive
67954                             return undefined;
67955                         }
67956                     }
67957                 }
67958                 return typeReferenceDirectives;
67959             }
67960             function isSymbolFromTypeDeclarationFile(symbol) {
67961                 // bail out if symbol does not have associated declarations (i.e. this is transient symbol created for property in binding pattern)
67962                 if (!symbol.declarations) {
67963                     return false;
67964                 }
67965                 // walk the parent chain for symbols to make sure that top level parent symbol is in the global scope
67966                 // external modules cannot define or contribute to type declaration files
67967                 var current = symbol;
67968                 while (true) {
67969                     var parent = getParentOfSymbol(current);
67970                     if (parent) {
67971                         current = parent;
67972                     }
67973                     else {
67974                         break;
67975                     }
67976                 }
67977                 if (current.valueDeclaration && current.valueDeclaration.kind === 290 /* SourceFile */ && current.flags & 512 /* ValueModule */) {
67978                     return false;
67979                 }
67980                 // check that at least one declaration of top level symbol originates from type declaration file
67981                 for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) {
67982                     var decl = _a[_i];
67983                     var file = ts.getSourceFileOfNode(decl);
67984                     if (fileToDirective.has(file.path)) {
67985                         return true;
67986                     }
67987                 }
67988                 return false;
67989             }
67990             function addReferencedFilesToTypeDirective(file, key) {
67991                 if (fileToDirective.has(file.path))
67992                     return;
67993                 fileToDirective.set(file.path, key);
67994                 for (var _i = 0, _a = file.referencedFiles; _i < _a.length; _i++) {
67995                     var fileName = _a[_i].fileName;
67996                     var resolvedFile = ts.resolveTripleslashReference(fileName, file.originalFileName);
67997                     var referencedFile = host.getSourceFile(resolvedFile);
67998                     if (referencedFile) {
67999                         addReferencedFilesToTypeDirective(referencedFile, key);
68000                     }
68001                 }
68002             }
68003         }
68004         function getExternalModuleFileFromDeclaration(declaration) {
68005             var specifier = declaration.kind === 249 /* ModuleDeclaration */ ? ts.tryCast(declaration.name, ts.isStringLiteral) : ts.getExternalModuleName(declaration);
68006             var moduleSymbol = resolveExternalModuleNameWorker(specifier, specifier, /*moduleNotFoundError*/ undefined); // TODO: GH#18217
68007             if (!moduleSymbol) {
68008                 return undefined;
68009             }
68010             return ts.getDeclarationOfKind(moduleSymbol, 290 /* SourceFile */);
68011         }
68012         function initializeTypeChecker() {
68013             // Bind all source files and propagate errors
68014             for (var _i = 0, _a = host.getSourceFiles(); _i < _a.length; _i++) {
68015                 var file = _a[_i];
68016                 ts.bindSourceFile(file, compilerOptions);
68017             }
68018             amalgamatedDuplicates = ts.createMap();
68019             // Initialize global symbol table
68020             var augmentations;
68021             for (var _b = 0, _c = host.getSourceFiles(); _b < _c.length; _b++) {
68022                 var file = _c[_b];
68023                 if (file.redirectInfo) {
68024                     continue;
68025                 }
68026                 if (!ts.isExternalOrCommonJsModule(file)) {
68027                     // It is an error for a non-external-module (i.e. script) to declare its own `globalThis`.
68028                     // We can't use `builtinGlobals` for this due to synthetic expando-namespace generation in JS files.
68029                     var fileGlobalThisSymbol = file.locals.get("globalThis");
68030                     if (fileGlobalThisSymbol) {
68031                         for (var _d = 0, _e = fileGlobalThisSymbol.declarations; _d < _e.length; _d++) {
68032                             var declaration = _e[_d];
68033                             diagnostics.add(ts.createDiagnosticForNode(declaration, ts.Diagnostics.Declaration_name_conflicts_with_built_in_global_identifier_0, "globalThis"));
68034                         }
68035                     }
68036                     mergeSymbolTable(globals, file.locals);
68037                 }
68038                 if (file.jsGlobalAugmentations) {
68039                     mergeSymbolTable(globals, file.jsGlobalAugmentations);
68040                 }
68041                 if (file.patternAmbientModules && file.patternAmbientModules.length) {
68042                     patternAmbientModules = ts.concatenate(patternAmbientModules, file.patternAmbientModules);
68043                 }
68044                 if (file.moduleAugmentations.length) {
68045                     (augmentations || (augmentations = [])).push(file.moduleAugmentations);
68046                 }
68047                 if (file.symbol && file.symbol.globalExports) {
68048                     // Merge in UMD exports with first-in-wins semantics (see #9771)
68049                     var source = file.symbol.globalExports;
68050                     source.forEach(function (sourceSymbol, id) {
68051                         if (!globals.has(id)) {
68052                             globals.set(id, sourceSymbol);
68053                         }
68054                     });
68055                 }
68056             }
68057             // We do global augmentations separately from module augmentations (and before creating global types) because they
68058             //  1. Affect global types. We won't have the correct global types until global augmentations are merged. Also,
68059             //  2. Module augmentation instantiation requires creating the type of a module, which, in turn, can require
68060             //       checking for an export or property on the module (if export=) which, in turn, can fall back to the
68061             //       apparent type of the module - either globalObjectType or globalFunctionType - which wouldn't exist if we
68062             //       did module augmentations prior to finalizing the global types.
68063             if (augmentations) {
68064                 // merge _global_ module augmentations.
68065                 // this needs to be done after global symbol table is initialized to make sure that all ambient modules are indexed
68066                 for (var _f = 0, augmentations_1 = augmentations; _f < augmentations_1.length; _f++) {
68067                     var list = augmentations_1[_f];
68068                     for (var _g = 0, list_1 = list; _g < list_1.length; _g++) {
68069                         var augmentation = list_1[_g];
68070                         if (!ts.isGlobalScopeAugmentation(augmentation.parent))
68071                             continue;
68072                         mergeModuleAugmentation(augmentation);
68073                     }
68074                 }
68075             }
68076             // Setup global builtins
68077             addToSymbolTable(globals, builtinGlobals, ts.Diagnostics.Declaration_name_conflicts_with_built_in_global_identifier_0);
68078             getSymbolLinks(undefinedSymbol).type = undefinedWideningType;
68079             getSymbolLinks(argumentsSymbol).type = getGlobalType("IArguments", /*arity*/ 0, /*reportErrors*/ true);
68080             getSymbolLinks(unknownSymbol).type = errorType;
68081             getSymbolLinks(globalThisSymbol).type = createObjectType(16 /* Anonymous */, globalThisSymbol);
68082             // Initialize special types
68083             globalArrayType = getGlobalType("Array", /*arity*/ 1, /*reportErrors*/ true);
68084             globalObjectType = getGlobalType("Object", /*arity*/ 0, /*reportErrors*/ true);
68085             globalFunctionType = getGlobalType("Function", /*arity*/ 0, /*reportErrors*/ true);
68086             globalCallableFunctionType = strictBindCallApply && getGlobalType("CallableFunction", /*arity*/ 0, /*reportErrors*/ true) || globalFunctionType;
68087             globalNewableFunctionType = strictBindCallApply && getGlobalType("NewableFunction", /*arity*/ 0, /*reportErrors*/ true) || globalFunctionType;
68088             globalStringType = getGlobalType("String", /*arity*/ 0, /*reportErrors*/ true);
68089             globalNumberType = getGlobalType("Number", /*arity*/ 0, /*reportErrors*/ true);
68090             globalBooleanType = getGlobalType("Boolean", /*arity*/ 0, /*reportErrors*/ true);
68091             globalRegExpType = getGlobalType("RegExp", /*arity*/ 0, /*reportErrors*/ true);
68092             anyArrayType = createArrayType(anyType);
68093             autoArrayType = createArrayType(autoType);
68094             if (autoArrayType === emptyObjectType) {
68095                 // autoArrayType is used as a marker, so even if global Array type is not defined, it needs to be a unique type
68096                 autoArrayType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined);
68097             }
68098             globalReadonlyArrayType = getGlobalTypeOrUndefined("ReadonlyArray", /*arity*/ 1) || globalArrayType;
68099             anyReadonlyArrayType = globalReadonlyArrayType ? createTypeFromGenericGlobalType(globalReadonlyArrayType, [anyType]) : anyArrayType;
68100             globalThisType = getGlobalTypeOrUndefined("ThisType", /*arity*/ 1);
68101             if (augmentations) {
68102                 // merge _nonglobal_ module augmentations.
68103                 // this needs to be done after global symbol table is initialized to make sure that all ambient modules are indexed
68104                 for (var _h = 0, augmentations_2 = augmentations; _h < augmentations_2.length; _h++) {
68105                     var list = augmentations_2[_h];
68106                     for (var _j = 0, list_2 = list; _j < list_2.length; _j++) {
68107                         var augmentation = list_2[_j];
68108                         if (ts.isGlobalScopeAugmentation(augmentation.parent))
68109                             continue;
68110                         mergeModuleAugmentation(augmentation);
68111                     }
68112                 }
68113             }
68114             amalgamatedDuplicates.forEach(function (_a) {
68115                 var firstFile = _a.firstFile, secondFile = _a.secondFile, conflictingSymbols = _a.conflictingSymbols;
68116                 // If not many things conflict, issue individual errors
68117                 if (conflictingSymbols.size < 8) {
68118                     conflictingSymbols.forEach(function (_a, symbolName) {
68119                         var isBlockScoped = _a.isBlockScoped, firstFileLocations = _a.firstFileLocations, secondFileLocations = _a.secondFileLocations;
68120                         var message = isBlockScoped ? ts.Diagnostics.Cannot_redeclare_block_scoped_variable_0 : ts.Diagnostics.Duplicate_identifier_0;
68121                         for (var _i = 0, firstFileLocations_1 = firstFileLocations; _i < firstFileLocations_1.length; _i++) {
68122                             var node = firstFileLocations_1[_i];
68123                             addDuplicateDeclarationError(node, message, symbolName, secondFileLocations);
68124                         }
68125                         for (var _b = 0, secondFileLocations_1 = secondFileLocations; _b < secondFileLocations_1.length; _b++) {
68126                             var node = secondFileLocations_1[_b];
68127                             addDuplicateDeclarationError(node, message, symbolName, firstFileLocations);
68128                         }
68129                     });
68130                 }
68131                 else {
68132                     // Otherwise issue top-level error since the files appear very identical in terms of what they contain
68133                     var list = ts.arrayFrom(conflictingSymbols.keys()).join(", ");
68134                     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)));
68135                     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)));
68136                 }
68137             });
68138             amalgamatedDuplicates = undefined;
68139         }
68140         function checkExternalEmitHelpers(location, helpers) {
68141             if ((requestedExternalEmitHelpers & helpers) !== helpers && compilerOptions.importHelpers) {
68142                 var sourceFile = ts.getSourceFileOfNode(location);
68143                 if (ts.isEffectiveExternalModule(sourceFile, compilerOptions) && !(location.flags & 8388608 /* Ambient */)) {
68144                     var helpersModule = resolveHelpersModule(sourceFile, location);
68145                     if (helpersModule !== unknownSymbol) {
68146                         var uncheckedHelpers = helpers & ~requestedExternalEmitHelpers;
68147                         for (var helper = 1 /* FirstEmitHelper */; helper <= 1048576 /* LastEmitHelper */; helper <<= 1) {
68148                             if (uncheckedHelpers & helper) {
68149                                 var name = getHelperName(helper);
68150                                 var symbol = getSymbol(helpersModule.exports, ts.escapeLeadingUnderscores(name), 111551 /* Value */);
68151                                 if (!symbol) {
68152                                     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);
68153                                 }
68154                             }
68155                         }
68156                     }
68157                     requestedExternalEmitHelpers |= helpers;
68158                 }
68159             }
68160         }
68161         function getHelperName(helper) {
68162             switch (helper) {
68163                 case 1 /* Extends */: return "__extends";
68164                 case 2 /* Assign */: return "__assign";
68165                 case 4 /* Rest */: return "__rest";
68166                 case 8 /* Decorate */: return "__decorate";
68167                 case 16 /* Metadata */: return "__metadata";
68168                 case 32 /* Param */: return "__param";
68169                 case 64 /* Awaiter */: return "__awaiter";
68170                 case 128 /* Generator */: return "__generator";
68171                 case 256 /* Values */: return "__values";
68172                 case 512 /* Read */: return "__read";
68173                 case 1024 /* Spread */: return "__spread";
68174                 case 2048 /* SpreadArrays */: return "__spreadArrays";
68175                 case 4096 /* Await */: return "__await";
68176                 case 8192 /* AsyncGenerator */: return "__asyncGenerator";
68177                 case 16384 /* AsyncDelegator */: return "__asyncDelegator";
68178                 case 32768 /* AsyncValues */: return "__asyncValues";
68179                 case 65536 /* ExportStar */: return "__exportStar";
68180                 case 131072 /* MakeTemplateObject */: return "__makeTemplateObject";
68181                 case 262144 /* ClassPrivateFieldGet */: return "__classPrivateFieldGet";
68182                 case 524288 /* ClassPrivateFieldSet */: return "__classPrivateFieldSet";
68183                 case 1048576 /* CreateBinding */: return "__createBinding";
68184                 default: return ts.Debug.fail("Unrecognized helper");
68185             }
68186         }
68187         function resolveHelpersModule(node, errorNode) {
68188             if (!externalHelpersModule) {
68189                 externalHelpersModule = resolveExternalModule(node, ts.externalHelpersModuleNameText, ts.Diagnostics.This_syntax_requires_an_imported_helper_but_module_0_cannot_be_found, errorNode) || unknownSymbol;
68190             }
68191             return externalHelpersModule;
68192         }
68193         // GRAMMAR CHECKING
68194         function checkGrammarDecoratorsAndModifiers(node) {
68195             return checkGrammarDecorators(node) || checkGrammarModifiers(node);
68196         }
68197         function checkGrammarDecorators(node) {
68198             if (!node.decorators) {
68199                 return false;
68200             }
68201             if (!ts.nodeCanBeDecorated(node, node.parent, node.parent.parent)) {
68202                 if (node.kind === 161 /* MethodDeclaration */ && !ts.nodeIsPresent(node.body)) {
68203                     return grammarErrorOnFirstToken(node, ts.Diagnostics.A_decorator_can_only_decorate_a_method_implementation_not_an_overload);
68204                 }
68205                 else {
68206                     return grammarErrorOnFirstToken(node, ts.Diagnostics.Decorators_are_not_valid_here);
68207                 }
68208             }
68209             else if (node.kind === 163 /* GetAccessor */ || node.kind === 164 /* SetAccessor */) {
68210                 var accessors = ts.getAllAccessorDeclarations(node.parent.members, node);
68211                 if (accessors.firstAccessor.decorators && node === accessors.secondAccessor) {
68212                     return grammarErrorOnFirstToken(node, ts.Diagnostics.Decorators_cannot_be_applied_to_multiple_get_Slashset_accessors_of_the_same_name);
68213                 }
68214             }
68215             return false;
68216         }
68217         function checkGrammarModifiers(node) {
68218             var quickResult = reportObviousModifierErrors(node);
68219             if (quickResult !== undefined) {
68220                 return quickResult;
68221             }
68222             var lastStatic, lastDeclare, lastAsync, lastReadonly;
68223             var flags = 0 /* None */;
68224             for (var _i = 0, _a = node.modifiers; _i < _a.length; _i++) {
68225                 var modifier = _a[_i];
68226                 if (modifier.kind !== 138 /* ReadonlyKeyword */) {
68227                     if (node.kind === 158 /* PropertySignature */ || node.kind === 160 /* MethodSignature */) {
68228                         return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_type_member, ts.tokenToString(modifier.kind));
68229                     }
68230                     if (node.kind === 167 /* IndexSignature */) {
68231                         return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_an_index_signature, ts.tokenToString(modifier.kind));
68232                     }
68233                 }
68234                 switch (modifier.kind) {
68235                     case 81 /* ConstKeyword */:
68236                         if (node.kind !== 248 /* EnumDeclaration */) {
68237                             return grammarErrorOnNode(node, ts.Diagnostics.A_class_member_cannot_have_the_0_keyword, ts.tokenToString(81 /* ConstKeyword */));
68238                         }
68239                         break;
68240                     case 119 /* PublicKeyword */:
68241                     case 118 /* ProtectedKeyword */:
68242                     case 117 /* PrivateKeyword */:
68243                         var text = visibilityToString(ts.modifierToFlag(modifier.kind));
68244                         if (flags & 28 /* AccessibilityModifier */) {
68245                             return grammarErrorOnNode(modifier, ts.Diagnostics.Accessibility_modifier_already_seen);
68246                         }
68247                         else if (flags & 32 /* Static */) {
68248                             return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, text, "static");
68249                         }
68250                         else if (flags & 64 /* Readonly */) {
68251                             return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, text, "readonly");
68252                         }
68253                         else if (flags & 256 /* Async */) {
68254                             return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, text, "async");
68255                         }
68256                         else if (node.parent.kind === 250 /* ModuleBlock */ || node.parent.kind === 290 /* SourceFile */) {
68257                             return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_module_or_namespace_element, text);
68258                         }
68259                         else if (flags & 128 /* Abstract */) {
68260                             if (modifier.kind === 117 /* PrivateKeyword */) {
68261                                 return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_with_1_modifier, text, "abstract");
68262                             }
68263                             else {
68264                                 return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, text, "abstract");
68265                             }
68266                         }
68267                         else if (ts.isPrivateIdentifierPropertyDeclaration(node)) {
68268                             return grammarErrorOnNode(modifier, ts.Diagnostics.An_accessibility_modifier_cannot_be_used_with_a_private_identifier);
68269                         }
68270                         flags |= ts.modifierToFlag(modifier.kind);
68271                         break;
68272                     case 120 /* StaticKeyword */:
68273                         if (flags & 32 /* Static */) {
68274                             return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "static");
68275                         }
68276                         else if (flags & 64 /* Readonly */) {
68277                             return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, "static", "readonly");
68278                         }
68279                         else if (flags & 256 /* Async */) {
68280                             return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, "static", "async");
68281                         }
68282                         else if (node.parent.kind === 250 /* ModuleBlock */ || node.parent.kind === 290 /* SourceFile */) {
68283                             return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_module_or_namespace_element, "static");
68284                         }
68285                         else if (node.kind === 156 /* Parameter */) {
68286                             return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_parameter, "static");
68287                         }
68288                         else if (flags & 128 /* Abstract */) {
68289                             return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_with_1_modifier, "static", "abstract");
68290                         }
68291                         else if (ts.isPrivateIdentifierPropertyDeclaration(node)) {
68292                             return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_with_a_private_identifier, "static");
68293                         }
68294                         flags |= 32 /* Static */;
68295                         lastStatic = modifier;
68296                         break;
68297                     case 138 /* ReadonlyKeyword */:
68298                         if (flags & 64 /* Readonly */) {
68299                             return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "readonly");
68300                         }
68301                         else if (node.kind !== 159 /* PropertyDeclaration */ && node.kind !== 158 /* PropertySignature */ && node.kind !== 167 /* IndexSignature */ && node.kind !== 156 /* Parameter */) {
68302                             // If node.kind === SyntaxKind.Parameter, checkParameter report an error if it's not a parameter property.
68303                             return grammarErrorOnNode(modifier, ts.Diagnostics.readonly_modifier_can_only_appear_on_a_property_declaration_or_index_signature);
68304                         }
68305                         flags |= 64 /* Readonly */;
68306                         lastReadonly = modifier;
68307                         break;
68308                     case 89 /* ExportKeyword */:
68309                         if (flags & 1 /* Export */) {
68310                             return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "export");
68311                         }
68312                         else if (flags & 2 /* Ambient */) {
68313                             return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, "export", "declare");
68314                         }
68315                         else if (flags & 128 /* Abstract */) {
68316                             return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, "export", "abstract");
68317                         }
68318                         else if (flags & 256 /* Async */) {
68319                             return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, "export", "async");
68320                         }
68321                         else if (ts.isClassLike(node.parent)) {
68322                             return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_class_element, "export");
68323                         }
68324                         else if (node.kind === 156 /* Parameter */) {
68325                             return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_parameter, "export");
68326                         }
68327                         flags |= 1 /* Export */;
68328                         break;
68329                     case 84 /* DefaultKeyword */:
68330                         var container = node.parent.kind === 290 /* SourceFile */ ? node.parent : node.parent.parent;
68331                         if (container.kind === 249 /* ModuleDeclaration */ && !ts.isAmbientModule(container)) {
68332                             return grammarErrorOnNode(modifier, ts.Diagnostics.A_default_export_can_only_be_used_in_an_ECMAScript_style_module);
68333                         }
68334                         flags |= 512 /* Default */;
68335                         break;
68336                     case 130 /* DeclareKeyword */:
68337                         if (flags & 2 /* Ambient */) {
68338                             return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "declare");
68339                         }
68340                         else if (flags & 256 /* Async */) {
68341                             return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_in_an_ambient_context, "async");
68342                         }
68343                         else if (ts.isClassLike(node.parent) && !ts.isPropertyDeclaration(node)) {
68344                             return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_class_element, "declare");
68345                         }
68346                         else if (node.kind === 156 /* Parameter */) {
68347                             return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_parameter, "declare");
68348                         }
68349                         else if ((node.parent.flags & 8388608 /* Ambient */) && node.parent.kind === 250 /* ModuleBlock */) {
68350                             return grammarErrorOnNode(modifier, ts.Diagnostics.A_declare_modifier_cannot_be_used_in_an_already_ambient_context);
68351                         }
68352                         else if (ts.isPrivateIdentifierPropertyDeclaration(node)) {
68353                             return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_with_a_private_identifier, "declare");
68354                         }
68355                         flags |= 2 /* Ambient */;
68356                         lastDeclare = modifier;
68357                         break;
68358                     case 122 /* AbstractKeyword */:
68359                         if (flags & 128 /* Abstract */) {
68360                             return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "abstract");
68361                         }
68362                         if (node.kind !== 245 /* ClassDeclaration */) {
68363                             if (node.kind !== 161 /* MethodDeclaration */ &&
68364                                 node.kind !== 159 /* PropertyDeclaration */ &&
68365                                 node.kind !== 163 /* GetAccessor */ &&
68366                                 node.kind !== 164 /* SetAccessor */) {
68367                                 return grammarErrorOnNode(modifier, ts.Diagnostics.abstract_modifier_can_only_appear_on_a_class_method_or_property_declaration);
68368                             }
68369                             if (!(node.parent.kind === 245 /* ClassDeclaration */ && ts.hasModifier(node.parent, 128 /* Abstract */))) {
68370                                 return grammarErrorOnNode(modifier, ts.Diagnostics.Abstract_methods_can_only_appear_within_an_abstract_class);
68371                             }
68372                             if (flags & 32 /* Static */) {
68373                                 return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_with_1_modifier, "static", "abstract");
68374                             }
68375                             if (flags & 8 /* Private */) {
68376                                 return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_with_1_modifier, "private", "abstract");
68377                             }
68378                         }
68379                         if (ts.isNamedDeclaration(node) && node.name.kind === 76 /* PrivateIdentifier */) {
68380                             return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_with_a_private_identifier, "abstract");
68381                         }
68382                         flags |= 128 /* Abstract */;
68383                         break;
68384                     case 126 /* AsyncKeyword */:
68385                         if (flags & 256 /* Async */) {
68386                             return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "async");
68387                         }
68388                         else if (flags & 2 /* Ambient */ || node.parent.flags & 8388608 /* Ambient */) {
68389                             return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_in_an_ambient_context, "async");
68390                         }
68391                         else if (node.kind === 156 /* Parameter */) {
68392                             return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_parameter, "async");
68393                         }
68394                         flags |= 256 /* Async */;
68395                         lastAsync = modifier;
68396                         break;
68397                 }
68398             }
68399             if (node.kind === 162 /* Constructor */) {
68400                 if (flags & 32 /* Static */) {
68401                     return grammarErrorOnNode(lastStatic, ts.Diagnostics._0_modifier_cannot_appear_on_a_constructor_declaration, "static");
68402                 }
68403                 if (flags & 128 /* Abstract */) {
68404                     return grammarErrorOnNode(lastStatic, ts.Diagnostics._0_modifier_cannot_appear_on_a_constructor_declaration, "abstract"); // TODO: GH#18217
68405                 }
68406                 else if (flags & 256 /* Async */) {
68407                     return grammarErrorOnNode(lastAsync, ts.Diagnostics._0_modifier_cannot_appear_on_a_constructor_declaration, "async");
68408                 }
68409                 else if (flags & 64 /* Readonly */) {
68410                     return grammarErrorOnNode(lastReadonly, ts.Diagnostics._0_modifier_cannot_appear_on_a_constructor_declaration, "readonly");
68411                 }
68412                 return false;
68413             }
68414             else if ((node.kind === 254 /* ImportDeclaration */ || node.kind === 253 /* ImportEqualsDeclaration */) && flags & 2 /* Ambient */) {
68415                 return grammarErrorOnNode(lastDeclare, ts.Diagnostics.A_0_modifier_cannot_be_used_with_an_import_declaration, "declare");
68416             }
68417             else if (node.kind === 156 /* Parameter */ && (flags & 92 /* ParameterPropertyModifier */) && ts.isBindingPattern(node.name)) {
68418                 return grammarErrorOnNode(node, ts.Diagnostics.A_parameter_property_may_not_be_declared_using_a_binding_pattern);
68419             }
68420             else if (node.kind === 156 /* Parameter */ && (flags & 92 /* ParameterPropertyModifier */) && node.dotDotDotToken) {
68421                 return grammarErrorOnNode(node, ts.Diagnostics.A_parameter_property_cannot_be_declared_using_a_rest_parameter);
68422             }
68423             if (flags & 256 /* Async */) {
68424                 return checkGrammarAsyncModifier(node, lastAsync);
68425             }
68426             return false;
68427         }
68428         /**
68429          * true | false: Early return this value from checkGrammarModifiers.
68430          * undefined: Need to do full checking on the modifiers.
68431          */
68432         function reportObviousModifierErrors(node) {
68433             return !node.modifiers
68434                 ? false
68435                 : shouldReportBadModifier(node)
68436                     ? grammarErrorOnFirstToken(node, ts.Diagnostics.Modifiers_cannot_appear_here)
68437                     : undefined;
68438         }
68439         function shouldReportBadModifier(node) {
68440             switch (node.kind) {
68441                 case 163 /* GetAccessor */:
68442                 case 164 /* SetAccessor */:
68443                 case 162 /* Constructor */:
68444                 case 159 /* PropertyDeclaration */:
68445                 case 158 /* PropertySignature */:
68446                 case 161 /* MethodDeclaration */:
68447                 case 160 /* MethodSignature */:
68448                 case 167 /* IndexSignature */:
68449                 case 249 /* ModuleDeclaration */:
68450                 case 254 /* ImportDeclaration */:
68451                 case 253 /* ImportEqualsDeclaration */:
68452                 case 260 /* ExportDeclaration */:
68453                 case 259 /* ExportAssignment */:
68454                 case 201 /* FunctionExpression */:
68455                 case 202 /* ArrowFunction */:
68456                 case 156 /* Parameter */:
68457                     return false;
68458                 default:
68459                     if (node.parent.kind === 250 /* ModuleBlock */ || node.parent.kind === 290 /* SourceFile */) {
68460                         return false;
68461                     }
68462                     switch (node.kind) {
68463                         case 244 /* FunctionDeclaration */:
68464                             return nodeHasAnyModifiersExcept(node, 126 /* AsyncKeyword */);
68465                         case 245 /* ClassDeclaration */:
68466                             return nodeHasAnyModifiersExcept(node, 122 /* AbstractKeyword */);
68467                         case 246 /* InterfaceDeclaration */:
68468                         case 225 /* VariableStatement */:
68469                         case 247 /* TypeAliasDeclaration */:
68470                             return true;
68471                         case 248 /* EnumDeclaration */:
68472                             return nodeHasAnyModifiersExcept(node, 81 /* ConstKeyword */);
68473                         default:
68474                             ts.Debug.fail();
68475                             return false;
68476                     }
68477             }
68478         }
68479         function nodeHasAnyModifiersExcept(node, allowedModifier) {
68480             return node.modifiers.length > 1 || node.modifiers[0].kind !== allowedModifier;
68481         }
68482         function checkGrammarAsyncModifier(node, asyncModifier) {
68483             switch (node.kind) {
68484                 case 161 /* MethodDeclaration */:
68485                 case 244 /* FunctionDeclaration */:
68486                 case 201 /* FunctionExpression */:
68487                 case 202 /* ArrowFunction */:
68488                     return false;
68489             }
68490             return grammarErrorOnNode(asyncModifier, ts.Diagnostics._0_modifier_cannot_be_used_here, "async");
68491         }
68492         function checkGrammarForDisallowedTrailingComma(list, diag) {
68493             if (diag === void 0) { diag = ts.Diagnostics.Trailing_comma_not_allowed; }
68494             if (list && list.hasTrailingComma) {
68495                 return grammarErrorAtPos(list[0], list.end - ",".length, ",".length, diag);
68496             }
68497             return false;
68498         }
68499         function checkGrammarTypeParameterList(typeParameters, file) {
68500             if (typeParameters && typeParameters.length === 0) {
68501                 var start = typeParameters.pos - "<".length;
68502                 var end = ts.skipTrivia(file.text, typeParameters.end) + ">".length;
68503                 return grammarErrorAtPos(file, start, end - start, ts.Diagnostics.Type_parameter_list_cannot_be_empty);
68504             }
68505             return false;
68506         }
68507         function checkGrammarParameterList(parameters) {
68508             var seenOptionalParameter = false;
68509             var parameterCount = parameters.length;
68510             for (var i = 0; i < parameterCount; i++) {
68511                 var parameter = parameters[i];
68512                 if (parameter.dotDotDotToken) {
68513                     if (i !== (parameterCount - 1)) {
68514                         return grammarErrorOnNode(parameter.dotDotDotToken, ts.Diagnostics.A_rest_parameter_must_be_last_in_a_parameter_list);
68515                     }
68516                     if (!(parameter.flags & 8388608 /* Ambient */)) { // Allow `...foo,` in ambient declarations; see GH#23070
68517                         checkGrammarForDisallowedTrailingComma(parameters, ts.Diagnostics.A_rest_parameter_or_binding_pattern_may_not_have_a_trailing_comma);
68518                     }
68519                     if (parameter.questionToken) {
68520                         return grammarErrorOnNode(parameter.questionToken, ts.Diagnostics.A_rest_parameter_cannot_be_optional);
68521                     }
68522                     if (parameter.initializer) {
68523                         return grammarErrorOnNode(parameter.name, ts.Diagnostics.A_rest_parameter_cannot_have_an_initializer);
68524                     }
68525                 }
68526                 else if (parameter.questionToken) {
68527                     seenOptionalParameter = true;
68528                     if (parameter.initializer) {
68529                         return grammarErrorOnNode(parameter.name, ts.Diagnostics.Parameter_cannot_have_question_mark_and_initializer);
68530                     }
68531                 }
68532                 else if (seenOptionalParameter && !parameter.initializer) {
68533                     return grammarErrorOnNode(parameter.name, ts.Diagnostics.A_required_parameter_cannot_follow_an_optional_parameter);
68534                 }
68535             }
68536         }
68537         function getNonSimpleParameters(parameters) {
68538             return ts.filter(parameters, function (parameter) { return !!parameter.initializer || ts.isBindingPattern(parameter.name) || ts.isRestParameter(parameter); });
68539         }
68540         function checkGrammarForUseStrictSimpleParameterList(node) {
68541             if (languageVersion >= 3 /* ES2016 */) {
68542                 var useStrictDirective_1 = node.body && ts.isBlock(node.body) && ts.findUseStrictPrologue(node.body.statements);
68543                 if (useStrictDirective_1) {
68544                     var nonSimpleParameters = getNonSimpleParameters(node.parameters);
68545                     if (ts.length(nonSimpleParameters)) {
68546                         ts.forEach(nonSimpleParameters, function (parameter) {
68547                             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));
68548                         });
68549                         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)); });
68550                         ts.addRelatedInfo.apply(void 0, __spreadArrays([error(useStrictDirective_1, ts.Diagnostics.use_strict_directive_cannot_be_used_with_non_simple_parameter_list)], diagnostics_1));
68551                         return true;
68552                     }
68553                 }
68554             }
68555             return false;
68556         }
68557         function checkGrammarFunctionLikeDeclaration(node) {
68558             // Prevent cascading error by short-circuit
68559             var file = ts.getSourceFileOfNode(node);
68560             return checkGrammarDecoratorsAndModifiers(node) || checkGrammarTypeParameterList(node.typeParameters, file) ||
68561                 checkGrammarParameterList(node.parameters) || checkGrammarArrowFunction(node, file) ||
68562                 (ts.isFunctionLikeDeclaration(node) && checkGrammarForUseStrictSimpleParameterList(node));
68563         }
68564         function checkGrammarClassLikeDeclaration(node) {
68565             var file = ts.getSourceFileOfNode(node);
68566             return checkGrammarClassDeclarationHeritageClauses(node) || checkGrammarTypeParameterList(node.typeParameters, file);
68567         }
68568         function checkGrammarArrowFunction(node, file) {
68569             if (!ts.isArrowFunction(node)) {
68570                 return false;
68571             }
68572             var equalsGreaterThanToken = node.equalsGreaterThanToken;
68573             var startLine = ts.getLineAndCharacterOfPosition(file, equalsGreaterThanToken.pos).line;
68574             var endLine = ts.getLineAndCharacterOfPosition(file, equalsGreaterThanToken.end).line;
68575             return startLine !== endLine && grammarErrorOnNode(equalsGreaterThanToken, ts.Diagnostics.Line_terminator_not_permitted_before_arrow);
68576         }
68577         function checkGrammarIndexSignatureParameters(node) {
68578             var parameter = node.parameters[0];
68579             if (node.parameters.length !== 1) {
68580                 if (parameter) {
68581                     return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_must_have_exactly_one_parameter);
68582                 }
68583                 else {
68584                     return grammarErrorOnNode(node, ts.Diagnostics.An_index_signature_must_have_exactly_one_parameter);
68585                 }
68586             }
68587             checkGrammarForDisallowedTrailingComma(node.parameters, ts.Diagnostics.An_index_signature_cannot_have_a_trailing_comma);
68588             if (parameter.dotDotDotToken) {
68589                 return grammarErrorOnNode(parameter.dotDotDotToken, ts.Diagnostics.An_index_signature_cannot_have_a_rest_parameter);
68590             }
68591             if (ts.hasModifiers(parameter)) {
68592                 return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_parameter_cannot_have_an_accessibility_modifier);
68593             }
68594             if (parameter.questionToken) {
68595                 return grammarErrorOnNode(parameter.questionToken, ts.Diagnostics.An_index_signature_parameter_cannot_have_a_question_mark);
68596             }
68597             if (parameter.initializer) {
68598                 return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_parameter_cannot_have_an_initializer);
68599             }
68600             if (!parameter.type) {
68601                 return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_parameter_must_have_a_type_annotation);
68602             }
68603             if (parameter.type.kind !== 143 /* StringKeyword */ && parameter.type.kind !== 140 /* NumberKeyword */) {
68604                 var type = getTypeFromTypeNode(parameter.type);
68605                 if (type.flags & 4 /* String */ || type.flags & 8 /* Number */) {
68606                     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));
68607                 }
68608                 if (type.flags & 1048576 /* Union */ && allTypesAssignableToKind(type, 384 /* StringOrNumberLiteral */, /*strict*/ true)) {
68609                     return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_parameter_type_cannot_be_a_union_type_Consider_using_a_mapped_object_type_instead);
68610                 }
68611                 return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_parameter_type_must_be_either_string_or_number);
68612             }
68613             if (!node.type) {
68614                 return grammarErrorOnNode(node, ts.Diagnostics.An_index_signature_must_have_a_type_annotation);
68615             }
68616             return false;
68617         }
68618         function checkGrammarIndexSignature(node) {
68619             // Prevent cascading error by short-circuit
68620             return checkGrammarDecoratorsAndModifiers(node) || checkGrammarIndexSignatureParameters(node);
68621         }
68622         function checkGrammarForAtLeastOneTypeArgument(node, typeArguments) {
68623             if (typeArguments && typeArguments.length === 0) {
68624                 var sourceFile = ts.getSourceFileOfNode(node);
68625                 var start = typeArguments.pos - "<".length;
68626                 var end = ts.skipTrivia(sourceFile.text, typeArguments.end) + ">".length;
68627                 return grammarErrorAtPos(sourceFile, start, end - start, ts.Diagnostics.Type_argument_list_cannot_be_empty);
68628             }
68629             return false;
68630         }
68631         function checkGrammarTypeArguments(node, typeArguments) {
68632             return checkGrammarForDisallowedTrailingComma(typeArguments) ||
68633                 checkGrammarForAtLeastOneTypeArgument(node, typeArguments);
68634         }
68635         function checkGrammarTaggedTemplateChain(node) {
68636             if (node.questionDotToken || node.flags & 32 /* OptionalChain */) {
68637                 return grammarErrorOnNode(node.template, ts.Diagnostics.Tagged_template_expressions_are_not_permitted_in_an_optional_chain);
68638             }
68639             return false;
68640         }
68641         function checkGrammarForOmittedArgument(args) {
68642             if (args) {
68643                 for (var _i = 0, args_4 = args; _i < args_4.length; _i++) {
68644                     var arg = args_4[_i];
68645                     if (arg.kind === 215 /* OmittedExpression */) {
68646                         return grammarErrorAtPos(arg, arg.pos, 0, ts.Diagnostics.Argument_expression_expected);
68647                     }
68648                 }
68649             }
68650             return false;
68651         }
68652         function checkGrammarArguments(args) {
68653             return checkGrammarForOmittedArgument(args);
68654         }
68655         function checkGrammarHeritageClause(node) {
68656             var types = node.types;
68657             if (checkGrammarForDisallowedTrailingComma(types)) {
68658                 return true;
68659             }
68660             if (types && types.length === 0) {
68661                 var listType = ts.tokenToString(node.token);
68662                 return grammarErrorAtPos(node, types.pos, 0, ts.Diagnostics._0_list_cannot_be_empty, listType);
68663             }
68664             return ts.some(types, checkGrammarExpressionWithTypeArguments);
68665         }
68666         function checkGrammarExpressionWithTypeArguments(node) {
68667             return checkGrammarTypeArguments(node, node.typeArguments);
68668         }
68669         function checkGrammarClassDeclarationHeritageClauses(node) {
68670             var seenExtendsClause = false;
68671             var seenImplementsClause = false;
68672             if (!checkGrammarDecoratorsAndModifiers(node) && node.heritageClauses) {
68673                 for (var _i = 0, _a = node.heritageClauses; _i < _a.length; _i++) {
68674                     var heritageClause = _a[_i];
68675                     if (heritageClause.token === 90 /* ExtendsKeyword */) {
68676                         if (seenExtendsClause) {
68677                             return grammarErrorOnFirstToken(heritageClause, ts.Diagnostics.extends_clause_already_seen);
68678                         }
68679                         if (seenImplementsClause) {
68680                             return grammarErrorOnFirstToken(heritageClause, ts.Diagnostics.extends_clause_must_precede_implements_clause);
68681                         }
68682                         if (heritageClause.types.length > 1) {
68683                             return grammarErrorOnFirstToken(heritageClause.types[1], ts.Diagnostics.Classes_can_only_extend_a_single_class);
68684                         }
68685                         seenExtendsClause = true;
68686                     }
68687                     else {
68688                         ts.Debug.assert(heritageClause.token === 113 /* ImplementsKeyword */);
68689                         if (seenImplementsClause) {
68690                             return grammarErrorOnFirstToken(heritageClause, ts.Diagnostics.implements_clause_already_seen);
68691                         }
68692                         seenImplementsClause = true;
68693                     }
68694                     // Grammar checking heritageClause inside class declaration
68695                     checkGrammarHeritageClause(heritageClause);
68696                 }
68697             }
68698         }
68699         function checkGrammarInterfaceDeclaration(node) {
68700             var seenExtendsClause = false;
68701             if (node.heritageClauses) {
68702                 for (var _i = 0, _a = node.heritageClauses; _i < _a.length; _i++) {
68703                     var heritageClause = _a[_i];
68704                     if (heritageClause.token === 90 /* ExtendsKeyword */) {
68705                         if (seenExtendsClause) {
68706                             return grammarErrorOnFirstToken(heritageClause, ts.Diagnostics.extends_clause_already_seen);
68707                         }
68708                         seenExtendsClause = true;
68709                     }
68710                     else {
68711                         ts.Debug.assert(heritageClause.token === 113 /* ImplementsKeyword */);
68712                         return grammarErrorOnFirstToken(heritageClause, ts.Diagnostics.Interface_declaration_cannot_have_implements_clause);
68713                     }
68714                     // Grammar checking heritageClause inside class declaration
68715                     checkGrammarHeritageClause(heritageClause);
68716                 }
68717             }
68718             return false;
68719         }
68720         function checkGrammarComputedPropertyName(node) {
68721             // If node is not a computedPropertyName, just skip the grammar checking
68722             if (node.kind !== 154 /* ComputedPropertyName */) {
68723                 return false;
68724             }
68725             var computedPropertyName = node;
68726             if (computedPropertyName.expression.kind === 209 /* BinaryExpression */ && computedPropertyName.expression.operatorToken.kind === 27 /* CommaToken */) {
68727                 return grammarErrorOnNode(computedPropertyName.expression, ts.Diagnostics.A_comma_expression_is_not_allowed_in_a_computed_property_name);
68728             }
68729             return false;
68730         }
68731         function checkGrammarForGenerator(node) {
68732             if (node.asteriskToken) {
68733                 ts.Debug.assert(node.kind === 244 /* FunctionDeclaration */ ||
68734                     node.kind === 201 /* FunctionExpression */ ||
68735                     node.kind === 161 /* MethodDeclaration */);
68736                 if (node.flags & 8388608 /* Ambient */) {
68737                     return grammarErrorOnNode(node.asteriskToken, ts.Diagnostics.Generators_are_not_allowed_in_an_ambient_context);
68738                 }
68739                 if (!node.body) {
68740                     return grammarErrorOnNode(node.asteriskToken, ts.Diagnostics.An_overload_signature_cannot_be_declared_as_a_generator);
68741                 }
68742             }
68743         }
68744         function checkGrammarForInvalidQuestionMark(questionToken, message) {
68745             return !!questionToken && grammarErrorOnNode(questionToken, message);
68746         }
68747         function checkGrammarForInvalidExclamationToken(exclamationToken, message) {
68748             return !!exclamationToken && grammarErrorOnNode(exclamationToken, message);
68749         }
68750         function checkGrammarObjectLiteralExpression(node, inDestructuring) {
68751             var seen = ts.createUnderscoreEscapedMap();
68752             for (var _i = 0, _a = node.properties; _i < _a.length; _i++) {
68753                 var prop = _a[_i];
68754                 if (prop.kind === 283 /* SpreadAssignment */) {
68755                     if (inDestructuring) {
68756                         // a rest property cannot be destructured any further
68757                         var expression = ts.skipParentheses(prop.expression);
68758                         if (ts.isArrayLiteralExpression(expression) || ts.isObjectLiteralExpression(expression)) {
68759                             return grammarErrorOnNode(prop.expression, ts.Diagnostics.A_rest_element_cannot_contain_a_binding_pattern);
68760                         }
68761                     }
68762                     continue;
68763                 }
68764                 var name = prop.name;
68765                 if (name.kind === 154 /* ComputedPropertyName */) {
68766                     // If the name is not a ComputedPropertyName, the grammar checking will skip it
68767                     checkGrammarComputedPropertyName(name);
68768                 }
68769                 if (prop.kind === 282 /* ShorthandPropertyAssignment */ && !inDestructuring && prop.objectAssignmentInitializer) {
68770                     // having objectAssignmentInitializer is only valid in ObjectAssignmentPattern
68771                     // outside of destructuring it is a syntax error
68772                     return grammarErrorOnNode(prop.equalsToken, ts.Diagnostics.can_only_be_used_in_an_object_literal_property_inside_a_destructuring_assignment);
68773                 }
68774                 if (name.kind === 76 /* PrivateIdentifier */) {
68775                     return grammarErrorOnNode(name, ts.Diagnostics.Private_identifiers_are_not_allowed_outside_class_bodies);
68776                 }
68777                 // Modifiers are never allowed on properties except for 'async' on a method declaration
68778                 if (prop.modifiers) {
68779                     // eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion
68780                     for (var _b = 0, _c = prop.modifiers; _b < _c.length; _b++) { // TODO: GH#19955
68781                         var mod = _c[_b];
68782                         if (mod.kind !== 126 /* AsyncKeyword */ || prop.kind !== 161 /* MethodDeclaration */) {
68783                             grammarErrorOnNode(mod, ts.Diagnostics._0_modifier_cannot_be_used_here, ts.getTextOfNode(mod));
68784                         }
68785                     }
68786                 }
68787                 // ECMA-262 11.1.5 Object Initializer
68788                 // If previous is not undefined then throw a SyntaxError exception if any of the following conditions are true
68789                 // a.This production is contained in strict code and IsDataDescriptor(previous) is true and
68790                 // IsDataDescriptor(propId.descriptor) is true.
68791                 //    b.IsDataDescriptor(previous) is true and IsAccessorDescriptor(propId.descriptor) is true.
68792                 //    c.IsAccessorDescriptor(previous) is true and IsDataDescriptor(propId.descriptor) is true.
68793                 //    d.IsAccessorDescriptor(previous) is true and IsAccessorDescriptor(propId.descriptor) is true
68794                 // and either both previous and propId.descriptor have[[Get]] fields or both previous and propId.descriptor have[[Set]] fields
68795                 var currentKind = void 0;
68796                 switch (prop.kind) {
68797                     case 282 /* ShorthandPropertyAssignment */:
68798                         checkGrammarForInvalidExclamationToken(prop.exclamationToken, ts.Diagnostics.A_definite_assignment_assertion_is_not_permitted_in_this_context);
68799                     // falls through
68800                     case 281 /* PropertyAssignment */:
68801                         // Grammar checking for computedPropertyName and shorthandPropertyAssignment
68802                         checkGrammarForInvalidQuestionMark(prop.questionToken, ts.Diagnostics.An_object_member_cannot_be_declared_optional);
68803                         if (name.kind === 8 /* NumericLiteral */) {
68804                             checkGrammarNumericLiteral(name);
68805                         }
68806                         currentKind = 4 /* PropertyAssignment */;
68807                         break;
68808                     case 161 /* MethodDeclaration */:
68809                         currentKind = 8 /* Method */;
68810                         break;
68811                     case 163 /* GetAccessor */:
68812                         currentKind = 1 /* GetAccessor */;
68813                         break;
68814                     case 164 /* SetAccessor */:
68815                         currentKind = 2 /* SetAccessor */;
68816                         break;
68817                     default:
68818                         throw ts.Debug.assertNever(prop, "Unexpected syntax kind:" + prop.kind);
68819                 }
68820                 if (!inDestructuring) {
68821                     var effectiveName = ts.getPropertyNameForPropertyNameNode(name);
68822                     if (effectiveName === undefined) {
68823                         continue;
68824                     }
68825                     var existingKind = seen.get(effectiveName);
68826                     if (!existingKind) {
68827                         seen.set(effectiveName, currentKind);
68828                     }
68829                     else {
68830                         if ((currentKind & 12 /* PropertyAssignmentOrMethod */) && (existingKind & 12 /* PropertyAssignmentOrMethod */)) {
68831                             grammarErrorOnNode(name, ts.Diagnostics.Duplicate_identifier_0, ts.getTextOfNode(name));
68832                         }
68833                         else if ((currentKind & 3 /* GetOrSetAccessor */) && (existingKind & 3 /* GetOrSetAccessor */)) {
68834                             if (existingKind !== 3 /* GetOrSetAccessor */ && currentKind !== existingKind) {
68835                                 seen.set(effectiveName, currentKind | existingKind);
68836                             }
68837                             else {
68838                                 return grammarErrorOnNode(name, ts.Diagnostics.An_object_literal_cannot_have_multiple_get_Slashset_accessors_with_the_same_name);
68839                             }
68840                         }
68841                         else {
68842                             return grammarErrorOnNode(name, ts.Diagnostics.An_object_literal_cannot_have_property_and_accessor_with_the_same_name);
68843                         }
68844                     }
68845                 }
68846             }
68847         }
68848         function checkGrammarJsxElement(node) {
68849             checkGrammarTypeArguments(node, node.typeArguments);
68850             var seen = ts.createUnderscoreEscapedMap();
68851             for (var _i = 0, _a = node.attributes.properties; _i < _a.length; _i++) {
68852                 var attr = _a[_i];
68853                 if (attr.kind === 275 /* JsxSpreadAttribute */) {
68854                     continue;
68855                 }
68856                 var name = attr.name, initializer = attr.initializer;
68857                 if (!seen.get(name.escapedText)) {
68858                     seen.set(name.escapedText, true);
68859                 }
68860                 else {
68861                     return grammarErrorOnNode(name, ts.Diagnostics.JSX_elements_cannot_have_multiple_attributes_with_the_same_name);
68862                 }
68863                 if (initializer && initializer.kind === 276 /* JsxExpression */ && !initializer.expression) {
68864                     return grammarErrorOnNode(initializer, ts.Diagnostics.JSX_attributes_must_only_be_assigned_a_non_empty_expression);
68865                 }
68866             }
68867         }
68868         function checkGrammarJsxExpression(node) {
68869             if (node.expression && ts.isCommaSequence(node.expression)) {
68870                 return grammarErrorOnNode(node.expression, ts.Diagnostics.JSX_expressions_may_not_use_the_comma_operator_Did_you_mean_to_write_an_array);
68871             }
68872         }
68873         function checkGrammarForInOrForOfStatement(forInOrOfStatement) {
68874             if (checkGrammarStatementInAmbientContext(forInOrOfStatement)) {
68875                 return true;
68876             }
68877             if (forInOrOfStatement.kind === 232 /* ForOfStatement */ && forInOrOfStatement.awaitModifier) {
68878                 if ((forInOrOfStatement.flags & 32768 /* AwaitContext */) === 0 /* None */) {
68879                     // use of 'for-await-of' in non-async function
68880                     var sourceFile = ts.getSourceFileOfNode(forInOrOfStatement);
68881                     if (!hasParseDiagnostics(sourceFile)) {
68882                         var diagnostic = ts.createDiagnosticForNode(forInOrOfStatement.awaitModifier, ts.Diagnostics.A_for_await_of_statement_is_only_allowed_within_an_async_function_or_async_generator);
68883                         var func = ts.getContainingFunction(forInOrOfStatement);
68884                         if (func && func.kind !== 162 /* Constructor */) {
68885                             ts.Debug.assert((ts.getFunctionFlags(func) & 2 /* Async */) === 0, "Enclosing function should never be an async function.");
68886                             var relatedInfo = ts.createDiagnosticForNode(func, ts.Diagnostics.Did_you_mean_to_mark_this_function_as_async);
68887                             ts.addRelatedInfo(diagnostic, relatedInfo);
68888                         }
68889                         diagnostics.add(diagnostic);
68890                         return true;
68891                     }
68892                     return false;
68893                 }
68894             }
68895             if (forInOrOfStatement.initializer.kind === 243 /* VariableDeclarationList */) {
68896                 var variableList = forInOrOfStatement.initializer;
68897                 if (!checkGrammarVariableDeclarationList(variableList)) {
68898                     var declarations = variableList.declarations;
68899                     // declarations.length can be zero if there is an error in variable declaration in for-of or for-in
68900                     // See http://www.ecma-international.org/ecma-262/6.0/#sec-for-in-and-for-of-statements for details
68901                     // For example:
68902                     //      var let = 10;
68903                     //      for (let of [1,2,3]) {} // this is invalid ES6 syntax
68904                     //      for (let in [1,2,3]) {} // this is invalid ES6 syntax
68905                     // We will then want to skip on grammar checking on variableList declaration
68906                     if (!declarations.length) {
68907                         return false;
68908                     }
68909                     if (declarations.length > 1) {
68910                         var diagnostic = forInOrOfStatement.kind === 231 /* ForInStatement */
68911                             ? ts.Diagnostics.Only_a_single_variable_declaration_is_allowed_in_a_for_in_statement
68912                             : ts.Diagnostics.Only_a_single_variable_declaration_is_allowed_in_a_for_of_statement;
68913                         return grammarErrorOnFirstToken(variableList.declarations[1], diagnostic);
68914                     }
68915                     var firstDeclaration = declarations[0];
68916                     if (firstDeclaration.initializer) {
68917                         var diagnostic = forInOrOfStatement.kind === 231 /* ForInStatement */
68918                             ? ts.Diagnostics.The_variable_declaration_of_a_for_in_statement_cannot_have_an_initializer
68919                             : ts.Diagnostics.The_variable_declaration_of_a_for_of_statement_cannot_have_an_initializer;
68920                         return grammarErrorOnNode(firstDeclaration.name, diagnostic);
68921                     }
68922                     if (firstDeclaration.type) {
68923                         var diagnostic = forInOrOfStatement.kind === 231 /* ForInStatement */
68924                             ? ts.Diagnostics.The_left_hand_side_of_a_for_in_statement_cannot_use_a_type_annotation
68925                             : ts.Diagnostics.The_left_hand_side_of_a_for_of_statement_cannot_use_a_type_annotation;
68926                         return grammarErrorOnNode(firstDeclaration, diagnostic);
68927                     }
68928                 }
68929             }
68930             return false;
68931         }
68932         function checkGrammarAccessor(accessor) {
68933             if (!(accessor.flags & 8388608 /* Ambient */)) {
68934                 if (languageVersion < 1 /* ES5 */) {
68935                     return grammarErrorOnNode(accessor.name, ts.Diagnostics.Accessors_are_only_available_when_targeting_ECMAScript_5_and_higher);
68936                 }
68937                 if (accessor.body === undefined && !ts.hasModifier(accessor, 128 /* Abstract */)) {
68938                     return grammarErrorAtPos(accessor, accessor.end - 1, ";".length, ts.Diagnostics._0_expected, "{");
68939                 }
68940             }
68941             if (accessor.body && ts.hasModifier(accessor, 128 /* Abstract */)) {
68942                 return grammarErrorOnNode(accessor, ts.Diagnostics.An_abstract_accessor_cannot_have_an_implementation);
68943             }
68944             if (accessor.typeParameters) {
68945                 return grammarErrorOnNode(accessor.name, ts.Diagnostics.An_accessor_cannot_have_type_parameters);
68946             }
68947             if (!doesAccessorHaveCorrectParameterCount(accessor)) {
68948                 return grammarErrorOnNode(accessor.name, accessor.kind === 163 /* GetAccessor */ ?
68949                     ts.Diagnostics.A_get_accessor_cannot_have_parameters :
68950                     ts.Diagnostics.A_set_accessor_must_have_exactly_one_parameter);
68951             }
68952             if (accessor.kind === 164 /* SetAccessor */) {
68953                 if (accessor.type) {
68954                     return grammarErrorOnNode(accessor.name, ts.Diagnostics.A_set_accessor_cannot_have_a_return_type_annotation);
68955                 }
68956                 var parameter = ts.Debug.checkDefined(ts.getSetAccessorValueParameter(accessor), "Return value does not match parameter count assertion.");
68957                 if (parameter.dotDotDotToken) {
68958                     return grammarErrorOnNode(parameter.dotDotDotToken, ts.Diagnostics.A_set_accessor_cannot_have_rest_parameter);
68959                 }
68960                 if (parameter.questionToken) {
68961                     return grammarErrorOnNode(parameter.questionToken, ts.Diagnostics.A_set_accessor_cannot_have_an_optional_parameter);
68962                 }
68963                 if (parameter.initializer) {
68964                     return grammarErrorOnNode(accessor.name, ts.Diagnostics.A_set_accessor_parameter_cannot_have_an_initializer);
68965                 }
68966             }
68967             return false;
68968         }
68969         /** Does the accessor have the right number of parameters?
68970          * A get accessor has no parameters or a single `this` parameter.
68971          * A set accessor has one parameter or a `this` parameter and one more parameter.
68972          */
68973         function doesAccessorHaveCorrectParameterCount(accessor) {
68974             return getAccessorThisParameter(accessor) || accessor.parameters.length === (accessor.kind === 163 /* GetAccessor */ ? 0 : 1);
68975         }
68976         function getAccessorThisParameter(accessor) {
68977             if (accessor.parameters.length === (accessor.kind === 163 /* GetAccessor */ ? 1 : 2)) {
68978                 return ts.getThisParameter(accessor);
68979             }
68980         }
68981         function checkGrammarTypeOperatorNode(node) {
68982             if (node.operator === 147 /* UniqueKeyword */) {
68983                 if (node.type.kind !== 144 /* SymbolKeyword */) {
68984                     return grammarErrorOnNode(node.type, ts.Diagnostics._0_expected, ts.tokenToString(144 /* SymbolKeyword */));
68985                 }
68986                 var parent = ts.walkUpParenthesizedTypes(node.parent);
68987                 switch (parent.kind) {
68988                     case 242 /* VariableDeclaration */:
68989                         var decl = parent;
68990                         if (decl.name.kind !== 75 /* Identifier */) {
68991                             return grammarErrorOnNode(node, ts.Diagnostics.unique_symbol_types_may_not_be_used_on_a_variable_declaration_with_a_binding_name);
68992                         }
68993                         if (!ts.isVariableDeclarationInVariableStatement(decl)) {
68994                             return grammarErrorOnNode(node, ts.Diagnostics.unique_symbol_types_are_only_allowed_on_variables_in_a_variable_statement);
68995                         }
68996                         if (!(decl.parent.flags & 2 /* Const */)) {
68997                             return grammarErrorOnNode(parent.name, ts.Diagnostics.A_variable_whose_type_is_a_unique_symbol_type_must_be_const);
68998                         }
68999                         break;
69000                     case 159 /* PropertyDeclaration */:
69001                         if (!ts.hasModifier(parent, 32 /* Static */) ||
69002                             !ts.hasModifier(parent, 64 /* Readonly */)) {
69003                             return grammarErrorOnNode(parent.name, ts.Diagnostics.A_property_of_a_class_whose_type_is_a_unique_symbol_type_must_be_both_static_and_readonly);
69004                         }
69005                         break;
69006                     case 158 /* PropertySignature */:
69007                         if (!ts.hasModifier(parent, 64 /* Readonly */)) {
69008                             return grammarErrorOnNode(parent.name, ts.Diagnostics.A_property_of_an_interface_or_type_literal_whose_type_is_a_unique_symbol_type_must_be_readonly);
69009                         }
69010                         break;
69011                     default:
69012                         return grammarErrorOnNode(node, ts.Diagnostics.unique_symbol_types_are_not_allowed_here);
69013                 }
69014             }
69015             else if (node.operator === 138 /* ReadonlyKeyword */) {
69016                 if (node.type.kind !== 174 /* ArrayType */ && node.type.kind !== 175 /* TupleType */) {
69017                     return grammarErrorOnFirstToken(node, ts.Diagnostics.readonly_type_modifier_is_only_permitted_on_array_and_tuple_literal_types, ts.tokenToString(144 /* SymbolKeyword */));
69018                 }
69019             }
69020         }
69021         function checkGrammarForInvalidDynamicName(node, message) {
69022             if (isNonBindableDynamicName(node)) {
69023                 return grammarErrorOnNode(node, message);
69024             }
69025         }
69026         function checkGrammarMethod(node) {
69027             if (checkGrammarFunctionLikeDeclaration(node)) {
69028                 return true;
69029             }
69030             if (node.kind === 161 /* MethodDeclaration */) {
69031                 if (node.parent.kind === 193 /* ObjectLiteralExpression */) {
69032                     // We only disallow modifier on a method declaration if it is a property of object-literal-expression
69033                     if (node.modifiers && !(node.modifiers.length === 1 && ts.first(node.modifiers).kind === 126 /* AsyncKeyword */)) {
69034                         return grammarErrorOnFirstToken(node, ts.Diagnostics.Modifiers_cannot_appear_here);
69035                     }
69036                     else if (checkGrammarForInvalidQuestionMark(node.questionToken, ts.Diagnostics.An_object_member_cannot_be_declared_optional)) {
69037                         return true;
69038                     }
69039                     else if (checkGrammarForInvalidExclamationToken(node.exclamationToken, ts.Diagnostics.A_definite_assignment_assertion_is_not_permitted_in_this_context)) {
69040                         return true;
69041                     }
69042                     else if (node.body === undefined) {
69043                         return grammarErrorAtPos(node, node.end - 1, ";".length, ts.Diagnostics._0_expected, "{");
69044                     }
69045                 }
69046                 if (checkGrammarForGenerator(node)) {
69047                     return true;
69048                 }
69049             }
69050             if (ts.isClassLike(node.parent)) {
69051                 // Technically, computed properties in ambient contexts is disallowed
69052                 // for property declarations and accessors too, not just methods.
69053                 // However, property declarations disallow computed names in general,
69054                 // and accessors are not allowed in ambient contexts in general,
69055                 // so this error only really matters for methods.
69056                 if (node.flags & 8388608 /* Ambient */) {
69057                     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);
69058                 }
69059                 else if (node.kind === 161 /* MethodDeclaration */ && !node.body) {
69060                     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);
69061                 }
69062             }
69063             else if (node.parent.kind === 246 /* InterfaceDeclaration */) {
69064                 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);
69065             }
69066             else if (node.parent.kind === 173 /* TypeLiteral */) {
69067                 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);
69068             }
69069         }
69070         function checkGrammarBreakOrContinueStatement(node) {
69071             var current = node;
69072             while (current) {
69073                 if (ts.isFunctionLike(current)) {
69074                     return grammarErrorOnNode(node, ts.Diagnostics.Jump_target_cannot_cross_function_boundary);
69075                 }
69076                 switch (current.kind) {
69077                     case 238 /* LabeledStatement */:
69078                         if (node.label && current.label.escapedText === node.label.escapedText) {
69079                             // found matching label - verify that label usage is correct
69080                             // continue can only target labels that are on iteration statements
69081                             var isMisplacedContinueLabel = node.kind === 233 /* ContinueStatement */
69082                                 && !ts.isIterationStatement(current.statement, /*lookInLabeledStatement*/ true);
69083                             if (isMisplacedContinueLabel) {
69084                                 return grammarErrorOnNode(node, ts.Diagnostics.A_continue_statement_can_only_jump_to_a_label_of_an_enclosing_iteration_statement);
69085                             }
69086                             return false;
69087                         }
69088                         break;
69089                     case 237 /* SwitchStatement */:
69090                         if (node.kind === 234 /* BreakStatement */ && !node.label) {
69091                             // unlabeled break within switch statement - ok
69092                             return false;
69093                         }
69094                         break;
69095                     default:
69096                         if (ts.isIterationStatement(current, /*lookInLabeledStatement*/ false) && !node.label) {
69097                             // unlabeled break or continue within iteration statement - ok
69098                             return false;
69099                         }
69100                         break;
69101                 }
69102                 current = current.parent;
69103             }
69104             if (node.label) {
69105                 var message = node.kind === 234 /* BreakStatement */
69106                     ? ts.Diagnostics.A_break_statement_can_only_jump_to_a_label_of_an_enclosing_statement
69107                     : ts.Diagnostics.A_continue_statement_can_only_jump_to_a_label_of_an_enclosing_iteration_statement;
69108                 return grammarErrorOnNode(node, message);
69109             }
69110             else {
69111                 var message = node.kind === 234 /* BreakStatement */
69112                     ? ts.Diagnostics.A_break_statement_can_only_be_used_within_an_enclosing_iteration_or_switch_statement
69113                     : ts.Diagnostics.A_continue_statement_can_only_be_used_within_an_enclosing_iteration_statement;
69114                 return grammarErrorOnNode(node, message);
69115             }
69116         }
69117         function checkGrammarBindingElement(node) {
69118             if (node.dotDotDotToken) {
69119                 var elements = node.parent.elements;
69120                 if (node !== ts.last(elements)) {
69121                     return grammarErrorOnNode(node, ts.Diagnostics.A_rest_element_must_be_last_in_a_destructuring_pattern);
69122                 }
69123                 checkGrammarForDisallowedTrailingComma(elements, ts.Diagnostics.A_rest_parameter_or_binding_pattern_may_not_have_a_trailing_comma);
69124                 if (node.propertyName) {
69125                     return grammarErrorOnNode(node.name, ts.Diagnostics.A_rest_element_cannot_have_a_property_name);
69126                 }
69127                 if (node.initializer) {
69128                     // Error on equals token which immediately precedes the initializer
69129                     return grammarErrorAtPos(node, node.initializer.pos - 1, 1, ts.Diagnostics.A_rest_element_cannot_have_an_initializer);
69130                 }
69131             }
69132         }
69133         function isStringOrNumberLiteralExpression(expr) {
69134             return ts.isStringOrNumericLiteralLike(expr) ||
69135                 expr.kind === 207 /* PrefixUnaryExpression */ && expr.operator === 40 /* MinusToken */ &&
69136                     expr.operand.kind === 8 /* NumericLiteral */;
69137         }
69138         function isBigIntLiteralExpression(expr) {
69139             return expr.kind === 9 /* BigIntLiteral */ ||
69140                 expr.kind === 207 /* PrefixUnaryExpression */ && expr.operator === 40 /* MinusToken */ &&
69141                     expr.operand.kind === 9 /* BigIntLiteral */;
69142         }
69143         function isSimpleLiteralEnumReference(expr) {
69144             if ((ts.isPropertyAccessExpression(expr) || (ts.isElementAccessExpression(expr) && isStringOrNumberLiteralExpression(expr.argumentExpression))) &&
69145                 ts.isEntityNameExpression(expr.expression)) {
69146                 return !!(checkExpressionCached(expr).flags & 1024 /* EnumLiteral */);
69147             }
69148         }
69149         function checkAmbientInitializer(node) {
69150             var initializer = node.initializer;
69151             if (initializer) {
69152                 var isInvalidInitializer = !(isStringOrNumberLiteralExpression(initializer) ||
69153                     isSimpleLiteralEnumReference(initializer) ||
69154                     initializer.kind === 106 /* TrueKeyword */ || initializer.kind === 91 /* FalseKeyword */ ||
69155                     isBigIntLiteralExpression(initializer));
69156                 var isConstOrReadonly = ts.isDeclarationReadonly(node) || ts.isVariableDeclaration(node) && ts.isVarConst(node);
69157                 if (isConstOrReadonly && !node.type) {
69158                     if (isInvalidInitializer) {
69159                         return grammarErrorOnNode(initializer, ts.Diagnostics.A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal_or_literal_enum_reference);
69160                     }
69161                 }
69162                 else {
69163                     return grammarErrorOnNode(initializer, ts.Diagnostics.Initializers_are_not_allowed_in_ambient_contexts);
69164                 }
69165                 if (!isConstOrReadonly || isInvalidInitializer) {
69166                     return grammarErrorOnNode(initializer, ts.Diagnostics.Initializers_are_not_allowed_in_ambient_contexts);
69167                 }
69168             }
69169         }
69170         function checkGrammarVariableDeclaration(node) {
69171             if (node.parent.parent.kind !== 231 /* ForInStatement */ && node.parent.parent.kind !== 232 /* ForOfStatement */) {
69172                 if (node.flags & 8388608 /* Ambient */) {
69173                     checkAmbientInitializer(node);
69174                 }
69175                 else if (!node.initializer) {
69176                     if (ts.isBindingPattern(node.name) && !ts.isBindingPattern(node.parent)) {
69177                         return grammarErrorOnNode(node, ts.Diagnostics.A_destructuring_declaration_must_have_an_initializer);
69178                     }
69179                     if (ts.isVarConst(node)) {
69180                         return grammarErrorOnNode(node, ts.Diagnostics.const_declarations_must_be_initialized);
69181                     }
69182                 }
69183             }
69184             if (node.exclamationToken && (node.parent.parent.kind !== 225 /* VariableStatement */ || !node.type || node.initializer || node.flags & 8388608 /* Ambient */)) {
69185                 return grammarErrorOnNode(node.exclamationToken, ts.Diagnostics.Definite_assignment_assertions_can_only_be_used_along_with_a_type_annotation);
69186             }
69187             var moduleKind = ts.getEmitModuleKind(compilerOptions);
69188             if (moduleKind < ts.ModuleKind.ES2015 && moduleKind !== ts.ModuleKind.System && !compilerOptions.noEmit &&
69189                 !(node.parent.parent.flags & 8388608 /* Ambient */) && ts.hasModifier(node.parent.parent, 1 /* Export */)) {
69190                 checkESModuleMarker(node.name);
69191             }
69192             var checkLetConstNames = (ts.isLet(node) || ts.isVarConst(node));
69193             // 1. LexicalDeclaration : LetOrConst BindingList ;
69194             // It is a Syntax Error if the BoundNames of BindingList contains "let".
69195             // 2. ForDeclaration: ForDeclaration : LetOrConst ForBinding
69196             // It is a Syntax Error if the BoundNames of ForDeclaration contains "let".
69197             // It is a SyntaxError if a VariableDeclaration or VariableDeclarationNoIn occurs within strict code
69198             // and its Identifier is eval or arguments
69199             return checkLetConstNames && checkGrammarNameInLetOrConstDeclarations(node.name);
69200         }
69201         function checkESModuleMarker(name) {
69202             if (name.kind === 75 /* Identifier */) {
69203                 if (ts.idText(name) === "__esModule") {
69204                     return grammarErrorOnNode(name, ts.Diagnostics.Identifier_expected_esModule_is_reserved_as_an_exported_marker_when_transforming_ECMAScript_modules);
69205                 }
69206             }
69207             else {
69208                 var elements = name.elements;
69209                 for (var _i = 0, elements_1 = elements; _i < elements_1.length; _i++) {
69210                     var element = elements_1[_i];
69211                     if (!ts.isOmittedExpression(element)) {
69212                         return checkESModuleMarker(element.name);
69213                     }
69214                 }
69215             }
69216             return false;
69217         }
69218         function checkGrammarNameInLetOrConstDeclarations(name) {
69219             if (name.kind === 75 /* Identifier */) {
69220                 if (name.originalKeywordKind === 115 /* LetKeyword */) {
69221                     return grammarErrorOnNode(name, ts.Diagnostics.let_is_not_allowed_to_be_used_as_a_name_in_let_or_const_declarations);
69222                 }
69223             }
69224             else {
69225                 var elements = name.elements;
69226                 for (var _i = 0, elements_2 = elements; _i < elements_2.length; _i++) {
69227                     var element = elements_2[_i];
69228                     if (!ts.isOmittedExpression(element)) {
69229                         checkGrammarNameInLetOrConstDeclarations(element.name);
69230                     }
69231                 }
69232             }
69233             return false;
69234         }
69235         function checkGrammarVariableDeclarationList(declarationList) {
69236             var declarations = declarationList.declarations;
69237             if (checkGrammarForDisallowedTrailingComma(declarationList.declarations)) {
69238                 return true;
69239             }
69240             if (!declarationList.declarations.length) {
69241                 return grammarErrorAtPos(declarationList, declarations.pos, declarations.end - declarations.pos, ts.Diagnostics.Variable_declaration_list_cannot_be_empty);
69242             }
69243             return false;
69244         }
69245         function allowLetAndConstDeclarations(parent) {
69246             switch (parent.kind) {
69247                 case 227 /* IfStatement */:
69248                 case 228 /* DoStatement */:
69249                 case 229 /* WhileStatement */:
69250                 case 236 /* WithStatement */:
69251                 case 230 /* ForStatement */:
69252                 case 231 /* ForInStatement */:
69253                 case 232 /* ForOfStatement */:
69254                     return false;
69255                 case 238 /* LabeledStatement */:
69256                     return allowLetAndConstDeclarations(parent.parent);
69257             }
69258             return true;
69259         }
69260         function checkGrammarForDisallowedLetOrConstStatement(node) {
69261             if (!allowLetAndConstDeclarations(node.parent)) {
69262                 if (ts.isLet(node.declarationList)) {
69263                     return grammarErrorOnNode(node, ts.Diagnostics.let_declarations_can_only_be_declared_inside_a_block);
69264                 }
69265                 else if (ts.isVarConst(node.declarationList)) {
69266                     return grammarErrorOnNode(node, ts.Diagnostics.const_declarations_can_only_be_declared_inside_a_block);
69267                 }
69268             }
69269         }
69270         function checkGrammarMetaProperty(node) {
69271             var escapedText = node.name.escapedText;
69272             switch (node.keywordToken) {
69273                 case 99 /* NewKeyword */:
69274                     if (escapedText !== "target") {
69275                         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");
69276                     }
69277                     break;
69278                 case 96 /* ImportKeyword */:
69279                     if (escapedText !== "meta") {
69280                         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");
69281                     }
69282                     break;
69283             }
69284         }
69285         function hasParseDiagnostics(sourceFile) {
69286             return sourceFile.parseDiagnostics.length > 0;
69287         }
69288         function grammarErrorOnFirstToken(node, message, arg0, arg1, arg2) {
69289             var sourceFile = ts.getSourceFileOfNode(node);
69290             if (!hasParseDiagnostics(sourceFile)) {
69291                 var span = ts.getSpanOfTokenAtPosition(sourceFile, node.pos);
69292                 diagnostics.add(ts.createFileDiagnostic(sourceFile, span.start, span.length, message, arg0, arg1, arg2));
69293                 return true;
69294             }
69295             return false;
69296         }
69297         function grammarErrorAtPos(nodeForSourceFile, start, length, message, arg0, arg1, arg2) {
69298             var sourceFile = ts.getSourceFileOfNode(nodeForSourceFile);
69299             if (!hasParseDiagnostics(sourceFile)) {
69300                 diagnostics.add(ts.createFileDiagnostic(sourceFile, start, length, message, arg0, arg1, arg2));
69301                 return true;
69302             }
69303             return false;
69304         }
69305         function grammarErrorOnNode(node, message, arg0, arg1, arg2) {
69306             var sourceFile = ts.getSourceFileOfNode(node);
69307             if (!hasParseDiagnostics(sourceFile)) {
69308                 diagnostics.add(ts.createDiagnosticForNode(node, message, arg0, arg1, arg2));
69309                 return true;
69310             }
69311             return false;
69312         }
69313         function checkGrammarConstructorTypeParameters(node) {
69314             var jsdocTypeParameters = ts.isInJSFile(node) ? ts.getJSDocTypeParameterDeclarations(node) : undefined;
69315             var range = node.typeParameters || jsdocTypeParameters && ts.firstOrUndefined(jsdocTypeParameters);
69316             if (range) {
69317                 var pos = range.pos === range.end ? range.pos : ts.skipTrivia(ts.getSourceFileOfNode(node).text, range.pos);
69318                 return grammarErrorAtPos(node, pos, range.end - pos, ts.Diagnostics.Type_parameters_cannot_appear_on_a_constructor_declaration);
69319             }
69320         }
69321         function checkGrammarConstructorTypeAnnotation(node) {
69322             var type = ts.getEffectiveReturnTypeNode(node);
69323             if (type) {
69324                 return grammarErrorOnNode(type, ts.Diagnostics.Type_annotation_cannot_appear_on_a_constructor_declaration);
69325             }
69326         }
69327         function checkGrammarProperty(node) {
69328             if (ts.isClassLike(node.parent)) {
69329                 if (ts.isStringLiteral(node.name) && node.name.text === "constructor") {
69330                     return grammarErrorOnNode(node.name, ts.Diagnostics.Classes_may_not_have_a_field_named_constructor);
69331                 }
69332                 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)) {
69333                     return true;
69334                 }
69335                 if (languageVersion < 2 /* ES2015 */ && ts.isPrivateIdentifier(node.name)) {
69336                     return grammarErrorOnNode(node.name, ts.Diagnostics.Private_identifiers_are_only_available_when_targeting_ECMAScript_2015_and_higher);
69337                 }
69338             }
69339             else if (node.parent.kind === 246 /* InterfaceDeclaration */) {
69340                 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)) {
69341                     return true;
69342                 }
69343                 if (node.initializer) {
69344                     return grammarErrorOnNode(node.initializer, ts.Diagnostics.An_interface_property_cannot_have_an_initializer);
69345                 }
69346             }
69347             else if (node.parent.kind === 173 /* TypeLiteral */) {
69348                 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)) {
69349                     return true;
69350                 }
69351                 if (node.initializer) {
69352                     return grammarErrorOnNode(node.initializer, ts.Diagnostics.A_type_literal_property_cannot_have_an_initializer);
69353                 }
69354             }
69355             if (node.flags & 8388608 /* Ambient */) {
69356                 checkAmbientInitializer(node);
69357             }
69358             if (ts.isPropertyDeclaration(node) && node.exclamationToken && (!ts.isClassLike(node.parent) || !node.type || node.initializer ||
69359                 node.flags & 8388608 /* Ambient */ || ts.hasModifier(node, 32 /* Static */ | 128 /* Abstract */))) {
69360                 return grammarErrorOnNode(node.exclamationToken, ts.Diagnostics.A_definite_assignment_assertion_is_not_permitted_in_this_context);
69361             }
69362         }
69363         function checkGrammarTopLevelElementForRequiredDeclareModifier(node) {
69364             // A declare modifier is required for any top level .d.ts declaration except export=, export default, export as namespace
69365             // interfaces and imports categories:
69366             //
69367             //  DeclarationElement:
69368             //     ExportAssignment
69369             //     export_opt   InterfaceDeclaration
69370             //     export_opt   TypeAliasDeclaration
69371             //     export_opt   ImportDeclaration
69372             //     export_opt   ExternalImportDeclaration
69373             //     export_opt   AmbientDeclaration
69374             //
69375             // TODO: The spec needs to be amended to reflect this grammar.
69376             if (node.kind === 246 /* InterfaceDeclaration */ ||
69377                 node.kind === 247 /* TypeAliasDeclaration */ ||
69378                 node.kind === 254 /* ImportDeclaration */ ||
69379                 node.kind === 253 /* ImportEqualsDeclaration */ ||
69380                 node.kind === 260 /* ExportDeclaration */ ||
69381                 node.kind === 259 /* ExportAssignment */ ||
69382                 node.kind === 252 /* NamespaceExportDeclaration */ ||
69383                 ts.hasModifier(node, 2 /* Ambient */ | 1 /* Export */ | 512 /* Default */)) {
69384                 return false;
69385             }
69386             return grammarErrorOnFirstToken(node, ts.Diagnostics.Top_level_declarations_in_d_ts_files_must_start_with_either_a_declare_or_export_modifier);
69387         }
69388         function checkGrammarTopLevelElementsForRequiredDeclareModifier(file) {
69389             for (var _i = 0, _a = file.statements; _i < _a.length; _i++) {
69390                 var decl = _a[_i];
69391                 if (ts.isDeclaration(decl) || decl.kind === 225 /* VariableStatement */) {
69392                     if (checkGrammarTopLevelElementForRequiredDeclareModifier(decl)) {
69393                         return true;
69394                     }
69395                 }
69396             }
69397             return false;
69398         }
69399         function checkGrammarSourceFile(node) {
69400             return !!(node.flags & 8388608 /* Ambient */) && checkGrammarTopLevelElementsForRequiredDeclareModifier(node);
69401         }
69402         function checkGrammarStatementInAmbientContext(node) {
69403             if (node.flags & 8388608 /* Ambient */) {
69404                 // Find containing block which is either Block, ModuleBlock, SourceFile
69405                 var links = getNodeLinks(node);
69406                 if (!links.hasReportedStatementInAmbientContext && (ts.isFunctionLike(node.parent) || ts.isAccessor(node.parent))) {
69407                     return getNodeLinks(node).hasReportedStatementInAmbientContext = grammarErrorOnFirstToken(node, ts.Diagnostics.An_implementation_cannot_be_declared_in_ambient_contexts);
69408                 }
69409                 // We are either parented by another statement, or some sort of block.
69410                 // If we're in a block, we only want to really report an error once
69411                 // to prevent noisiness.  So use a bit on the block to indicate if
69412                 // this has already been reported, and don't report if it has.
69413                 //
69414                 if (node.parent.kind === 223 /* Block */ || node.parent.kind === 250 /* ModuleBlock */ || node.parent.kind === 290 /* SourceFile */) {
69415                     var links_2 = getNodeLinks(node.parent);
69416                     // Check if the containing block ever report this error
69417                     if (!links_2.hasReportedStatementInAmbientContext) {
69418                         return links_2.hasReportedStatementInAmbientContext = grammarErrorOnFirstToken(node, ts.Diagnostics.Statements_are_not_allowed_in_ambient_contexts);
69419                     }
69420                 }
69421                 else {
69422                     // We must be parented by a statement.  If so, there's no need
69423                     // to report the error as our parent will have already done it.
69424                     // Debug.assert(isStatement(node.parent));
69425                 }
69426             }
69427             return false;
69428         }
69429         function checkGrammarNumericLiteral(node) {
69430             // Grammar checking
69431             if (node.numericLiteralFlags & 32 /* Octal */) {
69432                 var diagnosticMessage = void 0;
69433                 if (languageVersion >= 1 /* ES5 */) {
69434                     diagnosticMessage = ts.Diagnostics.Octal_literals_are_not_available_when_targeting_ECMAScript_5_and_higher_Use_the_syntax_0;
69435                 }
69436                 else if (ts.isChildOfNodeWithKind(node, 187 /* LiteralType */)) {
69437                     diagnosticMessage = ts.Diagnostics.Octal_literal_types_must_use_ES2015_syntax_Use_the_syntax_0;
69438                 }
69439                 else if (ts.isChildOfNodeWithKind(node, 284 /* EnumMember */)) {
69440                     diagnosticMessage = ts.Diagnostics.Octal_literals_are_not_allowed_in_enums_members_initializer_Use_the_syntax_0;
69441                 }
69442                 if (diagnosticMessage) {
69443                     var withMinus = ts.isPrefixUnaryExpression(node.parent) && node.parent.operator === 40 /* MinusToken */;
69444                     var literal = (withMinus ? "-" : "") + "0o" + node.text;
69445                     return grammarErrorOnNode(withMinus ? node.parent : node, diagnosticMessage, literal);
69446                 }
69447             }
69448             // Realism (size) checking
69449             checkNumericLiteralValueSize(node);
69450             return false;
69451         }
69452         function checkNumericLiteralValueSize(node) {
69453             // Scientific notation (e.g. 2e54 and 1e00000000010) can't be converted to bigint
69454             // Literals with 15 or fewer characters aren't long enough to reach past 2^53 - 1
69455             // Fractional numbers (e.g. 9000000000000000.001) are inherently imprecise anyway
69456             if (node.numericLiteralFlags & 16 /* Scientific */ || node.text.length <= 15 || node.text.indexOf(".") !== -1) {
69457                 return;
69458             }
69459             // We can't rely on the runtime to accurately store and compare extremely large numeric values
69460             // Even for internal use, we use getTextOfNode: https://github.com/microsoft/TypeScript/issues/33298
69461             // Thus, if the runtime claims a too-large number is lower than Number.MAX_SAFE_INTEGER,
69462             // it's likely addition operations on it will fail too
69463             var apparentValue = +ts.getTextOfNode(node);
69464             if (apparentValue <= Math.pow(2, 53) - 1 && apparentValue + 1 > apparentValue) {
69465                 return;
69466             }
69467             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));
69468         }
69469         function checkGrammarBigIntLiteral(node) {
69470             var literalType = ts.isLiteralTypeNode(node.parent) ||
69471                 ts.isPrefixUnaryExpression(node.parent) && ts.isLiteralTypeNode(node.parent.parent);
69472             if (!literalType) {
69473                 if (languageVersion < 7 /* ES2020 */) {
69474                     if (grammarErrorOnNode(node, ts.Diagnostics.BigInt_literals_are_not_available_when_targeting_lower_than_ES2020)) {
69475                         return true;
69476                     }
69477                 }
69478             }
69479             return false;
69480         }
69481         function grammarErrorAfterFirstToken(node, message, arg0, arg1, arg2) {
69482             var sourceFile = ts.getSourceFileOfNode(node);
69483             if (!hasParseDiagnostics(sourceFile)) {
69484                 var span = ts.getSpanOfTokenAtPosition(sourceFile, node.pos);
69485                 diagnostics.add(ts.createFileDiagnostic(sourceFile, ts.textSpanEnd(span), /*length*/ 0, message, arg0, arg1, arg2));
69486                 return true;
69487             }
69488             return false;
69489         }
69490         function getAmbientModules() {
69491             if (!ambientModulesCache) {
69492                 ambientModulesCache = [];
69493                 globals.forEach(function (global, sym) {
69494                     // No need to `unescapeLeadingUnderscores`, an escaped symbol is never an ambient module.
69495                     if (ambientModuleSymbolRegex.test(sym)) {
69496                         ambientModulesCache.push(global);
69497                     }
69498                 });
69499             }
69500             return ambientModulesCache;
69501         }
69502         function checkGrammarImportClause(node) {
69503             if (node.isTypeOnly && node.name && node.namedBindings) {
69504                 return grammarErrorOnNode(node, ts.Diagnostics.A_type_only_import_can_specify_a_default_import_or_named_bindings_but_not_both);
69505             }
69506             return false;
69507         }
69508         function checkGrammarImportCallExpression(node) {
69509             if (moduleKind === ts.ModuleKind.ES2015) {
69510                 return grammarErrorOnNode(node, ts.Diagnostics.Dynamic_imports_are_only_supported_when_the_module_flag_is_set_to_es2020_esnext_commonjs_amd_system_or_umd);
69511             }
69512             if (node.typeArguments) {
69513                 return grammarErrorOnNode(node, ts.Diagnostics.Dynamic_import_cannot_have_type_arguments);
69514             }
69515             var nodeArguments = node.arguments;
69516             if (nodeArguments.length !== 1) {
69517                 return grammarErrorOnNode(node, ts.Diagnostics.Dynamic_import_must_have_one_specifier_as_an_argument);
69518             }
69519             checkGrammarForDisallowedTrailingComma(nodeArguments);
69520             // see: parseArgumentOrArrayLiteralElement...we use this function which parse arguments of callExpression to parse specifier for dynamic import.
69521             // parseArgumentOrArrayLiteralElement allows spread element to be in an argument list which is not allowed as specifier in dynamic import.
69522             if (ts.isSpreadElement(nodeArguments[0])) {
69523                 return grammarErrorOnNode(nodeArguments[0], ts.Diagnostics.Specifier_of_dynamic_import_cannot_be_spread_element);
69524             }
69525             return false;
69526         }
69527         function findMatchingTypeReferenceOrTypeAliasReference(source, unionTarget) {
69528             var sourceObjectFlags = ts.getObjectFlags(source);
69529             if (sourceObjectFlags & (4 /* Reference */ | 16 /* Anonymous */) && unionTarget.flags & 1048576 /* Union */) {
69530                 return ts.find(unionTarget.types, function (target) {
69531                     if (target.flags & 524288 /* Object */) {
69532                         var overlapObjFlags = sourceObjectFlags & ts.getObjectFlags(target);
69533                         if (overlapObjFlags & 4 /* Reference */) {
69534                             return source.target === target.target;
69535                         }
69536                         if (overlapObjFlags & 16 /* Anonymous */) {
69537                             return !!source.aliasSymbol && source.aliasSymbol === target.aliasSymbol;
69538                         }
69539                     }
69540                     return false;
69541                 });
69542             }
69543         }
69544         function findBestTypeForObjectLiteral(source, unionTarget) {
69545             if (ts.getObjectFlags(source) & 128 /* ObjectLiteral */ && forEachType(unionTarget, isArrayLikeType)) {
69546                 return ts.find(unionTarget.types, function (t) { return !isArrayLikeType(t); });
69547             }
69548         }
69549         function findBestTypeForInvokable(source, unionTarget) {
69550             var signatureKind = 0 /* Call */;
69551             var hasSignatures = getSignaturesOfType(source, signatureKind).length > 0 ||
69552                 (signatureKind = 1 /* Construct */, getSignaturesOfType(source, signatureKind).length > 0);
69553             if (hasSignatures) {
69554                 return ts.find(unionTarget.types, function (t) { return getSignaturesOfType(t, signatureKind).length > 0; });
69555             }
69556         }
69557         function findMostOverlappyType(source, unionTarget) {
69558             var bestMatch;
69559             var matchingCount = 0;
69560             for (var _i = 0, _a = unionTarget.types; _i < _a.length; _i++) {
69561                 var target = _a[_i];
69562                 var overlap = getIntersectionType([getIndexType(source), getIndexType(target)]);
69563                 if (overlap.flags & 4194304 /* Index */) {
69564                     // perfect overlap of keys
69565                     bestMatch = target;
69566                     matchingCount = Infinity;
69567                 }
69568                 else if (overlap.flags & 1048576 /* Union */) {
69569                     // We only want to account for literal types otherwise.
69570                     // If we have a union of index types, it seems likely that we
69571                     // needed to elaborate between two generic mapped types anyway.
69572                     var len = ts.length(ts.filter(overlap.types, isUnitType));
69573                     if (len >= matchingCount) {
69574                         bestMatch = target;
69575                         matchingCount = len;
69576                     }
69577                 }
69578                 else if (isUnitType(overlap) && 1 >= matchingCount) {
69579                     bestMatch = target;
69580                     matchingCount = 1;
69581                 }
69582             }
69583             return bestMatch;
69584         }
69585         function filterPrimitivesIfContainsNonPrimitive(type) {
69586             if (maybeTypeOfKind(type, 67108864 /* NonPrimitive */)) {
69587                 var result = filterType(type, function (t) { return !(t.flags & 131068 /* Primitive */); });
69588                 if (!(result.flags & 131072 /* Never */)) {
69589                     return result;
69590                 }
69591             }
69592             return type;
69593         }
69594         // Keep this up-to-date with the same logic within `getApparentTypeOfContextualType`, since they should behave similarly
69595         function findMatchingDiscriminantType(source, target, isRelatedTo, skipPartial) {
69596             if (target.flags & 1048576 /* Union */ && source.flags & (2097152 /* Intersection */ | 524288 /* Object */)) {
69597                 var sourceProperties = getPropertiesOfType(source);
69598                 if (sourceProperties) {
69599                     var sourcePropertiesFiltered = findDiscriminantProperties(sourceProperties, target);
69600                     if (sourcePropertiesFiltered) {
69601                         return discriminateTypeByDiscriminableItems(target, ts.map(sourcePropertiesFiltered, function (p) { return [function () { return getTypeOfSymbol(p); }, p.escapedName]; }), isRelatedTo, /*defaultValue*/ undefined, skipPartial);
69602                     }
69603                 }
69604             }
69605             return undefined;
69606         }
69607     }
69608     ts.createTypeChecker = createTypeChecker;
69609     function isNotAccessor(declaration) {
69610         // Accessors check for their own matching duplicates, and in contexts where they are valid, there are already duplicate identifier checks
69611         return !ts.isAccessor(declaration);
69612     }
69613     function isNotOverload(declaration) {
69614         return (declaration.kind !== 244 /* FunctionDeclaration */ && declaration.kind !== 161 /* MethodDeclaration */) ||
69615             !!declaration.body;
69616     }
69617     /** Like 'isDeclarationName', but returns true for LHS of `import { x as y }` or `export { x as y }`. */
69618     function isDeclarationNameOrImportPropertyName(name) {
69619         switch (name.parent.kind) {
69620             case 258 /* ImportSpecifier */:
69621             case 263 /* ExportSpecifier */:
69622                 return ts.isIdentifier(name);
69623             default:
69624                 return ts.isDeclarationName(name);
69625         }
69626     }
69627     function isSomeImportDeclaration(decl) {
69628         switch (decl.kind) {
69629             case 255 /* ImportClause */: // For default import
69630             case 253 /* ImportEqualsDeclaration */:
69631             case 256 /* NamespaceImport */:
69632             case 258 /* ImportSpecifier */: // For rename import `x as y`
69633                 return true;
69634             case 75 /* Identifier */:
69635                 // For regular import, `decl` is an Identifier under the ImportSpecifier.
69636                 return decl.parent.kind === 258 /* ImportSpecifier */;
69637             default:
69638                 return false;
69639         }
69640     }
69641     var JsxNames;
69642     (function (JsxNames) {
69643         JsxNames.JSX = "JSX";
69644         JsxNames.IntrinsicElements = "IntrinsicElements";
69645         JsxNames.ElementClass = "ElementClass";
69646         JsxNames.ElementAttributesPropertyNameContainer = "ElementAttributesProperty"; // TODO: Deprecate and remove support
69647         JsxNames.ElementChildrenAttributeNameContainer = "ElementChildrenAttribute";
69648         JsxNames.Element = "Element";
69649         JsxNames.IntrinsicAttributes = "IntrinsicAttributes";
69650         JsxNames.IntrinsicClassAttributes = "IntrinsicClassAttributes";
69651         JsxNames.LibraryManagedAttributes = "LibraryManagedAttributes";
69652     })(JsxNames || (JsxNames = {}));
69653     function getIterationTypesKeyFromIterationTypeKind(typeKind) {
69654         switch (typeKind) {
69655             case 0 /* Yield */: return "yieldType";
69656             case 1 /* Return */: return "returnType";
69657             case 2 /* Next */: return "nextType";
69658         }
69659     }
69660     function signatureHasRestParameter(s) {
69661         return !!(s.flags & 1 /* HasRestParameter */);
69662     }
69663     ts.signatureHasRestParameter = signatureHasRestParameter;
69664     function signatureHasLiteralTypes(s) {
69665         return !!(s.flags & 2 /* HasLiteralTypes */);
69666     }
69667     ts.signatureHasLiteralTypes = signatureHasLiteralTypes;
69668 })(ts || (ts = {}));
69669 var ts;
69670 (function (ts) {
69671     function createSynthesizedNode(kind) {
69672         var node = ts.createNode(kind, -1, -1);
69673         node.flags |= 8 /* Synthesized */;
69674         return node;
69675     }
69676     /* @internal */
69677     function updateNode(updated, original) {
69678         if (updated !== original) {
69679             setOriginalNode(updated, original);
69680             setTextRange(updated, original);
69681             ts.aggregateTransformFlags(updated);
69682         }
69683         return updated;
69684     }
69685     ts.updateNode = updateNode;
69686     /**
69687      * Make `elements` into a `NodeArray<T>`. If `elements` is `undefined`, returns an empty `NodeArray<T>`.
69688      */
69689     function createNodeArray(elements, hasTrailingComma) {
69690         if (!elements || elements === ts.emptyArray) {
69691             elements = [];
69692         }
69693         else if (ts.isNodeArray(elements)) {
69694             return elements;
69695         }
69696         var array = elements;
69697         array.pos = -1;
69698         array.end = -1;
69699         array.hasTrailingComma = hasTrailingComma;
69700         return array;
69701     }
69702     ts.createNodeArray = createNodeArray;
69703     /**
69704      * Creates a shallow, memberwise clone of a node with no source map location.
69705      */
69706     /* @internal */
69707     function getSynthesizedClone(node) {
69708         // We don't use "clone" from core.ts here, as we need to preserve the prototype chain of
69709         // the original node. We also need to exclude specific properties and only include own-
69710         // properties (to skip members already defined on the shared prototype).
69711         if (node === undefined) {
69712             return node;
69713         }
69714         var clone = createSynthesizedNode(node.kind);
69715         clone.flags |= node.flags;
69716         setOriginalNode(clone, node);
69717         for (var key in node) {
69718             if (clone.hasOwnProperty(key) || !node.hasOwnProperty(key)) {
69719                 continue;
69720             }
69721             clone[key] = node[key];
69722         }
69723         return clone;
69724     }
69725     ts.getSynthesizedClone = getSynthesizedClone;
69726     function createLiteral(value, isSingleQuote) {
69727         if (typeof value === "number") {
69728             return createNumericLiteral(value + "");
69729         }
69730         // eslint-disable-next-line no-in-operator
69731         if (typeof value === "object" && "base10Value" in value) { // PseudoBigInt
69732             return createBigIntLiteral(ts.pseudoBigIntToString(value) + "n");
69733         }
69734         if (typeof value === "boolean") {
69735             return value ? createTrue() : createFalse();
69736         }
69737         if (ts.isString(value)) {
69738             var res = createStringLiteral(value);
69739             if (isSingleQuote)
69740                 res.singleQuote = true;
69741             return res;
69742         }
69743         return createLiteralFromNode(value);
69744     }
69745     ts.createLiteral = createLiteral;
69746     function createNumericLiteral(value, numericLiteralFlags) {
69747         if (numericLiteralFlags === void 0) { numericLiteralFlags = 0 /* None */; }
69748         var node = createSynthesizedNode(8 /* NumericLiteral */);
69749         node.text = value;
69750         node.numericLiteralFlags = numericLiteralFlags;
69751         return node;
69752     }
69753     ts.createNumericLiteral = createNumericLiteral;
69754     function createBigIntLiteral(value) {
69755         var node = createSynthesizedNode(9 /* BigIntLiteral */);
69756         node.text = value;
69757         return node;
69758     }
69759     ts.createBigIntLiteral = createBigIntLiteral;
69760     function createStringLiteral(text) {
69761         var node = createSynthesizedNode(10 /* StringLiteral */);
69762         node.text = text;
69763         return node;
69764     }
69765     ts.createStringLiteral = createStringLiteral;
69766     function createRegularExpressionLiteral(text) {
69767         var node = createSynthesizedNode(13 /* RegularExpressionLiteral */);
69768         node.text = text;
69769         return node;
69770     }
69771     ts.createRegularExpressionLiteral = createRegularExpressionLiteral;
69772     function createLiteralFromNode(sourceNode) {
69773         var node = createStringLiteral(ts.getTextOfIdentifierOrLiteral(sourceNode));
69774         node.textSourceNode = sourceNode;
69775         return node;
69776     }
69777     function createIdentifier(text, typeArguments) {
69778         var node = createSynthesizedNode(75 /* Identifier */);
69779         node.escapedText = ts.escapeLeadingUnderscores(text);
69780         node.originalKeywordKind = text ? ts.stringToToken(text) : 0 /* Unknown */;
69781         node.autoGenerateFlags = 0 /* None */;
69782         node.autoGenerateId = 0;
69783         if (typeArguments) {
69784             node.typeArguments = createNodeArray(typeArguments);
69785         }
69786         return node;
69787     }
69788     ts.createIdentifier = createIdentifier;
69789     function updateIdentifier(node, typeArguments) {
69790         return node.typeArguments !== typeArguments
69791             ? updateNode(createIdentifier(ts.idText(node), typeArguments), node)
69792             : node;
69793     }
69794     ts.updateIdentifier = updateIdentifier;
69795     var nextAutoGenerateId = 0;
69796     function createTempVariable(recordTempVariable, reservedInNestedScopes) {
69797         var name = createIdentifier("");
69798         name.autoGenerateFlags = 1 /* Auto */;
69799         name.autoGenerateId = nextAutoGenerateId;
69800         nextAutoGenerateId++;
69801         if (recordTempVariable) {
69802             recordTempVariable(name);
69803         }
69804         if (reservedInNestedScopes) {
69805             name.autoGenerateFlags |= 8 /* ReservedInNestedScopes */;
69806         }
69807         return name;
69808     }
69809     ts.createTempVariable = createTempVariable;
69810     /** Create a unique temporary variable for use in a loop. */
69811     function createLoopVariable() {
69812         var name = createIdentifier("");
69813         name.autoGenerateFlags = 2 /* Loop */;
69814         name.autoGenerateId = nextAutoGenerateId;
69815         nextAutoGenerateId++;
69816         return name;
69817     }
69818     ts.createLoopVariable = createLoopVariable;
69819     /** Create a unique name based on the supplied text. */
69820     function createUniqueName(text) {
69821         var name = createIdentifier(text);
69822         name.autoGenerateFlags = 3 /* Unique */;
69823         name.autoGenerateId = nextAutoGenerateId;
69824         nextAutoGenerateId++;
69825         return name;
69826     }
69827     ts.createUniqueName = createUniqueName;
69828     function createOptimisticUniqueName(text) {
69829         var name = createIdentifier(text);
69830         name.autoGenerateFlags = 3 /* Unique */ | 16 /* Optimistic */;
69831         name.autoGenerateId = nextAutoGenerateId;
69832         nextAutoGenerateId++;
69833         return name;
69834     }
69835     ts.createOptimisticUniqueName = createOptimisticUniqueName;
69836     /** Create a unique name based on the supplied text. This does not consider names injected by the transformer. */
69837     function createFileLevelUniqueName(text) {
69838         var name = createOptimisticUniqueName(text);
69839         name.autoGenerateFlags |= 32 /* FileLevel */;
69840         return name;
69841     }
69842     ts.createFileLevelUniqueName = createFileLevelUniqueName;
69843     function getGeneratedNameForNode(node, flags) {
69844         var name = createIdentifier(node && ts.isIdentifier(node) ? ts.idText(node) : "");
69845         name.autoGenerateFlags = 4 /* Node */ | flags;
69846         name.autoGenerateId = nextAutoGenerateId;
69847         name.original = node;
69848         nextAutoGenerateId++;
69849         return name;
69850     }
69851     ts.getGeneratedNameForNode = getGeneratedNameForNode;
69852     // Private Identifiers
69853     function createPrivateIdentifier(text) {
69854         if (text[0] !== "#") {
69855             ts.Debug.fail("First character of private identifier must be #: " + text);
69856         }
69857         var node = createSynthesizedNode(76 /* PrivateIdentifier */);
69858         node.escapedText = ts.escapeLeadingUnderscores(text);
69859         return node;
69860     }
69861     ts.createPrivateIdentifier = createPrivateIdentifier;
69862     // Punctuation
69863     function createToken(token) {
69864         return createSynthesizedNode(token);
69865     }
69866     ts.createToken = createToken;
69867     // Reserved words
69868     function createSuper() {
69869         return createSynthesizedNode(102 /* SuperKeyword */);
69870     }
69871     ts.createSuper = createSuper;
69872     function createThis() {
69873         return createSynthesizedNode(104 /* ThisKeyword */);
69874     }
69875     ts.createThis = createThis;
69876     function createNull() {
69877         return createSynthesizedNode(100 /* NullKeyword */);
69878     }
69879     ts.createNull = createNull;
69880     function createTrue() {
69881         return createSynthesizedNode(106 /* TrueKeyword */);
69882     }
69883     ts.createTrue = createTrue;
69884     function createFalse() {
69885         return createSynthesizedNode(91 /* FalseKeyword */);
69886     }
69887     ts.createFalse = createFalse;
69888     // Modifiers
69889     function createModifier(kind) {
69890         return createToken(kind);
69891     }
69892     ts.createModifier = createModifier;
69893     function createModifiersFromModifierFlags(flags) {
69894         var result = [];
69895         if (flags & 1 /* Export */) {
69896             result.push(createModifier(89 /* ExportKeyword */));
69897         }
69898         if (flags & 2 /* Ambient */) {
69899             result.push(createModifier(130 /* DeclareKeyword */));
69900         }
69901         if (flags & 512 /* Default */) {
69902             result.push(createModifier(84 /* DefaultKeyword */));
69903         }
69904         if (flags & 2048 /* Const */) {
69905             result.push(createModifier(81 /* ConstKeyword */));
69906         }
69907         if (flags & 4 /* Public */) {
69908             result.push(createModifier(119 /* PublicKeyword */));
69909         }
69910         if (flags & 8 /* Private */) {
69911             result.push(createModifier(117 /* PrivateKeyword */));
69912         }
69913         if (flags & 16 /* Protected */) {
69914             result.push(createModifier(118 /* ProtectedKeyword */));
69915         }
69916         if (flags & 128 /* Abstract */) {
69917             result.push(createModifier(122 /* AbstractKeyword */));
69918         }
69919         if (flags & 32 /* Static */) {
69920             result.push(createModifier(120 /* StaticKeyword */));
69921         }
69922         if (flags & 64 /* Readonly */) {
69923             result.push(createModifier(138 /* ReadonlyKeyword */));
69924         }
69925         if (flags & 256 /* Async */) {
69926             result.push(createModifier(126 /* AsyncKeyword */));
69927         }
69928         return result;
69929     }
69930     ts.createModifiersFromModifierFlags = createModifiersFromModifierFlags;
69931     // Names
69932     function createQualifiedName(left, right) {
69933         var node = createSynthesizedNode(153 /* QualifiedName */);
69934         node.left = left;
69935         node.right = asName(right);
69936         return node;
69937     }
69938     ts.createQualifiedName = createQualifiedName;
69939     function updateQualifiedName(node, left, right) {
69940         return node.left !== left
69941             || node.right !== right
69942             ? updateNode(createQualifiedName(left, right), node)
69943             : node;
69944     }
69945     ts.updateQualifiedName = updateQualifiedName;
69946     function parenthesizeForComputedName(expression) {
69947         return ts.isCommaSequence(expression)
69948             ? createParen(expression)
69949             : expression;
69950     }
69951     function createComputedPropertyName(expression) {
69952         var node = createSynthesizedNode(154 /* ComputedPropertyName */);
69953         node.expression = parenthesizeForComputedName(expression);
69954         return node;
69955     }
69956     ts.createComputedPropertyName = createComputedPropertyName;
69957     function updateComputedPropertyName(node, expression) {
69958         return node.expression !== expression
69959             ? updateNode(createComputedPropertyName(expression), node)
69960             : node;
69961     }
69962     ts.updateComputedPropertyName = updateComputedPropertyName;
69963     // Signature elements
69964     function createTypeParameterDeclaration(name, constraint, defaultType) {
69965         var node = createSynthesizedNode(155 /* TypeParameter */);
69966         node.name = asName(name);
69967         node.constraint = constraint;
69968         node.default = defaultType;
69969         return node;
69970     }
69971     ts.createTypeParameterDeclaration = createTypeParameterDeclaration;
69972     function updateTypeParameterDeclaration(node, name, constraint, defaultType) {
69973         return node.name !== name
69974             || node.constraint !== constraint
69975             || node.default !== defaultType
69976             ? updateNode(createTypeParameterDeclaration(name, constraint, defaultType), node)
69977             : node;
69978     }
69979     ts.updateTypeParameterDeclaration = updateTypeParameterDeclaration;
69980     function createParameter(decorators, modifiers, dotDotDotToken, name, questionToken, type, initializer) {
69981         var node = createSynthesizedNode(156 /* Parameter */);
69982         node.decorators = asNodeArray(decorators);
69983         node.modifiers = asNodeArray(modifiers);
69984         node.dotDotDotToken = dotDotDotToken;
69985         node.name = asName(name);
69986         node.questionToken = questionToken;
69987         node.type = type;
69988         node.initializer = initializer ? ts.parenthesizeExpressionForList(initializer) : undefined;
69989         return node;
69990     }
69991     ts.createParameter = createParameter;
69992     function updateParameter(node, decorators, modifiers, dotDotDotToken, name, questionToken, type, initializer) {
69993         return node.decorators !== decorators
69994             || node.modifiers !== modifiers
69995             || node.dotDotDotToken !== dotDotDotToken
69996             || node.name !== name
69997             || node.questionToken !== questionToken
69998             || node.type !== type
69999             || node.initializer !== initializer
70000             ? updateNode(createParameter(decorators, modifiers, dotDotDotToken, name, questionToken, type, initializer), node)
70001             : node;
70002     }
70003     ts.updateParameter = updateParameter;
70004     function createDecorator(expression) {
70005         var node = createSynthesizedNode(157 /* Decorator */);
70006         node.expression = ts.parenthesizeForAccess(expression);
70007         return node;
70008     }
70009     ts.createDecorator = createDecorator;
70010     function updateDecorator(node, expression) {
70011         return node.expression !== expression
70012             ? updateNode(createDecorator(expression), node)
70013             : node;
70014     }
70015     ts.updateDecorator = updateDecorator;
70016     // Type Elements
70017     function createPropertySignature(modifiers, name, questionToken, type, initializer) {
70018         var node = createSynthesizedNode(158 /* PropertySignature */);
70019         node.modifiers = asNodeArray(modifiers);
70020         node.name = asName(name);
70021         node.questionToken = questionToken;
70022         node.type = type;
70023         node.initializer = initializer;
70024         return node;
70025     }
70026     ts.createPropertySignature = createPropertySignature;
70027     function updatePropertySignature(node, modifiers, name, questionToken, type, initializer) {
70028         return node.modifiers !== modifiers
70029             || node.name !== name
70030             || node.questionToken !== questionToken
70031             || node.type !== type
70032             || node.initializer !== initializer
70033             ? updateNode(createPropertySignature(modifiers, name, questionToken, type, initializer), node)
70034             : node;
70035     }
70036     ts.updatePropertySignature = updatePropertySignature;
70037     function createProperty(decorators, modifiers, name, questionOrExclamationToken, type, initializer) {
70038         var node = createSynthesizedNode(159 /* PropertyDeclaration */);
70039         node.decorators = asNodeArray(decorators);
70040         node.modifiers = asNodeArray(modifiers);
70041         node.name = asName(name);
70042         node.questionToken = questionOrExclamationToken !== undefined && questionOrExclamationToken.kind === 57 /* QuestionToken */ ? questionOrExclamationToken : undefined;
70043         node.exclamationToken = questionOrExclamationToken !== undefined && questionOrExclamationToken.kind === 53 /* ExclamationToken */ ? questionOrExclamationToken : undefined;
70044         node.type = type;
70045         node.initializer = initializer;
70046         return node;
70047     }
70048     ts.createProperty = createProperty;
70049     function updateProperty(node, decorators, modifiers, name, questionOrExclamationToken, type, initializer) {
70050         return node.decorators !== decorators
70051             || node.modifiers !== modifiers
70052             || node.name !== name
70053             || node.questionToken !== (questionOrExclamationToken !== undefined && questionOrExclamationToken.kind === 57 /* QuestionToken */ ? questionOrExclamationToken : undefined)
70054             || node.exclamationToken !== (questionOrExclamationToken !== undefined && questionOrExclamationToken.kind === 53 /* ExclamationToken */ ? questionOrExclamationToken : undefined)
70055             || node.type !== type
70056             || node.initializer !== initializer
70057             ? updateNode(createProperty(decorators, modifiers, name, questionOrExclamationToken, type, initializer), node)
70058             : node;
70059     }
70060     ts.updateProperty = updateProperty;
70061     function createMethodSignature(typeParameters, parameters, type, name, questionToken) {
70062         var node = createSignatureDeclaration(160 /* MethodSignature */, typeParameters, parameters, type);
70063         node.name = asName(name);
70064         node.questionToken = questionToken;
70065         return node;
70066     }
70067     ts.createMethodSignature = createMethodSignature;
70068     function updateMethodSignature(node, typeParameters, parameters, type, name, questionToken) {
70069         return node.typeParameters !== typeParameters
70070             || node.parameters !== parameters
70071             || node.type !== type
70072             || node.name !== name
70073             || node.questionToken !== questionToken
70074             ? updateNode(createMethodSignature(typeParameters, parameters, type, name, questionToken), node)
70075             : node;
70076     }
70077     ts.updateMethodSignature = updateMethodSignature;
70078     function createMethod(decorators, modifiers, asteriskToken, name, questionToken, typeParameters, parameters, type, body) {
70079         var node = createSynthesizedNode(161 /* MethodDeclaration */);
70080         node.decorators = asNodeArray(decorators);
70081         node.modifiers = asNodeArray(modifiers);
70082         node.asteriskToken = asteriskToken;
70083         node.name = asName(name);
70084         node.questionToken = questionToken;
70085         node.typeParameters = asNodeArray(typeParameters);
70086         node.parameters = createNodeArray(parameters);
70087         node.type = type;
70088         node.body = body;
70089         return node;
70090     }
70091     ts.createMethod = createMethod;
70092     function createMethodCall(object, methodName, argumentsList) {
70093         return createCall(createPropertyAccess(object, asName(methodName)), 
70094         /*typeArguments*/ undefined, argumentsList);
70095     }
70096     function createGlobalMethodCall(globalObjectName, methodName, argumentsList) {
70097         return createMethodCall(createIdentifier(globalObjectName), methodName, argumentsList);
70098     }
70099     /* @internal */
70100     function createObjectDefinePropertyCall(target, propertyName, attributes) {
70101         return createGlobalMethodCall("Object", "defineProperty", [target, asExpression(propertyName), attributes]);
70102     }
70103     ts.createObjectDefinePropertyCall = createObjectDefinePropertyCall;
70104     function tryAddPropertyAssignment(properties, propertyName, expression) {
70105         if (expression) {
70106             properties.push(createPropertyAssignment(propertyName, expression));
70107             return true;
70108         }
70109         return false;
70110     }
70111     /* @internal */
70112     function createPropertyDescriptor(attributes, singleLine) {
70113         var properties = [];
70114         tryAddPropertyAssignment(properties, "enumerable", asExpression(attributes.enumerable));
70115         tryAddPropertyAssignment(properties, "configurable", asExpression(attributes.configurable));
70116         var isData = tryAddPropertyAssignment(properties, "writable", asExpression(attributes.writable));
70117         isData = tryAddPropertyAssignment(properties, "value", attributes.value) || isData;
70118         var isAccessor = tryAddPropertyAssignment(properties, "get", attributes.get);
70119         isAccessor = tryAddPropertyAssignment(properties, "set", attributes.set) || isAccessor;
70120         ts.Debug.assert(!(isData && isAccessor), "A PropertyDescriptor may not be both an accessor descriptor and a data descriptor.");
70121         return createObjectLiteral(properties, !singleLine);
70122     }
70123     ts.createPropertyDescriptor = createPropertyDescriptor;
70124     function updateMethod(node, decorators, modifiers, asteriskToken, name, questionToken, typeParameters, parameters, type, body) {
70125         return node.decorators !== decorators
70126             || node.modifiers !== modifiers
70127             || node.asteriskToken !== asteriskToken
70128             || node.name !== name
70129             || node.questionToken !== questionToken
70130             || node.typeParameters !== typeParameters
70131             || node.parameters !== parameters
70132             || node.type !== type
70133             || node.body !== body
70134             ? updateNode(createMethod(decorators, modifiers, asteriskToken, name, questionToken, typeParameters, parameters, type, body), node)
70135             : node;
70136     }
70137     ts.updateMethod = updateMethod;
70138     function createConstructor(decorators, modifiers, parameters, body) {
70139         var node = createSynthesizedNode(162 /* Constructor */);
70140         node.decorators = asNodeArray(decorators);
70141         node.modifiers = asNodeArray(modifiers);
70142         node.typeParameters = undefined;
70143         node.parameters = createNodeArray(parameters);
70144         node.type = undefined;
70145         node.body = body;
70146         return node;
70147     }
70148     ts.createConstructor = createConstructor;
70149     function updateConstructor(node, decorators, modifiers, parameters, body) {
70150         return node.decorators !== decorators
70151             || node.modifiers !== modifiers
70152             || node.parameters !== parameters
70153             || node.body !== body
70154             ? updateNode(createConstructor(decorators, modifiers, parameters, body), node)
70155             : node;
70156     }
70157     ts.updateConstructor = updateConstructor;
70158     function createGetAccessor(decorators, modifiers, name, parameters, type, body) {
70159         var node = createSynthesizedNode(163 /* GetAccessor */);
70160         node.decorators = asNodeArray(decorators);
70161         node.modifiers = asNodeArray(modifiers);
70162         node.name = asName(name);
70163         node.typeParameters = undefined;
70164         node.parameters = createNodeArray(parameters);
70165         node.type = type;
70166         node.body = body;
70167         return node;
70168     }
70169     ts.createGetAccessor = createGetAccessor;
70170     function updateGetAccessor(node, decorators, modifiers, name, parameters, type, body) {
70171         return node.decorators !== decorators
70172             || node.modifiers !== modifiers
70173             || node.name !== name
70174             || node.parameters !== parameters
70175             || node.type !== type
70176             || node.body !== body
70177             ? updateNode(createGetAccessor(decorators, modifiers, name, parameters, type, body), node)
70178             : node;
70179     }
70180     ts.updateGetAccessor = updateGetAccessor;
70181     function createSetAccessor(decorators, modifiers, name, parameters, body) {
70182         var node = createSynthesizedNode(164 /* SetAccessor */);
70183         node.decorators = asNodeArray(decorators);
70184         node.modifiers = asNodeArray(modifiers);
70185         node.name = asName(name);
70186         node.typeParameters = undefined;
70187         node.parameters = createNodeArray(parameters);
70188         node.body = body;
70189         return node;
70190     }
70191     ts.createSetAccessor = createSetAccessor;
70192     function updateSetAccessor(node, decorators, modifiers, name, parameters, body) {
70193         return node.decorators !== decorators
70194             || node.modifiers !== modifiers
70195             || node.name !== name
70196             || node.parameters !== parameters
70197             || node.body !== body
70198             ? updateNode(createSetAccessor(decorators, modifiers, name, parameters, body), node)
70199             : node;
70200     }
70201     ts.updateSetAccessor = updateSetAccessor;
70202     function createCallSignature(typeParameters, parameters, type) {
70203         return createSignatureDeclaration(165 /* CallSignature */, typeParameters, parameters, type);
70204     }
70205     ts.createCallSignature = createCallSignature;
70206     function updateCallSignature(node, typeParameters, parameters, type) {
70207         return updateSignatureDeclaration(node, typeParameters, parameters, type);
70208     }
70209     ts.updateCallSignature = updateCallSignature;
70210     function createConstructSignature(typeParameters, parameters, type) {
70211         return createSignatureDeclaration(166 /* ConstructSignature */, typeParameters, parameters, type);
70212     }
70213     ts.createConstructSignature = createConstructSignature;
70214     function updateConstructSignature(node, typeParameters, parameters, type) {
70215         return updateSignatureDeclaration(node, typeParameters, parameters, type);
70216     }
70217     ts.updateConstructSignature = updateConstructSignature;
70218     function createIndexSignature(decorators, modifiers, parameters, type) {
70219         var node = createSynthesizedNode(167 /* IndexSignature */);
70220         node.decorators = asNodeArray(decorators);
70221         node.modifiers = asNodeArray(modifiers);
70222         node.parameters = createNodeArray(parameters);
70223         node.type = type;
70224         return node;
70225     }
70226     ts.createIndexSignature = createIndexSignature;
70227     function updateIndexSignature(node, decorators, modifiers, parameters, type) {
70228         return node.parameters !== parameters
70229             || node.type !== type
70230             || node.decorators !== decorators
70231             || node.modifiers !== modifiers
70232             ? updateNode(createIndexSignature(decorators, modifiers, parameters, type), node)
70233             : node;
70234     }
70235     ts.updateIndexSignature = updateIndexSignature;
70236     /* @internal */
70237     function createSignatureDeclaration(kind, typeParameters, parameters, type, typeArguments) {
70238         var node = createSynthesizedNode(kind);
70239         node.typeParameters = asNodeArray(typeParameters);
70240         node.parameters = asNodeArray(parameters);
70241         node.type = type;
70242         node.typeArguments = asNodeArray(typeArguments);
70243         return node;
70244     }
70245     ts.createSignatureDeclaration = createSignatureDeclaration;
70246     function updateSignatureDeclaration(node, typeParameters, parameters, type) {
70247         return node.typeParameters !== typeParameters
70248             || node.parameters !== parameters
70249             || node.type !== type
70250             ? updateNode(createSignatureDeclaration(node.kind, typeParameters, parameters, type), node)
70251             : node;
70252     }
70253     // Types
70254     function createKeywordTypeNode(kind) {
70255         return createSynthesizedNode(kind);
70256     }
70257     ts.createKeywordTypeNode = createKeywordTypeNode;
70258     function createTypePredicateNode(parameterName, type) {
70259         return createTypePredicateNodeWithModifier(/*assertsModifier*/ undefined, parameterName, type);
70260     }
70261     ts.createTypePredicateNode = createTypePredicateNode;
70262     function createTypePredicateNodeWithModifier(assertsModifier, parameterName, type) {
70263         var node = createSynthesizedNode(168 /* TypePredicate */);
70264         node.assertsModifier = assertsModifier;
70265         node.parameterName = asName(parameterName);
70266         node.type = type;
70267         return node;
70268     }
70269     ts.createTypePredicateNodeWithModifier = createTypePredicateNodeWithModifier;
70270     function updateTypePredicateNode(node, parameterName, type) {
70271         return updateTypePredicateNodeWithModifier(node, node.assertsModifier, parameterName, type);
70272     }
70273     ts.updateTypePredicateNode = updateTypePredicateNode;
70274     function updateTypePredicateNodeWithModifier(node, assertsModifier, parameterName, type) {
70275         return node.assertsModifier !== assertsModifier
70276             || node.parameterName !== parameterName
70277             || node.type !== type
70278             ? updateNode(createTypePredicateNodeWithModifier(assertsModifier, parameterName, type), node)
70279             : node;
70280     }
70281     ts.updateTypePredicateNodeWithModifier = updateTypePredicateNodeWithModifier;
70282     function createTypeReferenceNode(typeName, typeArguments) {
70283         var node = createSynthesizedNode(169 /* TypeReference */);
70284         node.typeName = asName(typeName);
70285         node.typeArguments = typeArguments && ts.parenthesizeTypeParameters(typeArguments);
70286         return node;
70287     }
70288     ts.createTypeReferenceNode = createTypeReferenceNode;
70289     function updateTypeReferenceNode(node, typeName, typeArguments) {
70290         return node.typeName !== typeName
70291             || node.typeArguments !== typeArguments
70292             ? updateNode(createTypeReferenceNode(typeName, typeArguments), node)
70293             : node;
70294     }
70295     ts.updateTypeReferenceNode = updateTypeReferenceNode;
70296     function createFunctionTypeNode(typeParameters, parameters, type) {
70297         return createSignatureDeclaration(170 /* FunctionType */, typeParameters, parameters, type);
70298     }
70299     ts.createFunctionTypeNode = createFunctionTypeNode;
70300     function updateFunctionTypeNode(node, typeParameters, parameters, type) {
70301         return updateSignatureDeclaration(node, typeParameters, parameters, type);
70302     }
70303     ts.updateFunctionTypeNode = updateFunctionTypeNode;
70304     function createConstructorTypeNode(typeParameters, parameters, type) {
70305         return createSignatureDeclaration(171 /* ConstructorType */, typeParameters, parameters, type);
70306     }
70307     ts.createConstructorTypeNode = createConstructorTypeNode;
70308     function updateConstructorTypeNode(node, typeParameters, parameters, type) {
70309         return updateSignatureDeclaration(node, typeParameters, parameters, type);
70310     }
70311     ts.updateConstructorTypeNode = updateConstructorTypeNode;
70312     function createTypeQueryNode(exprName) {
70313         var node = createSynthesizedNode(172 /* TypeQuery */);
70314         node.exprName = exprName;
70315         return node;
70316     }
70317     ts.createTypeQueryNode = createTypeQueryNode;
70318     function updateTypeQueryNode(node, exprName) {
70319         return node.exprName !== exprName
70320             ? updateNode(createTypeQueryNode(exprName), node)
70321             : node;
70322     }
70323     ts.updateTypeQueryNode = updateTypeQueryNode;
70324     function createTypeLiteralNode(members) {
70325         var node = createSynthesizedNode(173 /* TypeLiteral */);
70326         node.members = createNodeArray(members);
70327         return node;
70328     }
70329     ts.createTypeLiteralNode = createTypeLiteralNode;
70330     function updateTypeLiteralNode(node, members) {
70331         return node.members !== members
70332             ? updateNode(createTypeLiteralNode(members), node)
70333             : node;
70334     }
70335     ts.updateTypeLiteralNode = updateTypeLiteralNode;
70336     function createArrayTypeNode(elementType) {
70337         var node = createSynthesizedNode(174 /* ArrayType */);
70338         node.elementType = ts.parenthesizeArrayTypeMember(elementType);
70339         return node;
70340     }
70341     ts.createArrayTypeNode = createArrayTypeNode;
70342     function updateArrayTypeNode(node, elementType) {
70343         return node.elementType !== elementType
70344             ? updateNode(createArrayTypeNode(elementType), node)
70345             : node;
70346     }
70347     ts.updateArrayTypeNode = updateArrayTypeNode;
70348     function createTupleTypeNode(elementTypes) {
70349         var node = createSynthesizedNode(175 /* TupleType */);
70350         node.elementTypes = createNodeArray(elementTypes);
70351         return node;
70352     }
70353     ts.createTupleTypeNode = createTupleTypeNode;
70354     function updateTupleTypeNode(node, elementTypes) {
70355         return node.elementTypes !== elementTypes
70356             ? updateNode(createTupleTypeNode(elementTypes), node)
70357             : node;
70358     }
70359     ts.updateTupleTypeNode = updateTupleTypeNode;
70360     function createOptionalTypeNode(type) {
70361         var node = createSynthesizedNode(176 /* OptionalType */);
70362         node.type = ts.parenthesizeArrayTypeMember(type);
70363         return node;
70364     }
70365     ts.createOptionalTypeNode = createOptionalTypeNode;
70366     function updateOptionalTypeNode(node, type) {
70367         return node.type !== type
70368             ? updateNode(createOptionalTypeNode(type), node)
70369             : node;
70370     }
70371     ts.updateOptionalTypeNode = updateOptionalTypeNode;
70372     function createRestTypeNode(type) {
70373         var node = createSynthesizedNode(177 /* RestType */);
70374         node.type = type;
70375         return node;
70376     }
70377     ts.createRestTypeNode = createRestTypeNode;
70378     function updateRestTypeNode(node, type) {
70379         return node.type !== type
70380             ? updateNode(createRestTypeNode(type), node)
70381             : node;
70382     }
70383     ts.updateRestTypeNode = updateRestTypeNode;
70384     function createUnionTypeNode(types) {
70385         return createUnionOrIntersectionTypeNode(178 /* UnionType */, types);
70386     }
70387     ts.createUnionTypeNode = createUnionTypeNode;
70388     function updateUnionTypeNode(node, types) {
70389         return updateUnionOrIntersectionTypeNode(node, types);
70390     }
70391     ts.updateUnionTypeNode = updateUnionTypeNode;
70392     function createIntersectionTypeNode(types) {
70393         return createUnionOrIntersectionTypeNode(179 /* IntersectionType */, types);
70394     }
70395     ts.createIntersectionTypeNode = createIntersectionTypeNode;
70396     function updateIntersectionTypeNode(node, types) {
70397         return updateUnionOrIntersectionTypeNode(node, types);
70398     }
70399     ts.updateIntersectionTypeNode = updateIntersectionTypeNode;
70400     function createUnionOrIntersectionTypeNode(kind, types) {
70401         var node = createSynthesizedNode(kind);
70402         node.types = ts.parenthesizeElementTypeMembers(types);
70403         return node;
70404     }
70405     ts.createUnionOrIntersectionTypeNode = createUnionOrIntersectionTypeNode;
70406     function updateUnionOrIntersectionTypeNode(node, types) {
70407         return node.types !== types
70408             ? updateNode(createUnionOrIntersectionTypeNode(node.kind, types), node)
70409             : node;
70410     }
70411     function createConditionalTypeNode(checkType, extendsType, trueType, falseType) {
70412         var node = createSynthesizedNode(180 /* ConditionalType */);
70413         node.checkType = ts.parenthesizeConditionalTypeMember(checkType);
70414         node.extendsType = ts.parenthesizeConditionalTypeMember(extendsType);
70415         node.trueType = trueType;
70416         node.falseType = falseType;
70417         return node;
70418     }
70419     ts.createConditionalTypeNode = createConditionalTypeNode;
70420     function updateConditionalTypeNode(node, checkType, extendsType, trueType, falseType) {
70421         return node.checkType !== checkType
70422             || node.extendsType !== extendsType
70423             || node.trueType !== trueType
70424             || node.falseType !== falseType
70425             ? updateNode(createConditionalTypeNode(checkType, extendsType, trueType, falseType), node)
70426             : node;
70427     }
70428     ts.updateConditionalTypeNode = updateConditionalTypeNode;
70429     function createInferTypeNode(typeParameter) {
70430         var node = createSynthesizedNode(181 /* InferType */);
70431         node.typeParameter = typeParameter;
70432         return node;
70433     }
70434     ts.createInferTypeNode = createInferTypeNode;
70435     function updateInferTypeNode(node, typeParameter) {
70436         return node.typeParameter !== typeParameter
70437             ? updateNode(createInferTypeNode(typeParameter), node)
70438             : node;
70439     }
70440     ts.updateInferTypeNode = updateInferTypeNode;
70441     function createImportTypeNode(argument, qualifier, typeArguments, isTypeOf) {
70442         var node = createSynthesizedNode(188 /* ImportType */);
70443         node.argument = argument;
70444         node.qualifier = qualifier;
70445         node.typeArguments = ts.parenthesizeTypeParameters(typeArguments);
70446         node.isTypeOf = isTypeOf;
70447         return node;
70448     }
70449     ts.createImportTypeNode = createImportTypeNode;
70450     function updateImportTypeNode(node, argument, qualifier, typeArguments, isTypeOf) {
70451         return node.argument !== argument
70452             || node.qualifier !== qualifier
70453             || node.typeArguments !== typeArguments
70454             || node.isTypeOf !== isTypeOf
70455             ? updateNode(createImportTypeNode(argument, qualifier, typeArguments, isTypeOf), node)
70456             : node;
70457     }
70458     ts.updateImportTypeNode = updateImportTypeNode;
70459     function createParenthesizedType(type) {
70460         var node = createSynthesizedNode(182 /* ParenthesizedType */);
70461         node.type = type;
70462         return node;
70463     }
70464     ts.createParenthesizedType = createParenthesizedType;
70465     function updateParenthesizedType(node, type) {
70466         return node.type !== type
70467             ? updateNode(createParenthesizedType(type), node)
70468             : node;
70469     }
70470     ts.updateParenthesizedType = updateParenthesizedType;
70471     function createThisTypeNode() {
70472         return createSynthesizedNode(183 /* ThisType */);
70473     }
70474     ts.createThisTypeNode = createThisTypeNode;
70475     function createTypeOperatorNode(operatorOrType, type) {
70476         var node = createSynthesizedNode(184 /* TypeOperator */);
70477         node.operator = typeof operatorOrType === "number" ? operatorOrType : 134 /* KeyOfKeyword */;
70478         node.type = ts.parenthesizeElementTypeMember(typeof operatorOrType === "number" ? type : operatorOrType);
70479         return node;
70480     }
70481     ts.createTypeOperatorNode = createTypeOperatorNode;
70482     function updateTypeOperatorNode(node, type) {
70483         return node.type !== type ? updateNode(createTypeOperatorNode(node.operator, type), node) : node;
70484     }
70485     ts.updateTypeOperatorNode = updateTypeOperatorNode;
70486     function createIndexedAccessTypeNode(objectType, indexType) {
70487         var node = createSynthesizedNode(185 /* IndexedAccessType */);
70488         node.objectType = ts.parenthesizeElementTypeMember(objectType);
70489         node.indexType = indexType;
70490         return node;
70491     }
70492     ts.createIndexedAccessTypeNode = createIndexedAccessTypeNode;
70493     function updateIndexedAccessTypeNode(node, objectType, indexType) {
70494         return node.objectType !== objectType
70495             || node.indexType !== indexType
70496             ? updateNode(createIndexedAccessTypeNode(objectType, indexType), node)
70497             : node;
70498     }
70499     ts.updateIndexedAccessTypeNode = updateIndexedAccessTypeNode;
70500     function createMappedTypeNode(readonlyToken, typeParameter, questionToken, type) {
70501         var node = createSynthesizedNode(186 /* MappedType */);
70502         node.readonlyToken = readonlyToken;
70503         node.typeParameter = typeParameter;
70504         node.questionToken = questionToken;
70505         node.type = type;
70506         return node;
70507     }
70508     ts.createMappedTypeNode = createMappedTypeNode;
70509     function updateMappedTypeNode(node, readonlyToken, typeParameter, questionToken, type) {
70510         return node.readonlyToken !== readonlyToken
70511             || node.typeParameter !== typeParameter
70512             || node.questionToken !== questionToken
70513             || node.type !== type
70514             ? updateNode(createMappedTypeNode(readonlyToken, typeParameter, questionToken, type), node)
70515             : node;
70516     }
70517     ts.updateMappedTypeNode = updateMappedTypeNode;
70518     function createLiteralTypeNode(literal) {
70519         var node = createSynthesizedNode(187 /* LiteralType */);
70520         node.literal = literal;
70521         return node;
70522     }
70523     ts.createLiteralTypeNode = createLiteralTypeNode;
70524     function updateLiteralTypeNode(node, literal) {
70525         return node.literal !== literal
70526             ? updateNode(createLiteralTypeNode(literal), node)
70527             : node;
70528     }
70529     ts.updateLiteralTypeNode = updateLiteralTypeNode;
70530     // Binding Patterns
70531     function createObjectBindingPattern(elements) {
70532         var node = createSynthesizedNode(189 /* ObjectBindingPattern */);
70533         node.elements = createNodeArray(elements);
70534         return node;
70535     }
70536     ts.createObjectBindingPattern = createObjectBindingPattern;
70537     function updateObjectBindingPattern(node, elements) {
70538         return node.elements !== elements
70539             ? updateNode(createObjectBindingPattern(elements), node)
70540             : node;
70541     }
70542     ts.updateObjectBindingPattern = updateObjectBindingPattern;
70543     function createArrayBindingPattern(elements) {
70544         var node = createSynthesizedNode(190 /* ArrayBindingPattern */);
70545         node.elements = createNodeArray(elements);
70546         return node;
70547     }
70548     ts.createArrayBindingPattern = createArrayBindingPattern;
70549     function updateArrayBindingPattern(node, elements) {
70550         return node.elements !== elements
70551             ? updateNode(createArrayBindingPattern(elements), node)
70552             : node;
70553     }
70554     ts.updateArrayBindingPattern = updateArrayBindingPattern;
70555     function createBindingElement(dotDotDotToken, propertyName, name, initializer) {
70556         var node = createSynthesizedNode(191 /* BindingElement */);
70557         node.dotDotDotToken = dotDotDotToken;
70558         node.propertyName = asName(propertyName);
70559         node.name = asName(name);
70560         node.initializer = initializer;
70561         return node;
70562     }
70563     ts.createBindingElement = createBindingElement;
70564     function updateBindingElement(node, dotDotDotToken, propertyName, name, initializer) {
70565         return node.propertyName !== propertyName
70566             || node.dotDotDotToken !== dotDotDotToken
70567             || node.name !== name
70568             || node.initializer !== initializer
70569             ? updateNode(createBindingElement(dotDotDotToken, propertyName, name, initializer), node)
70570             : node;
70571     }
70572     ts.updateBindingElement = updateBindingElement;
70573     // Expression
70574     function createArrayLiteral(elements, multiLine) {
70575         var node = createSynthesizedNode(192 /* ArrayLiteralExpression */);
70576         node.elements = ts.parenthesizeListElements(createNodeArray(elements));
70577         if (multiLine)
70578             node.multiLine = true;
70579         return node;
70580     }
70581     ts.createArrayLiteral = createArrayLiteral;
70582     function updateArrayLiteral(node, elements) {
70583         return node.elements !== elements
70584             ? updateNode(createArrayLiteral(elements, node.multiLine), node)
70585             : node;
70586     }
70587     ts.updateArrayLiteral = updateArrayLiteral;
70588     function createObjectLiteral(properties, multiLine) {
70589         var node = createSynthesizedNode(193 /* ObjectLiteralExpression */);
70590         node.properties = createNodeArray(properties);
70591         if (multiLine)
70592             node.multiLine = true;
70593         return node;
70594     }
70595     ts.createObjectLiteral = createObjectLiteral;
70596     function updateObjectLiteral(node, properties) {
70597         return node.properties !== properties
70598             ? updateNode(createObjectLiteral(properties, node.multiLine), node)
70599             : node;
70600     }
70601     ts.updateObjectLiteral = updateObjectLiteral;
70602     function createPropertyAccess(expression, name) {
70603         var node = createSynthesizedNode(194 /* PropertyAccessExpression */);
70604         node.expression = ts.parenthesizeForAccess(expression);
70605         node.name = asName(name);
70606         setEmitFlags(node, 131072 /* NoIndentation */);
70607         return node;
70608     }
70609     ts.createPropertyAccess = createPropertyAccess;
70610     function updatePropertyAccess(node, expression, name) {
70611         if (ts.isPropertyAccessChain(node)) {
70612             return updatePropertyAccessChain(node, expression, node.questionDotToken, ts.cast(name, ts.isIdentifier));
70613         }
70614         // Because we are updating existed propertyAccess we want to inherit its emitFlags
70615         // instead of using the default from createPropertyAccess
70616         return node.expression !== expression
70617             || node.name !== name
70618             ? updateNode(setEmitFlags(createPropertyAccess(expression, name), ts.getEmitFlags(node)), node)
70619             : node;
70620     }
70621     ts.updatePropertyAccess = updatePropertyAccess;
70622     function createPropertyAccessChain(expression, questionDotToken, name) {
70623         var node = createSynthesizedNode(194 /* PropertyAccessExpression */);
70624         node.flags |= 32 /* OptionalChain */;
70625         node.expression = ts.parenthesizeForAccess(expression);
70626         node.questionDotToken = questionDotToken;
70627         node.name = asName(name);
70628         setEmitFlags(node, 131072 /* NoIndentation */);
70629         return node;
70630     }
70631     ts.createPropertyAccessChain = createPropertyAccessChain;
70632     function updatePropertyAccessChain(node, expression, questionDotToken, name) {
70633         ts.Debug.assert(!!(node.flags & 32 /* OptionalChain */), "Cannot update a PropertyAccessExpression using updatePropertyAccessChain. Use updatePropertyAccess instead.");
70634         // Because we are updating an existing PropertyAccessChain we want to inherit its emitFlags
70635         // instead of using the default from createPropertyAccess
70636         return node.expression !== expression
70637             || node.questionDotToken !== questionDotToken
70638             || node.name !== name
70639             ? updateNode(setEmitFlags(createPropertyAccessChain(expression, questionDotToken, name), ts.getEmitFlags(node)), node)
70640             : node;
70641     }
70642     ts.updatePropertyAccessChain = updatePropertyAccessChain;
70643     function createElementAccess(expression, index) {
70644         var node = createSynthesizedNode(195 /* ElementAccessExpression */);
70645         node.expression = ts.parenthesizeForAccess(expression);
70646         node.argumentExpression = asExpression(index);
70647         return node;
70648     }
70649     ts.createElementAccess = createElementAccess;
70650     function updateElementAccess(node, expression, argumentExpression) {
70651         if (ts.isOptionalChain(node)) {
70652             return updateElementAccessChain(node, expression, node.questionDotToken, argumentExpression);
70653         }
70654         return node.expression !== expression
70655             || node.argumentExpression !== argumentExpression
70656             ? updateNode(createElementAccess(expression, argumentExpression), node)
70657             : node;
70658     }
70659     ts.updateElementAccess = updateElementAccess;
70660     function createElementAccessChain(expression, questionDotToken, index) {
70661         var node = createSynthesizedNode(195 /* ElementAccessExpression */);
70662         node.flags |= 32 /* OptionalChain */;
70663         node.expression = ts.parenthesizeForAccess(expression);
70664         node.questionDotToken = questionDotToken;
70665         node.argumentExpression = asExpression(index);
70666         return node;
70667     }
70668     ts.createElementAccessChain = createElementAccessChain;
70669     function updateElementAccessChain(node, expression, questionDotToken, argumentExpression) {
70670         ts.Debug.assert(!!(node.flags & 32 /* OptionalChain */), "Cannot update an ElementAccessExpression using updateElementAccessChain. Use updateElementAccess instead.");
70671         return node.expression !== expression
70672             || node.questionDotToken !== questionDotToken
70673             || node.argumentExpression !== argumentExpression
70674             ? updateNode(createElementAccessChain(expression, questionDotToken, argumentExpression), node)
70675             : node;
70676     }
70677     ts.updateElementAccessChain = updateElementAccessChain;
70678     function createCall(expression, typeArguments, argumentsArray) {
70679         var node = createSynthesizedNode(196 /* CallExpression */);
70680         node.expression = ts.parenthesizeForAccess(expression);
70681         node.typeArguments = asNodeArray(typeArguments);
70682         node.arguments = ts.parenthesizeListElements(createNodeArray(argumentsArray));
70683         return node;
70684     }
70685     ts.createCall = createCall;
70686     function updateCall(node, expression, typeArguments, argumentsArray) {
70687         if (ts.isOptionalChain(node)) {
70688             return updateCallChain(node, expression, node.questionDotToken, typeArguments, argumentsArray);
70689         }
70690         return node.expression !== expression
70691             || node.typeArguments !== typeArguments
70692             || node.arguments !== argumentsArray
70693             ? updateNode(createCall(expression, typeArguments, argumentsArray), node)
70694             : node;
70695     }
70696     ts.updateCall = updateCall;
70697     function createCallChain(expression, questionDotToken, typeArguments, argumentsArray) {
70698         var node = createSynthesizedNode(196 /* CallExpression */);
70699         node.flags |= 32 /* OptionalChain */;
70700         node.expression = ts.parenthesizeForAccess(expression);
70701         node.questionDotToken = questionDotToken;
70702         node.typeArguments = asNodeArray(typeArguments);
70703         node.arguments = ts.parenthesizeListElements(createNodeArray(argumentsArray));
70704         return node;
70705     }
70706     ts.createCallChain = createCallChain;
70707     function updateCallChain(node, expression, questionDotToken, typeArguments, argumentsArray) {
70708         ts.Debug.assert(!!(node.flags & 32 /* OptionalChain */), "Cannot update a CallExpression using updateCallChain. Use updateCall instead.");
70709         return node.expression !== expression
70710             || node.questionDotToken !== questionDotToken
70711             || node.typeArguments !== typeArguments
70712             || node.arguments !== argumentsArray
70713             ? updateNode(createCallChain(expression, questionDotToken, typeArguments, argumentsArray), node)
70714             : node;
70715     }
70716     ts.updateCallChain = updateCallChain;
70717     function createNew(expression, typeArguments, argumentsArray) {
70718         var node = createSynthesizedNode(197 /* NewExpression */);
70719         node.expression = ts.parenthesizeForNew(expression);
70720         node.typeArguments = asNodeArray(typeArguments);
70721         node.arguments = argumentsArray ? ts.parenthesizeListElements(createNodeArray(argumentsArray)) : undefined;
70722         return node;
70723     }
70724     ts.createNew = createNew;
70725     function updateNew(node, expression, typeArguments, argumentsArray) {
70726         return node.expression !== expression
70727             || node.typeArguments !== typeArguments
70728             || node.arguments !== argumentsArray
70729             ? updateNode(createNew(expression, typeArguments, argumentsArray), node)
70730             : node;
70731     }
70732     ts.updateNew = updateNew;
70733     function createTaggedTemplate(tag, typeArgumentsOrTemplate, template) {
70734         var node = createSynthesizedNode(198 /* TaggedTemplateExpression */);
70735         node.tag = ts.parenthesizeForAccess(tag);
70736         if (template) {
70737             node.typeArguments = asNodeArray(typeArgumentsOrTemplate);
70738             node.template = template;
70739         }
70740         else {
70741             node.typeArguments = undefined;
70742             node.template = typeArgumentsOrTemplate;
70743         }
70744         return node;
70745     }
70746     ts.createTaggedTemplate = createTaggedTemplate;
70747     function updateTaggedTemplate(node, tag, typeArgumentsOrTemplate, template) {
70748         return node.tag !== tag
70749             || (template
70750                 ? node.typeArguments !== typeArgumentsOrTemplate || node.template !== template
70751                 : node.typeArguments !== undefined || node.template !== typeArgumentsOrTemplate)
70752             ? updateNode(createTaggedTemplate(tag, typeArgumentsOrTemplate, template), node)
70753             : node;
70754     }
70755     ts.updateTaggedTemplate = updateTaggedTemplate;
70756     function createTypeAssertion(type, expression) {
70757         var node = createSynthesizedNode(199 /* TypeAssertionExpression */);
70758         node.type = type;
70759         node.expression = ts.parenthesizePrefixOperand(expression);
70760         return node;
70761     }
70762     ts.createTypeAssertion = createTypeAssertion;
70763     function updateTypeAssertion(node, type, expression) {
70764         return node.type !== type
70765             || node.expression !== expression
70766             ? updateNode(createTypeAssertion(type, expression), node)
70767             : node;
70768     }
70769     ts.updateTypeAssertion = updateTypeAssertion;
70770     function createParen(expression) {
70771         var node = createSynthesizedNode(200 /* ParenthesizedExpression */);
70772         node.expression = expression;
70773         return node;
70774     }
70775     ts.createParen = createParen;
70776     function updateParen(node, expression) {
70777         return node.expression !== expression
70778             ? updateNode(createParen(expression), node)
70779             : node;
70780     }
70781     ts.updateParen = updateParen;
70782     function createFunctionExpression(modifiers, asteriskToken, name, typeParameters, parameters, type, body) {
70783         var node = createSynthesizedNode(201 /* FunctionExpression */);
70784         node.modifiers = asNodeArray(modifiers);
70785         node.asteriskToken = asteriskToken;
70786         node.name = asName(name);
70787         node.typeParameters = asNodeArray(typeParameters);
70788         node.parameters = createNodeArray(parameters);
70789         node.type = type;
70790         node.body = body;
70791         return node;
70792     }
70793     ts.createFunctionExpression = createFunctionExpression;
70794     function updateFunctionExpression(node, modifiers, asteriskToken, name, typeParameters, parameters, type, body) {
70795         return node.name !== name
70796             || node.modifiers !== modifiers
70797             || node.asteriskToken !== asteriskToken
70798             || node.typeParameters !== typeParameters
70799             || node.parameters !== parameters
70800             || node.type !== type
70801             || node.body !== body
70802             ? updateNode(createFunctionExpression(modifiers, asteriskToken, name, typeParameters, parameters, type, body), node)
70803             : node;
70804     }
70805     ts.updateFunctionExpression = updateFunctionExpression;
70806     function createArrowFunction(modifiers, typeParameters, parameters, type, equalsGreaterThanToken, body) {
70807         var node = createSynthesizedNode(202 /* ArrowFunction */);
70808         node.modifiers = asNodeArray(modifiers);
70809         node.typeParameters = asNodeArray(typeParameters);
70810         node.parameters = createNodeArray(parameters);
70811         node.type = type;
70812         node.equalsGreaterThanToken = equalsGreaterThanToken || createToken(38 /* EqualsGreaterThanToken */);
70813         node.body = ts.parenthesizeConciseBody(body);
70814         return node;
70815     }
70816     ts.createArrowFunction = createArrowFunction;
70817     function updateArrowFunction(node, modifiers, typeParameters, parameters, type, equalsGreaterThanToken, body) {
70818         return node.modifiers !== modifiers
70819             || node.typeParameters !== typeParameters
70820             || node.parameters !== parameters
70821             || node.type !== type
70822             || node.equalsGreaterThanToken !== equalsGreaterThanToken
70823             || node.body !== body
70824             ? updateNode(createArrowFunction(modifiers, typeParameters, parameters, type, equalsGreaterThanToken, body), node)
70825             : node;
70826     }
70827     ts.updateArrowFunction = updateArrowFunction;
70828     function createDelete(expression) {
70829         var node = createSynthesizedNode(203 /* DeleteExpression */);
70830         node.expression = ts.parenthesizePrefixOperand(expression);
70831         return node;
70832     }
70833     ts.createDelete = createDelete;
70834     function updateDelete(node, expression) {
70835         return node.expression !== expression
70836             ? updateNode(createDelete(expression), node)
70837             : node;
70838     }
70839     ts.updateDelete = updateDelete;
70840     function createTypeOf(expression) {
70841         var node = createSynthesizedNode(204 /* TypeOfExpression */);
70842         node.expression = ts.parenthesizePrefixOperand(expression);
70843         return node;
70844     }
70845     ts.createTypeOf = createTypeOf;
70846     function updateTypeOf(node, expression) {
70847         return node.expression !== expression
70848             ? updateNode(createTypeOf(expression), node)
70849             : node;
70850     }
70851     ts.updateTypeOf = updateTypeOf;
70852     function createVoid(expression) {
70853         var node = createSynthesizedNode(205 /* VoidExpression */);
70854         node.expression = ts.parenthesizePrefixOperand(expression);
70855         return node;
70856     }
70857     ts.createVoid = createVoid;
70858     function updateVoid(node, expression) {
70859         return node.expression !== expression
70860             ? updateNode(createVoid(expression), node)
70861             : node;
70862     }
70863     ts.updateVoid = updateVoid;
70864     function createAwait(expression) {
70865         var node = createSynthesizedNode(206 /* AwaitExpression */);
70866         node.expression = ts.parenthesizePrefixOperand(expression);
70867         return node;
70868     }
70869     ts.createAwait = createAwait;
70870     function updateAwait(node, expression) {
70871         return node.expression !== expression
70872             ? updateNode(createAwait(expression), node)
70873             : node;
70874     }
70875     ts.updateAwait = updateAwait;
70876     function createPrefix(operator, operand) {
70877         var node = createSynthesizedNode(207 /* PrefixUnaryExpression */);
70878         node.operator = operator;
70879         node.operand = ts.parenthesizePrefixOperand(operand);
70880         return node;
70881     }
70882     ts.createPrefix = createPrefix;
70883     function updatePrefix(node, operand) {
70884         return node.operand !== operand
70885             ? updateNode(createPrefix(node.operator, operand), node)
70886             : node;
70887     }
70888     ts.updatePrefix = updatePrefix;
70889     function createPostfix(operand, operator) {
70890         var node = createSynthesizedNode(208 /* PostfixUnaryExpression */);
70891         node.operand = ts.parenthesizePostfixOperand(operand);
70892         node.operator = operator;
70893         return node;
70894     }
70895     ts.createPostfix = createPostfix;
70896     function updatePostfix(node, operand) {
70897         return node.operand !== operand
70898             ? updateNode(createPostfix(operand, node.operator), node)
70899             : node;
70900     }
70901     ts.updatePostfix = updatePostfix;
70902     function createBinary(left, operator, right) {
70903         var node = createSynthesizedNode(209 /* BinaryExpression */);
70904         var operatorToken = asToken(operator);
70905         var operatorKind = operatorToken.kind;
70906         node.left = ts.parenthesizeBinaryOperand(operatorKind, left, /*isLeftSideOfBinary*/ true, /*leftOperand*/ undefined);
70907         node.operatorToken = operatorToken;
70908         node.right = ts.parenthesizeBinaryOperand(operatorKind, right, /*isLeftSideOfBinary*/ false, node.left);
70909         return node;
70910     }
70911     ts.createBinary = createBinary;
70912     function updateBinary(node, left, right, operator) {
70913         return node.left !== left
70914             || node.right !== right
70915             ? updateNode(createBinary(left, operator || node.operatorToken, right), node)
70916             : node;
70917     }
70918     ts.updateBinary = updateBinary;
70919     function createConditional(condition, questionTokenOrWhenTrue, whenTrueOrWhenFalse, colonToken, whenFalse) {
70920         var node = createSynthesizedNode(210 /* ConditionalExpression */);
70921         node.condition = ts.parenthesizeForConditionalHead(condition);
70922         node.questionToken = whenFalse ? questionTokenOrWhenTrue : createToken(57 /* QuestionToken */);
70923         node.whenTrue = ts.parenthesizeSubexpressionOfConditionalExpression(whenFalse ? whenTrueOrWhenFalse : questionTokenOrWhenTrue);
70924         node.colonToken = whenFalse ? colonToken : createToken(58 /* ColonToken */);
70925         node.whenFalse = ts.parenthesizeSubexpressionOfConditionalExpression(whenFalse ? whenFalse : whenTrueOrWhenFalse);
70926         return node;
70927     }
70928     ts.createConditional = createConditional;
70929     function updateConditional(node, condition, questionToken, whenTrue, colonToken, whenFalse) {
70930         return node.condition !== condition
70931             || node.questionToken !== questionToken
70932             || node.whenTrue !== whenTrue
70933             || node.colonToken !== colonToken
70934             || node.whenFalse !== whenFalse
70935             ? updateNode(createConditional(condition, questionToken, whenTrue, colonToken, whenFalse), node)
70936             : node;
70937     }
70938     ts.updateConditional = updateConditional;
70939     function createTemplateExpression(head, templateSpans) {
70940         var node = createSynthesizedNode(211 /* TemplateExpression */);
70941         node.head = head;
70942         node.templateSpans = createNodeArray(templateSpans);
70943         return node;
70944     }
70945     ts.createTemplateExpression = createTemplateExpression;
70946     function updateTemplateExpression(node, head, templateSpans) {
70947         return node.head !== head
70948             || node.templateSpans !== templateSpans
70949             ? updateNode(createTemplateExpression(head, templateSpans), node)
70950             : node;
70951     }
70952     ts.updateTemplateExpression = updateTemplateExpression;
70953     var rawTextScanner;
70954     var invalidValueSentinel = {};
70955     function getCookedText(kind, rawText) {
70956         if (!rawTextScanner) {
70957             rawTextScanner = ts.createScanner(99 /* Latest */, /*skipTrivia*/ false, 0 /* Standard */);
70958         }
70959         switch (kind) {
70960             case 14 /* NoSubstitutionTemplateLiteral */:
70961                 rawTextScanner.setText("`" + rawText + "`");
70962                 break;
70963             case 15 /* TemplateHead */:
70964                 rawTextScanner.setText("`" + rawText + "${");
70965                 break;
70966             case 16 /* TemplateMiddle */:
70967                 rawTextScanner.setText("}" + rawText + "${");
70968                 break;
70969             case 17 /* TemplateTail */:
70970                 rawTextScanner.setText("}" + rawText + "`");
70971                 break;
70972         }
70973         var token = rawTextScanner.scan();
70974         if (token === 23 /* CloseBracketToken */) {
70975             token = rawTextScanner.reScanTemplateToken(/* isTaggedTemplate */ false);
70976         }
70977         if (rawTextScanner.isUnterminated()) {
70978             rawTextScanner.setText(undefined);
70979             return invalidValueSentinel;
70980         }
70981         var tokenValue;
70982         switch (token) {
70983             case 14 /* NoSubstitutionTemplateLiteral */:
70984             case 15 /* TemplateHead */:
70985             case 16 /* TemplateMiddle */:
70986             case 17 /* TemplateTail */:
70987                 tokenValue = rawTextScanner.getTokenValue();
70988                 break;
70989         }
70990         if (rawTextScanner.scan() !== 1 /* EndOfFileToken */) {
70991             rawTextScanner.setText(undefined);
70992             return invalidValueSentinel;
70993         }
70994         rawTextScanner.setText(undefined);
70995         return tokenValue;
70996     }
70997     function createTemplateLiteralLikeNode(kind, text, rawText) {
70998         var node = createSynthesizedNode(kind);
70999         node.text = text;
71000         if (rawText === undefined || text === rawText) {
71001             node.rawText = rawText;
71002         }
71003         else {
71004             var cooked = getCookedText(kind, rawText);
71005             if (typeof cooked === "object") {
71006                 return ts.Debug.fail("Invalid raw text");
71007             }
71008             ts.Debug.assert(text === cooked, "Expected argument 'text' to be the normalized (i.e. 'cooked') version of argument 'rawText'.");
71009             node.rawText = rawText;
71010         }
71011         return node;
71012     }
71013     function createTemplateHead(text, rawText) {
71014         var node = createTemplateLiteralLikeNode(15 /* TemplateHead */, text, rawText);
71015         node.text = text;
71016         return node;
71017     }
71018     ts.createTemplateHead = createTemplateHead;
71019     function createTemplateMiddle(text, rawText) {
71020         var node = createTemplateLiteralLikeNode(16 /* TemplateMiddle */, text, rawText);
71021         node.text = text;
71022         return node;
71023     }
71024     ts.createTemplateMiddle = createTemplateMiddle;
71025     function createTemplateTail(text, rawText) {
71026         var node = createTemplateLiteralLikeNode(17 /* TemplateTail */, text, rawText);
71027         node.text = text;
71028         return node;
71029     }
71030     ts.createTemplateTail = createTemplateTail;
71031     function createNoSubstitutionTemplateLiteral(text, rawText) {
71032         var node = createTemplateLiteralLikeNode(14 /* NoSubstitutionTemplateLiteral */, text, rawText);
71033         return node;
71034     }
71035     ts.createNoSubstitutionTemplateLiteral = createNoSubstitutionTemplateLiteral;
71036     function createYield(asteriskTokenOrExpression, expression) {
71037         var asteriskToken = asteriskTokenOrExpression && asteriskTokenOrExpression.kind === 41 /* AsteriskToken */ ? asteriskTokenOrExpression : undefined;
71038         expression = asteriskTokenOrExpression && asteriskTokenOrExpression.kind !== 41 /* AsteriskToken */ ? asteriskTokenOrExpression : expression;
71039         var node = createSynthesizedNode(212 /* YieldExpression */);
71040         node.asteriskToken = asteriskToken;
71041         node.expression = expression && ts.parenthesizeExpressionForList(expression);
71042         return node;
71043     }
71044     ts.createYield = createYield;
71045     function updateYield(node, asteriskToken, expression) {
71046         return node.expression !== expression
71047             || node.asteriskToken !== asteriskToken
71048             ? updateNode(createYield(asteriskToken, expression), node)
71049             : node;
71050     }
71051     ts.updateYield = updateYield;
71052     function createSpread(expression) {
71053         var node = createSynthesizedNode(213 /* SpreadElement */);
71054         node.expression = ts.parenthesizeExpressionForList(expression);
71055         return node;
71056     }
71057     ts.createSpread = createSpread;
71058     function updateSpread(node, expression) {
71059         return node.expression !== expression
71060             ? updateNode(createSpread(expression), node)
71061             : node;
71062     }
71063     ts.updateSpread = updateSpread;
71064     function createClassExpression(modifiers, name, typeParameters, heritageClauses, members) {
71065         var node = createSynthesizedNode(214 /* ClassExpression */);
71066         node.decorators = undefined;
71067         node.modifiers = asNodeArray(modifiers);
71068         node.name = asName(name);
71069         node.typeParameters = asNodeArray(typeParameters);
71070         node.heritageClauses = asNodeArray(heritageClauses);
71071         node.members = createNodeArray(members);
71072         return node;
71073     }
71074     ts.createClassExpression = createClassExpression;
71075     function updateClassExpression(node, modifiers, name, typeParameters, heritageClauses, members) {
71076         return node.modifiers !== modifiers
71077             || node.name !== name
71078             || node.typeParameters !== typeParameters
71079             || node.heritageClauses !== heritageClauses
71080             || node.members !== members
71081             ? updateNode(createClassExpression(modifiers, name, typeParameters, heritageClauses, members), node)
71082             : node;
71083     }
71084     ts.updateClassExpression = updateClassExpression;
71085     function createOmittedExpression() {
71086         return createSynthesizedNode(215 /* OmittedExpression */);
71087     }
71088     ts.createOmittedExpression = createOmittedExpression;
71089     function createExpressionWithTypeArguments(typeArguments, expression) {
71090         var node = createSynthesizedNode(216 /* ExpressionWithTypeArguments */);
71091         node.expression = ts.parenthesizeForAccess(expression);
71092         node.typeArguments = asNodeArray(typeArguments);
71093         return node;
71094     }
71095     ts.createExpressionWithTypeArguments = createExpressionWithTypeArguments;
71096     function updateExpressionWithTypeArguments(node, typeArguments, expression) {
71097         return node.typeArguments !== typeArguments
71098             || node.expression !== expression
71099             ? updateNode(createExpressionWithTypeArguments(typeArguments, expression), node)
71100             : node;
71101     }
71102     ts.updateExpressionWithTypeArguments = updateExpressionWithTypeArguments;
71103     function createAsExpression(expression, type) {
71104         var node = createSynthesizedNode(217 /* AsExpression */);
71105         node.expression = expression;
71106         node.type = type;
71107         return node;
71108     }
71109     ts.createAsExpression = createAsExpression;
71110     function updateAsExpression(node, expression, type) {
71111         return node.expression !== expression
71112             || node.type !== type
71113             ? updateNode(createAsExpression(expression, type), node)
71114             : node;
71115     }
71116     ts.updateAsExpression = updateAsExpression;
71117     function createNonNullExpression(expression) {
71118         var node = createSynthesizedNode(218 /* NonNullExpression */);
71119         node.expression = ts.parenthesizeForAccess(expression);
71120         return node;
71121     }
71122     ts.createNonNullExpression = createNonNullExpression;
71123     function updateNonNullExpression(node, expression) {
71124         if (ts.isNonNullChain(node)) {
71125             return updateNonNullChain(node, expression);
71126         }
71127         return node.expression !== expression
71128             ? updateNode(createNonNullExpression(expression), node)
71129             : node;
71130     }
71131     ts.updateNonNullExpression = updateNonNullExpression;
71132     function createNonNullChain(expression) {
71133         var node = createSynthesizedNode(218 /* NonNullExpression */);
71134         node.flags |= 32 /* OptionalChain */;
71135         node.expression = ts.parenthesizeForAccess(expression);
71136         return node;
71137     }
71138     ts.createNonNullChain = createNonNullChain;
71139     function updateNonNullChain(node, expression) {
71140         ts.Debug.assert(!!(node.flags & 32 /* OptionalChain */), "Cannot update a NonNullExpression using updateNonNullChain. Use updateNonNullExpression instead.");
71141         return node.expression !== expression
71142             ? updateNode(createNonNullChain(expression), node)
71143             : node;
71144     }
71145     ts.updateNonNullChain = updateNonNullChain;
71146     function createMetaProperty(keywordToken, name) {
71147         var node = createSynthesizedNode(219 /* MetaProperty */);
71148         node.keywordToken = keywordToken;
71149         node.name = name;
71150         return node;
71151     }
71152     ts.createMetaProperty = createMetaProperty;
71153     function updateMetaProperty(node, name) {
71154         return node.name !== name
71155             ? updateNode(createMetaProperty(node.keywordToken, name), node)
71156             : node;
71157     }
71158     ts.updateMetaProperty = updateMetaProperty;
71159     // Misc
71160     function createTemplateSpan(expression, literal) {
71161         var node = createSynthesizedNode(221 /* TemplateSpan */);
71162         node.expression = expression;
71163         node.literal = literal;
71164         return node;
71165     }
71166     ts.createTemplateSpan = createTemplateSpan;
71167     function updateTemplateSpan(node, expression, literal) {
71168         return node.expression !== expression
71169             || node.literal !== literal
71170             ? updateNode(createTemplateSpan(expression, literal), node)
71171             : node;
71172     }
71173     ts.updateTemplateSpan = updateTemplateSpan;
71174     function createSemicolonClassElement() {
71175         return createSynthesizedNode(222 /* SemicolonClassElement */);
71176     }
71177     ts.createSemicolonClassElement = createSemicolonClassElement;
71178     // Element
71179     function createBlock(statements, multiLine) {
71180         var block = createSynthesizedNode(223 /* Block */);
71181         block.statements = createNodeArray(statements);
71182         if (multiLine)
71183             block.multiLine = multiLine;
71184         return block;
71185     }
71186     ts.createBlock = createBlock;
71187     function updateBlock(node, statements) {
71188         return node.statements !== statements
71189             ? updateNode(createBlock(statements, node.multiLine), node)
71190             : node;
71191     }
71192     ts.updateBlock = updateBlock;
71193     function createVariableStatement(modifiers, declarationList) {
71194         var node = createSynthesizedNode(225 /* VariableStatement */);
71195         node.decorators = undefined;
71196         node.modifiers = asNodeArray(modifiers);
71197         node.declarationList = ts.isArray(declarationList) ? createVariableDeclarationList(declarationList) : declarationList;
71198         return node;
71199     }
71200     ts.createVariableStatement = createVariableStatement;
71201     function updateVariableStatement(node, modifiers, declarationList) {
71202         return node.modifiers !== modifiers
71203             || node.declarationList !== declarationList
71204             ? updateNode(createVariableStatement(modifiers, declarationList), node)
71205             : node;
71206     }
71207     ts.updateVariableStatement = updateVariableStatement;
71208     function createEmptyStatement() {
71209         return createSynthesizedNode(224 /* EmptyStatement */);
71210     }
71211     ts.createEmptyStatement = createEmptyStatement;
71212     function createExpressionStatement(expression) {
71213         var node = createSynthesizedNode(226 /* ExpressionStatement */);
71214         node.expression = ts.parenthesizeExpressionForExpressionStatement(expression);
71215         return node;
71216     }
71217     ts.createExpressionStatement = createExpressionStatement;
71218     function updateExpressionStatement(node, expression) {
71219         return node.expression !== expression
71220             ? updateNode(createExpressionStatement(expression), node)
71221             : node;
71222     }
71223     ts.updateExpressionStatement = updateExpressionStatement;
71224     /** @deprecated Use `createExpressionStatement` instead.  */
71225     ts.createStatement = createExpressionStatement;
71226     /** @deprecated Use `updateExpressionStatement` instead.  */
71227     ts.updateStatement = updateExpressionStatement;
71228     function createIf(expression, thenStatement, elseStatement) {
71229         var node = createSynthesizedNode(227 /* IfStatement */);
71230         node.expression = expression;
71231         node.thenStatement = asEmbeddedStatement(thenStatement);
71232         node.elseStatement = asEmbeddedStatement(elseStatement);
71233         return node;
71234     }
71235     ts.createIf = createIf;
71236     function updateIf(node, expression, thenStatement, elseStatement) {
71237         return node.expression !== expression
71238             || node.thenStatement !== thenStatement
71239             || node.elseStatement !== elseStatement
71240             ? updateNode(createIf(expression, thenStatement, elseStatement), node)
71241             : node;
71242     }
71243     ts.updateIf = updateIf;
71244     function createDo(statement, expression) {
71245         var node = createSynthesizedNode(228 /* DoStatement */);
71246         node.statement = asEmbeddedStatement(statement);
71247         node.expression = expression;
71248         return node;
71249     }
71250     ts.createDo = createDo;
71251     function updateDo(node, statement, expression) {
71252         return node.statement !== statement
71253             || node.expression !== expression
71254             ? updateNode(createDo(statement, expression), node)
71255             : node;
71256     }
71257     ts.updateDo = updateDo;
71258     function createWhile(expression, statement) {
71259         var node = createSynthesizedNode(229 /* WhileStatement */);
71260         node.expression = expression;
71261         node.statement = asEmbeddedStatement(statement);
71262         return node;
71263     }
71264     ts.createWhile = createWhile;
71265     function updateWhile(node, expression, statement) {
71266         return node.expression !== expression
71267             || node.statement !== statement
71268             ? updateNode(createWhile(expression, statement), node)
71269             : node;
71270     }
71271     ts.updateWhile = updateWhile;
71272     function createFor(initializer, condition, incrementor, statement) {
71273         var node = createSynthesizedNode(230 /* ForStatement */);
71274         node.initializer = initializer;
71275         node.condition = condition;
71276         node.incrementor = incrementor;
71277         node.statement = asEmbeddedStatement(statement);
71278         return node;
71279     }
71280     ts.createFor = createFor;
71281     function updateFor(node, initializer, condition, incrementor, statement) {
71282         return node.initializer !== initializer
71283             || node.condition !== condition
71284             || node.incrementor !== incrementor
71285             || node.statement !== statement
71286             ? updateNode(createFor(initializer, condition, incrementor, statement), node)
71287             : node;
71288     }
71289     ts.updateFor = updateFor;
71290     function createForIn(initializer, expression, statement) {
71291         var node = createSynthesizedNode(231 /* ForInStatement */);
71292         node.initializer = initializer;
71293         node.expression = expression;
71294         node.statement = asEmbeddedStatement(statement);
71295         return node;
71296     }
71297     ts.createForIn = createForIn;
71298     function updateForIn(node, initializer, expression, statement) {
71299         return node.initializer !== initializer
71300             || node.expression !== expression
71301             || node.statement !== statement
71302             ? updateNode(createForIn(initializer, expression, statement), node)
71303             : node;
71304     }
71305     ts.updateForIn = updateForIn;
71306     function createForOf(awaitModifier, initializer, expression, statement) {
71307         var node = createSynthesizedNode(232 /* ForOfStatement */);
71308         node.awaitModifier = awaitModifier;
71309         node.initializer = initializer;
71310         node.expression = ts.isCommaSequence(expression) ? createParen(expression) : expression;
71311         node.statement = asEmbeddedStatement(statement);
71312         return node;
71313     }
71314     ts.createForOf = createForOf;
71315     function updateForOf(node, awaitModifier, initializer, expression, statement) {
71316         return node.awaitModifier !== awaitModifier
71317             || node.initializer !== initializer
71318             || node.expression !== expression
71319             || node.statement !== statement
71320             ? updateNode(createForOf(awaitModifier, initializer, expression, statement), node)
71321             : node;
71322     }
71323     ts.updateForOf = updateForOf;
71324     function createContinue(label) {
71325         var node = createSynthesizedNode(233 /* ContinueStatement */);
71326         node.label = asName(label);
71327         return node;
71328     }
71329     ts.createContinue = createContinue;
71330     function updateContinue(node, label) {
71331         return node.label !== label
71332             ? updateNode(createContinue(label), node)
71333             : node;
71334     }
71335     ts.updateContinue = updateContinue;
71336     function createBreak(label) {
71337         var node = createSynthesizedNode(234 /* BreakStatement */);
71338         node.label = asName(label);
71339         return node;
71340     }
71341     ts.createBreak = createBreak;
71342     function updateBreak(node, label) {
71343         return node.label !== label
71344             ? updateNode(createBreak(label), node)
71345             : node;
71346     }
71347     ts.updateBreak = updateBreak;
71348     function createReturn(expression) {
71349         var node = createSynthesizedNode(235 /* ReturnStatement */);
71350         node.expression = expression;
71351         return node;
71352     }
71353     ts.createReturn = createReturn;
71354     function updateReturn(node, expression) {
71355         return node.expression !== expression
71356             ? updateNode(createReturn(expression), node)
71357             : node;
71358     }
71359     ts.updateReturn = updateReturn;
71360     function createWith(expression, statement) {
71361         var node = createSynthesizedNode(236 /* WithStatement */);
71362         node.expression = expression;
71363         node.statement = asEmbeddedStatement(statement);
71364         return node;
71365     }
71366     ts.createWith = createWith;
71367     function updateWith(node, expression, statement) {
71368         return node.expression !== expression
71369             || node.statement !== statement
71370             ? updateNode(createWith(expression, statement), node)
71371             : node;
71372     }
71373     ts.updateWith = updateWith;
71374     function createSwitch(expression, caseBlock) {
71375         var node = createSynthesizedNode(237 /* SwitchStatement */);
71376         node.expression = ts.parenthesizeExpressionForList(expression);
71377         node.caseBlock = caseBlock;
71378         return node;
71379     }
71380     ts.createSwitch = createSwitch;
71381     function updateSwitch(node, expression, caseBlock) {
71382         return node.expression !== expression
71383             || node.caseBlock !== caseBlock
71384             ? updateNode(createSwitch(expression, caseBlock), node)
71385             : node;
71386     }
71387     ts.updateSwitch = updateSwitch;
71388     function createLabel(label, statement) {
71389         var node = createSynthesizedNode(238 /* LabeledStatement */);
71390         node.label = asName(label);
71391         node.statement = asEmbeddedStatement(statement);
71392         return node;
71393     }
71394     ts.createLabel = createLabel;
71395     function updateLabel(node, label, statement) {
71396         return node.label !== label
71397             || node.statement !== statement
71398             ? updateNode(createLabel(label, statement), node)
71399             : node;
71400     }
71401     ts.updateLabel = updateLabel;
71402     function createThrow(expression) {
71403         var node = createSynthesizedNode(239 /* ThrowStatement */);
71404         node.expression = expression;
71405         return node;
71406     }
71407     ts.createThrow = createThrow;
71408     function updateThrow(node, expression) {
71409         return node.expression !== expression
71410             ? updateNode(createThrow(expression), node)
71411             : node;
71412     }
71413     ts.updateThrow = updateThrow;
71414     function createTry(tryBlock, catchClause, finallyBlock) {
71415         var node = createSynthesizedNode(240 /* TryStatement */);
71416         node.tryBlock = tryBlock;
71417         node.catchClause = catchClause;
71418         node.finallyBlock = finallyBlock;
71419         return node;
71420     }
71421     ts.createTry = createTry;
71422     function updateTry(node, tryBlock, catchClause, finallyBlock) {
71423         return node.tryBlock !== tryBlock
71424             || node.catchClause !== catchClause
71425             || node.finallyBlock !== finallyBlock
71426             ? updateNode(createTry(tryBlock, catchClause, finallyBlock), node)
71427             : node;
71428     }
71429     ts.updateTry = updateTry;
71430     function createDebuggerStatement() {
71431         return createSynthesizedNode(241 /* DebuggerStatement */);
71432     }
71433     ts.createDebuggerStatement = createDebuggerStatement;
71434     function createVariableDeclaration(name, type, initializer) {
71435         /* Internally, one should probably use createTypeScriptVariableDeclaration instead and handle definite assignment assertions */
71436         var node = createSynthesizedNode(242 /* VariableDeclaration */);
71437         node.name = asName(name);
71438         node.type = type;
71439         node.initializer = initializer !== undefined ? ts.parenthesizeExpressionForList(initializer) : undefined;
71440         return node;
71441     }
71442     ts.createVariableDeclaration = createVariableDeclaration;
71443     function updateVariableDeclaration(node, name, type, initializer) {
71444         /* Internally, one should probably use updateTypeScriptVariableDeclaration instead and handle definite assignment assertions */
71445         return node.name !== name
71446             || node.type !== type
71447             || node.initializer !== initializer
71448             ? updateNode(createVariableDeclaration(name, type, initializer), node)
71449             : node;
71450     }
71451     ts.updateVariableDeclaration = updateVariableDeclaration;
71452     /* @internal */
71453     function createTypeScriptVariableDeclaration(name, exclaimationToken, type, initializer) {
71454         var node = createSynthesizedNode(242 /* VariableDeclaration */);
71455         node.name = asName(name);
71456         node.type = type;
71457         node.initializer = initializer !== undefined ? ts.parenthesizeExpressionForList(initializer) : undefined;
71458         node.exclamationToken = exclaimationToken;
71459         return node;
71460     }
71461     ts.createTypeScriptVariableDeclaration = createTypeScriptVariableDeclaration;
71462     /* @internal */
71463     function updateTypeScriptVariableDeclaration(node, name, exclaimationToken, type, initializer) {
71464         return node.name !== name
71465             || node.type !== type
71466             || node.initializer !== initializer
71467             || node.exclamationToken !== exclaimationToken
71468             ? updateNode(createTypeScriptVariableDeclaration(name, exclaimationToken, type, initializer), node)
71469             : node;
71470     }
71471     ts.updateTypeScriptVariableDeclaration = updateTypeScriptVariableDeclaration;
71472     function createVariableDeclarationList(declarations, flags) {
71473         if (flags === void 0) { flags = 0 /* None */; }
71474         var node = createSynthesizedNode(243 /* VariableDeclarationList */);
71475         node.flags |= flags & 3 /* BlockScoped */;
71476         node.declarations = createNodeArray(declarations);
71477         return node;
71478     }
71479     ts.createVariableDeclarationList = createVariableDeclarationList;
71480     function updateVariableDeclarationList(node, declarations) {
71481         return node.declarations !== declarations
71482             ? updateNode(createVariableDeclarationList(declarations, node.flags), node)
71483             : node;
71484     }
71485     ts.updateVariableDeclarationList = updateVariableDeclarationList;
71486     function createFunctionDeclaration(decorators, modifiers, asteriskToken, name, typeParameters, parameters, type, body) {
71487         var node = createSynthesizedNode(244 /* FunctionDeclaration */);
71488         node.decorators = asNodeArray(decorators);
71489         node.modifiers = asNodeArray(modifiers);
71490         node.asteriskToken = asteriskToken;
71491         node.name = asName(name);
71492         node.typeParameters = asNodeArray(typeParameters);
71493         node.parameters = createNodeArray(parameters);
71494         node.type = type;
71495         node.body = body;
71496         return node;
71497     }
71498     ts.createFunctionDeclaration = createFunctionDeclaration;
71499     function updateFunctionDeclaration(node, decorators, modifiers, asteriskToken, name, typeParameters, parameters, type, body) {
71500         return node.decorators !== decorators
71501             || node.modifiers !== modifiers
71502             || node.asteriskToken !== asteriskToken
71503             || node.name !== name
71504             || node.typeParameters !== typeParameters
71505             || node.parameters !== parameters
71506             || node.type !== type
71507             || node.body !== body
71508             ? updateNode(createFunctionDeclaration(decorators, modifiers, asteriskToken, name, typeParameters, parameters, type, body), node)
71509             : node;
71510     }
71511     ts.updateFunctionDeclaration = updateFunctionDeclaration;
71512     /* @internal */
71513     function updateFunctionLikeBody(declaration, body) {
71514         switch (declaration.kind) {
71515             case 244 /* FunctionDeclaration */:
71516                 return createFunctionDeclaration(declaration.decorators, declaration.modifiers, declaration.asteriskToken, declaration.name, declaration.typeParameters, declaration.parameters, declaration.type, body);
71517             case 161 /* MethodDeclaration */:
71518                 return createMethod(declaration.decorators, declaration.modifiers, declaration.asteriskToken, declaration.name, declaration.questionToken, declaration.typeParameters, declaration.parameters, declaration.type, body);
71519             case 163 /* GetAccessor */:
71520                 return createGetAccessor(declaration.decorators, declaration.modifiers, declaration.name, declaration.parameters, declaration.type, body);
71521             case 164 /* SetAccessor */:
71522                 return createSetAccessor(declaration.decorators, declaration.modifiers, declaration.name, declaration.parameters, body);
71523             case 162 /* Constructor */:
71524                 return createConstructor(declaration.decorators, declaration.modifiers, declaration.parameters, body);
71525             case 201 /* FunctionExpression */:
71526                 return createFunctionExpression(declaration.modifiers, declaration.asteriskToken, declaration.name, declaration.typeParameters, declaration.parameters, declaration.type, body);
71527             case 202 /* ArrowFunction */:
71528                 return createArrowFunction(declaration.modifiers, declaration.typeParameters, declaration.parameters, declaration.type, declaration.equalsGreaterThanToken, body);
71529         }
71530     }
71531     ts.updateFunctionLikeBody = updateFunctionLikeBody;
71532     function createClassDeclaration(decorators, modifiers, name, typeParameters, heritageClauses, members) {
71533         var node = createSynthesizedNode(245 /* ClassDeclaration */);
71534         node.decorators = asNodeArray(decorators);
71535         node.modifiers = asNodeArray(modifiers);
71536         node.name = asName(name);
71537         node.typeParameters = asNodeArray(typeParameters);
71538         node.heritageClauses = asNodeArray(heritageClauses);
71539         node.members = createNodeArray(members);
71540         return node;
71541     }
71542     ts.createClassDeclaration = createClassDeclaration;
71543     function updateClassDeclaration(node, decorators, modifiers, name, typeParameters, heritageClauses, members) {
71544         return node.decorators !== decorators
71545             || node.modifiers !== modifiers
71546             || node.name !== name
71547             || node.typeParameters !== typeParameters
71548             || node.heritageClauses !== heritageClauses
71549             || node.members !== members
71550             ? updateNode(createClassDeclaration(decorators, modifiers, name, typeParameters, heritageClauses, members), node)
71551             : node;
71552     }
71553     ts.updateClassDeclaration = updateClassDeclaration;
71554     function createInterfaceDeclaration(decorators, modifiers, name, typeParameters, heritageClauses, members) {
71555         var node = createSynthesizedNode(246 /* InterfaceDeclaration */);
71556         node.decorators = asNodeArray(decorators);
71557         node.modifiers = asNodeArray(modifiers);
71558         node.name = asName(name);
71559         node.typeParameters = asNodeArray(typeParameters);
71560         node.heritageClauses = asNodeArray(heritageClauses);
71561         node.members = createNodeArray(members);
71562         return node;
71563     }
71564     ts.createInterfaceDeclaration = createInterfaceDeclaration;
71565     function updateInterfaceDeclaration(node, decorators, modifiers, name, typeParameters, heritageClauses, members) {
71566         return node.decorators !== decorators
71567             || node.modifiers !== modifiers
71568             || node.name !== name
71569             || node.typeParameters !== typeParameters
71570             || node.heritageClauses !== heritageClauses
71571             || node.members !== members
71572             ? updateNode(createInterfaceDeclaration(decorators, modifiers, name, typeParameters, heritageClauses, members), node)
71573             : node;
71574     }
71575     ts.updateInterfaceDeclaration = updateInterfaceDeclaration;
71576     function createTypeAliasDeclaration(decorators, modifiers, name, typeParameters, type) {
71577         var node = createSynthesizedNode(247 /* TypeAliasDeclaration */);
71578         node.decorators = asNodeArray(decorators);
71579         node.modifiers = asNodeArray(modifiers);
71580         node.name = asName(name);
71581         node.typeParameters = asNodeArray(typeParameters);
71582         node.type = type;
71583         return node;
71584     }
71585     ts.createTypeAliasDeclaration = createTypeAliasDeclaration;
71586     function updateTypeAliasDeclaration(node, decorators, modifiers, name, typeParameters, type) {
71587         return node.decorators !== decorators
71588             || node.modifiers !== modifiers
71589             || node.name !== name
71590             || node.typeParameters !== typeParameters
71591             || node.type !== type
71592             ? updateNode(createTypeAliasDeclaration(decorators, modifiers, name, typeParameters, type), node)
71593             : node;
71594     }
71595     ts.updateTypeAliasDeclaration = updateTypeAliasDeclaration;
71596     function createEnumDeclaration(decorators, modifiers, name, members) {
71597         var node = createSynthesizedNode(248 /* EnumDeclaration */);
71598         node.decorators = asNodeArray(decorators);
71599         node.modifiers = asNodeArray(modifiers);
71600         node.name = asName(name);
71601         node.members = createNodeArray(members);
71602         return node;
71603     }
71604     ts.createEnumDeclaration = createEnumDeclaration;
71605     function updateEnumDeclaration(node, decorators, modifiers, name, members) {
71606         return node.decorators !== decorators
71607             || node.modifiers !== modifiers
71608             || node.name !== name
71609             || node.members !== members
71610             ? updateNode(createEnumDeclaration(decorators, modifiers, name, members), node)
71611             : node;
71612     }
71613     ts.updateEnumDeclaration = updateEnumDeclaration;
71614     function createModuleDeclaration(decorators, modifiers, name, body, flags) {
71615         if (flags === void 0) { flags = 0 /* None */; }
71616         var node = createSynthesizedNode(249 /* ModuleDeclaration */);
71617         node.flags |= flags & (16 /* Namespace */ | 4 /* NestedNamespace */ | 1024 /* GlobalAugmentation */);
71618         node.decorators = asNodeArray(decorators);
71619         node.modifiers = asNodeArray(modifiers);
71620         node.name = name;
71621         node.body = body;
71622         return node;
71623     }
71624     ts.createModuleDeclaration = createModuleDeclaration;
71625     function updateModuleDeclaration(node, decorators, modifiers, name, body) {
71626         return node.decorators !== decorators
71627             || node.modifiers !== modifiers
71628             || node.name !== name
71629             || node.body !== body
71630             ? updateNode(createModuleDeclaration(decorators, modifiers, name, body, node.flags), node)
71631             : node;
71632     }
71633     ts.updateModuleDeclaration = updateModuleDeclaration;
71634     function createModuleBlock(statements) {
71635         var node = createSynthesizedNode(250 /* ModuleBlock */);
71636         node.statements = createNodeArray(statements);
71637         return node;
71638     }
71639     ts.createModuleBlock = createModuleBlock;
71640     function updateModuleBlock(node, statements) {
71641         return node.statements !== statements
71642             ? updateNode(createModuleBlock(statements), node)
71643             : node;
71644     }
71645     ts.updateModuleBlock = updateModuleBlock;
71646     function createCaseBlock(clauses) {
71647         var node = createSynthesizedNode(251 /* CaseBlock */);
71648         node.clauses = createNodeArray(clauses);
71649         return node;
71650     }
71651     ts.createCaseBlock = createCaseBlock;
71652     function updateCaseBlock(node, clauses) {
71653         return node.clauses !== clauses
71654             ? updateNode(createCaseBlock(clauses), node)
71655             : node;
71656     }
71657     ts.updateCaseBlock = updateCaseBlock;
71658     function createNamespaceExportDeclaration(name) {
71659         var node = createSynthesizedNode(252 /* NamespaceExportDeclaration */);
71660         node.name = asName(name);
71661         return node;
71662     }
71663     ts.createNamespaceExportDeclaration = createNamespaceExportDeclaration;
71664     function updateNamespaceExportDeclaration(node, name) {
71665         return node.name !== name
71666             ? updateNode(createNamespaceExportDeclaration(name), node)
71667             : node;
71668     }
71669     ts.updateNamespaceExportDeclaration = updateNamespaceExportDeclaration;
71670     function createImportEqualsDeclaration(decorators, modifiers, name, moduleReference) {
71671         var node = createSynthesizedNode(253 /* ImportEqualsDeclaration */);
71672         node.decorators = asNodeArray(decorators);
71673         node.modifiers = asNodeArray(modifiers);
71674         node.name = asName(name);
71675         node.moduleReference = moduleReference;
71676         return node;
71677     }
71678     ts.createImportEqualsDeclaration = createImportEqualsDeclaration;
71679     function updateImportEqualsDeclaration(node, decorators, modifiers, name, moduleReference) {
71680         return node.decorators !== decorators
71681             || node.modifiers !== modifiers
71682             || node.name !== name
71683             || node.moduleReference !== moduleReference
71684             ? updateNode(createImportEqualsDeclaration(decorators, modifiers, name, moduleReference), node)
71685             : node;
71686     }
71687     ts.updateImportEqualsDeclaration = updateImportEqualsDeclaration;
71688     function createImportDeclaration(decorators, modifiers, importClause, moduleSpecifier) {
71689         var node = createSynthesizedNode(254 /* ImportDeclaration */);
71690         node.decorators = asNodeArray(decorators);
71691         node.modifiers = asNodeArray(modifiers);
71692         node.importClause = importClause;
71693         node.moduleSpecifier = moduleSpecifier;
71694         return node;
71695     }
71696     ts.createImportDeclaration = createImportDeclaration;
71697     function updateImportDeclaration(node, decorators, modifiers, importClause, moduleSpecifier) {
71698         return node.decorators !== decorators
71699             || node.modifiers !== modifiers
71700             || node.importClause !== importClause
71701             || node.moduleSpecifier !== moduleSpecifier
71702             ? updateNode(createImportDeclaration(decorators, modifiers, importClause, moduleSpecifier), node)
71703             : node;
71704     }
71705     ts.updateImportDeclaration = updateImportDeclaration;
71706     function createImportClause(name, namedBindings, isTypeOnly) {
71707         if (isTypeOnly === void 0) { isTypeOnly = false; }
71708         var node = createSynthesizedNode(255 /* ImportClause */);
71709         node.name = name;
71710         node.namedBindings = namedBindings;
71711         node.isTypeOnly = isTypeOnly;
71712         return node;
71713     }
71714     ts.createImportClause = createImportClause;
71715     function updateImportClause(node, name, namedBindings, isTypeOnly) {
71716         return node.name !== name
71717             || node.namedBindings !== namedBindings
71718             || node.isTypeOnly !== isTypeOnly
71719             ? updateNode(createImportClause(name, namedBindings, isTypeOnly), node)
71720             : node;
71721     }
71722     ts.updateImportClause = updateImportClause;
71723     function createNamespaceImport(name) {
71724         var node = createSynthesizedNode(256 /* NamespaceImport */);
71725         node.name = name;
71726         return node;
71727     }
71728     ts.createNamespaceImport = createNamespaceImport;
71729     function createNamespaceExport(name) {
71730         var node = createSynthesizedNode(262 /* NamespaceExport */);
71731         node.name = name;
71732         return node;
71733     }
71734     ts.createNamespaceExport = createNamespaceExport;
71735     function updateNamespaceImport(node, name) {
71736         return node.name !== name
71737             ? updateNode(createNamespaceImport(name), node)
71738             : node;
71739     }
71740     ts.updateNamespaceImport = updateNamespaceImport;
71741     function updateNamespaceExport(node, name) {
71742         return node.name !== name
71743             ? updateNode(createNamespaceExport(name), node)
71744             : node;
71745     }
71746     ts.updateNamespaceExport = updateNamespaceExport;
71747     function createNamedImports(elements) {
71748         var node = createSynthesizedNode(257 /* NamedImports */);
71749         node.elements = createNodeArray(elements);
71750         return node;
71751     }
71752     ts.createNamedImports = createNamedImports;
71753     function updateNamedImports(node, elements) {
71754         return node.elements !== elements
71755             ? updateNode(createNamedImports(elements), node)
71756             : node;
71757     }
71758     ts.updateNamedImports = updateNamedImports;
71759     function createImportSpecifier(propertyName, name) {
71760         var node = createSynthesizedNode(258 /* ImportSpecifier */);
71761         node.propertyName = propertyName;
71762         node.name = name;
71763         return node;
71764     }
71765     ts.createImportSpecifier = createImportSpecifier;
71766     function updateImportSpecifier(node, propertyName, name) {
71767         return node.propertyName !== propertyName
71768             || node.name !== name
71769             ? updateNode(createImportSpecifier(propertyName, name), node)
71770             : node;
71771     }
71772     ts.updateImportSpecifier = updateImportSpecifier;
71773     function createExportAssignment(decorators, modifiers, isExportEquals, expression) {
71774         var node = createSynthesizedNode(259 /* ExportAssignment */);
71775         node.decorators = asNodeArray(decorators);
71776         node.modifiers = asNodeArray(modifiers);
71777         node.isExportEquals = isExportEquals;
71778         node.expression = isExportEquals ? ts.parenthesizeBinaryOperand(62 /* EqualsToken */, expression, /*isLeftSideOfBinary*/ false, /*leftOperand*/ undefined) : ts.parenthesizeDefaultExpression(expression);
71779         return node;
71780     }
71781     ts.createExportAssignment = createExportAssignment;
71782     function updateExportAssignment(node, decorators, modifiers, expression) {
71783         return node.decorators !== decorators
71784             || node.modifiers !== modifiers
71785             || node.expression !== expression
71786             ? updateNode(createExportAssignment(decorators, modifiers, node.isExportEquals, expression), node)
71787             : node;
71788     }
71789     ts.updateExportAssignment = updateExportAssignment;
71790     function createExportDeclaration(decorators, modifiers, exportClause, moduleSpecifier, isTypeOnly) {
71791         if (isTypeOnly === void 0) { isTypeOnly = false; }
71792         var node = createSynthesizedNode(260 /* ExportDeclaration */);
71793         node.decorators = asNodeArray(decorators);
71794         node.modifiers = asNodeArray(modifiers);
71795         node.isTypeOnly = isTypeOnly;
71796         node.exportClause = exportClause;
71797         node.moduleSpecifier = moduleSpecifier;
71798         return node;
71799     }
71800     ts.createExportDeclaration = createExportDeclaration;
71801     function updateExportDeclaration(node, decorators, modifiers, exportClause, moduleSpecifier, isTypeOnly) {
71802         return node.decorators !== decorators
71803             || node.modifiers !== modifiers
71804             || node.isTypeOnly !== isTypeOnly
71805             || node.exportClause !== exportClause
71806             || node.moduleSpecifier !== moduleSpecifier
71807             ? updateNode(createExportDeclaration(decorators, modifiers, exportClause, moduleSpecifier, isTypeOnly), node)
71808             : node;
71809     }
71810     ts.updateExportDeclaration = updateExportDeclaration;
71811     /* @internal */
71812     function createEmptyExports() {
71813         return createExportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, createNamedExports([]), /*moduleSpecifier*/ undefined);
71814     }
71815     ts.createEmptyExports = createEmptyExports;
71816     function createNamedExports(elements) {
71817         var node = createSynthesizedNode(261 /* NamedExports */);
71818         node.elements = createNodeArray(elements);
71819         return node;
71820     }
71821     ts.createNamedExports = createNamedExports;
71822     function updateNamedExports(node, elements) {
71823         return node.elements !== elements
71824             ? updateNode(createNamedExports(elements), node)
71825             : node;
71826     }
71827     ts.updateNamedExports = updateNamedExports;
71828     function createExportSpecifier(propertyName, name) {
71829         var node = createSynthesizedNode(263 /* ExportSpecifier */);
71830         node.propertyName = asName(propertyName);
71831         node.name = asName(name);
71832         return node;
71833     }
71834     ts.createExportSpecifier = createExportSpecifier;
71835     function updateExportSpecifier(node, propertyName, name) {
71836         return node.propertyName !== propertyName
71837             || node.name !== name
71838             ? updateNode(createExportSpecifier(propertyName, name), node)
71839             : node;
71840     }
71841     ts.updateExportSpecifier = updateExportSpecifier;
71842     // Module references
71843     function createExternalModuleReference(expression) {
71844         var node = createSynthesizedNode(265 /* ExternalModuleReference */);
71845         node.expression = expression;
71846         return node;
71847     }
71848     ts.createExternalModuleReference = createExternalModuleReference;
71849     function updateExternalModuleReference(node, expression) {
71850         return node.expression !== expression
71851             ? updateNode(createExternalModuleReference(expression), node)
71852             : node;
71853     }
71854     ts.updateExternalModuleReference = updateExternalModuleReference;
71855     // JSDoc
71856     /* @internal */
71857     function createJSDocTypeExpression(type) {
71858         var node = createSynthesizedNode(294 /* JSDocTypeExpression */);
71859         node.type = type;
71860         return node;
71861     }
71862     ts.createJSDocTypeExpression = createJSDocTypeExpression;
71863     /* @internal */
71864     function createJSDocTypeTag(typeExpression, comment) {
71865         var tag = createJSDocTag(320 /* JSDocTypeTag */, "type");
71866         tag.typeExpression = typeExpression;
71867         tag.comment = comment;
71868         return tag;
71869     }
71870     ts.createJSDocTypeTag = createJSDocTypeTag;
71871     /* @internal */
71872     function createJSDocReturnTag(typeExpression, comment) {
71873         var tag = createJSDocTag(318 /* JSDocReturnTag */, "returns");
71874         tag.typeExpression = typeExpression;
71875         tag.comment = comment;
71876         return tag;
71877     }
71878     ts.createJSDocReturnTag = createJSDocReturnTag;
71879     /** @internal */
71880     function createJSDocThisTag(typeExpression) {
71881         var tag = createJSDocTag(319 /* JSDocThisTag */, "this");
71882         tag.typeExpression = typeExpression;
71883         return tag;
71884     }
71885     ts.createJSDocThisTag = createJSDocThisTag;
71886     /* @internal */
71887     function createJSDocParamTag(name, isBracketed, typeExpression, comment) {
71888         var tag = createJSDocTag(317 /* JSDocParameterTag */, "param");
71889         tag.typeExpression = typeExpression;
71890         tag.name = name;
71891         tag.isBracketed = isBracketed;
71892         tag.comment = comment;
71893         return tag;
71894     }
71895     ts.createJSDocParamTag = createJSDocParamTag;
71896     /* @internal */
71897     function createJSDocClassTag() {
71898         return createJSDocTag(310 /* JSDocClassTag */, "class");
71899     }
71900     ts.createJSDocClassTag = createJSDocClassTag;
71901     /* @internal */
71902     function createJSDocComment(comment, tags) {
71903         var node = createSynthesizedNode(303 /* JSDocComment */);
71904         node.comment = comment;
71905         node.tags = tags;
71906         return node;
71907     }
71908     ts.createJSDocComment = createJSDocComment;
71909     /* @internal */
71910     function createJSDocTag(kind, tagName) {
71911         var node = createSynthesizedNode(kind);
71912         node.tagName = createIdentifier(tagName);
71913         return node;
71914     }
71915     // JSX
71916     function createJsxElement(openingElement, children, closingElement) {
71917         var node = createSynthesizedNode(266 /* JsxElement */);
71918         node.openingElement = openingElement;
71919         node.children = createNodeArray(children);
71920         node.closingElement = closingElement;
71921         return node;
71922     }
71923     ts.createJsxElement = createJsxElement;
71924     function updateJsxElement(node, openingElement, children, closingElement) {
71925         return node.openingElement !== openingElement
71926             || node.children !== children
71927             || node.closingElement !== closingElement
71928             ? updateNode(createJsxElement(openingElement, children, closingElement), node)
71929             : node;
71930     }
71931     ts.updateJsxElement = updateJsxElement;
71932     function createJsxSelfClosingElement(tagName, typeArguments, attributes) {
71933         var node = createSynthesizedNode(267 /* JsxSelfClosingElement */);
71934         node.tagName = tagName;
71935         node.typeArguments = asNodeArray(typeArguments);
71936         node.attributes = attributes;
71937         return node;
71938     }
71939     ts.createJsxSelfClosingElement = createJsxSelfClosingElement;
71940     function updateJsxSelfClosingElement(node, tagName, typeArguments, attributes) {
71941         return node.tagName !== tagName
71942             || node.typeArguments !== typeArguments
71943             || node.attributes !== attributes
71944             ? updateNode(createJsxSelfClosingElement(tagName, typeArguments, attributes), node)
71945             : node;
71946     }
71947     ts.updateJsxSelfClosingElement = updateJsxSelfClosingElement;
71948     function createJsxOpeningElement(tagName, typeArguments, attributes) {
71949         var node = createSynthesizedNode(268 /* JsxOpeningElement */);
71950         node.tagName = tagName;
71951         node.typeArguments = asNodeArray(typeArguments);
71952         node.attributes = attributes;
71953         return node;
71954     }
71955     ts.createJsxOpeningElement = createJsxOpeningElement;
71956     function updateJsxOpeningElement(node, tagName, typeArguments, attributes) {
71957         return node.tagName !== tagName
71958             || node.typeArguments !== typeArguments
71959             || node.attributes !== attributes
71960             ? updateNode(createJsxOpeningElement(tagName, typeArguments, attributes), node)
71961             : node;
71962     }
71963     ts.updateJsxOpeningElement = updateJsxOpeningElement;
71964     function createJsxClosingElement(tagName) {
71965         var node = createSynthesizedNode(269 /* JsxClosingElement */);
71966         node.tagName = tagName;
71967         return node;
71968     }
71969     ts.createJsxClosingElement = createJsxClosingElement;
71970     function updateJsxClosingElement(node, tagName) {
71971         return node.tagName !== tagName
71972             ? updateNode(createJsxClosingElement(tagName), node)
71973             : node;
71974     }
71975     ts.updateJsxClosingElement = updateJsxClosingElement;
71976     function createJsxFragment(openingFragment, children, closingFragment) {
71977         var node = createSynthesizedNode(270 /* JsxFragment */);
71978         node.openingFragment = openingFragment;
71979         node.children = createNodeArray(children);
71980         node.closingFragment = closingFragment;
71981         return node;
71982     }
71983     ts.createJsxFragment = createJsxFragment;
71984     function createJsxText(text, containsOnlyTriviaWhiteSpaces) {
71985         var node = createSynthesizedNode(11 /* JsxText */);
71986         node.text = text;
71987         node.containsOnlyTriviaWhiteSpaces = !!containsOnlyTriviaWhiteSpaces;
71988         return node;
71989     }
71990     ts.createJsxText = createJsxText;
71991     function updateJsxText(node, text, containsOnlyTriviaWhiteSpaces) {
71992         return node.text !== text
71993             || node.containsOnlyTriviaWhiteSpaces !== containsOnlyTriviaWhiteSpaces
71994             ? updateNode(createJsxText(text, containsOnlyTriviaWhiteSpaces), node)
71995             : node;
71996     }
71997     ts.updateJsxText = updateJsxText;
71998     function createJsxOpeningFragment() {
71999         return createSynthesizedNode(271 /* JsxOpeningFragment */);
72000     }
72001     ts.createJsxOpeningFragment = createJsxOpeningFragment;
72002     function createJsxJsxClosingFragment() {
72003         return createSynthesizedNode(272 /* JsxClosingFragment */);
72004     }
72005     ts.createJsxJsxClosingFragment = createJsxJsxClosingFragment;
72006     function updateJsxFragment(node, openingFragment, children, closingFragment) {
72007         return node.openingFragment !== openingFragment
72008             || node.children !== children
72009             || node.closingFragment !== closingFragment
72010             ? updateNode(createJsxFragment(openingFragment, children, closingFragment), node)
72011             : node;
72012     }
72013     ts.updateJsxFragment = updateJsxFragment;
72014     function createJsxAttribute(name, initializer) {
72015         var node = createSynthesizedNode(273 /* JsxAttribute */);
72016         node.name = name;
72017         node.initializer = initializer;
72018         return node;
72019     }
72020     ts.createJsxAttribute = createJsxAttribute;
72021     function updateJsxAttribute(node, name, initializer) {
72022         return node.name !== name
72023             || node.initializer !== initializer
72024             ? updateNode(createJsxAttribute(name, initializer), node)
72025             : node;
72026     }
72027     ts.updateJsxAttribute = updateJsxAttribute;
72028     function createJsxAttributes(properties) {
72029         var node = createSynthesizedNode(274 /* JsxAttributes */);
72030         node.properties = createNodeArray(properties);
72031         return node;
72032     }
72033     ts.createJsxAttributes = createJsxAttributes;
72034     function updateJsxAttributes(node, properties) {
72035         return node.properties !== properties
72036             ? updateNode(createJsxAttributes(properties), node)
72037             : node;
72038     }
72039     ts.updateJsxAttributes = updateJsxAttributes;
72040     function createJsxSpreadAttribute(expression) {
72041         var node = createSynthesizedNode(275 /* JsxSpreadAttribute */);
72042         node.expression = expression;
72043         return node;
72044     }
72045     ts.createJsxSpreadAttribute = createJsxSpreadAttribute;
72046     function updateJsxSpreadAttribute(node, expression) {
72047         return node.expression !== expression
72048             ? updateNode(createJsxSpreadAttribute(expression), node)
72049             : node;
72050     }
72051     ts.updateJsxSpreadAttribute = updateJsxSpreadAttribute;
72052     function createJsxExpression(dotDotDotToken, expression) {
72053         var node = createSynthesizedNode(276 /* JsxExpression */);
72054         node.dotDotDotToken = dotDotDotToken;
72055         node.expression = expression;
72056         return node;
72057     }
72058     ts.createJsxExpression = createJsxExpression;
72059     function updateJsxExpression(node, expression) {
72060         return node.expression !== expression
72061             ? updateNode(createJsxExpression(node.dotDotDotToken, expression), node)
72062             : node;
72063     }
72064     ts.updateJsxExpression = updateJsxExpression;
72065     // Clauses
72066     function createCaseClause(expression, statements) {
72067         var node = createSynthesizedNode(277 /* CaseClause */);
72068         node.expression = ts.parenthesizeExpressionForList(expression);
72069         node.statements = createNodeArray(statements);
72070         return node;
72071     }
72072     ts.createCaseClause = createCaseClause;
72073     function updateCaseClause(node, expression, statements) {
72074         return node.expression !== expression
72075             || node.statements !== statements
72076             ? updateNode(createCaseClause(expression, statements), node)
72077             : node;
72078     }
72079     ts.updateCaseClause = updateCaseClause;
72080     function createDefaultClause(statements) {
72081         var node = createSynthesizedNode(278 /* DefaultClause */);
72082         node.statements = createNodeArray(statements);
72083         return node;
72084     }
72085     ts.createDefaultClause = createDefaultClause;
72086     function updateDefaultClause(node, statements) {
72087         return node.statements !== statements
72088             ? updateNode(createDefaultClause(statements), node)
72089             : node;
72090     }
72091     ts.updateDefaultClause = updateDefaultClause;
72092     function createHeritageClause(token, types) {
72093         var node = createSynthesizedNode(279 /* HeritageClause */);
72094         node.token = token;
72095         node.types = createNodeArray(types);
72096         return node;
72097     }
72098     ts.createHeritageClause = createHeritageClause;
72099     function updateHeritageClause(node, types) {
72100         return node.types !== types
72101             ? updateNode(createHeritageClause(node.token, types), node)
72102             : node;
72103     }
72104     ts.updateHeritageClause = updateHeritageClause;
72105     function createCatchClause(variableDeclaration, block) {
72106         var node = createSynthesizedNode(280 /* CatchClause */);
72107         node.variableDeclaration = ts.isString(variableDeclaration) ? createVariableDeclaration(variableDeclaration) : variableDeclaration;
72108         node.block = block;
72109         return node;
72110     }
72111     ts.createCatchClause = createCatchClause;
72112     function updateCatchClause(node, variableDeclaration, block) {
72113         return node.variableDeclaration !== variableDeclaration
72114             || node.block !== block
72115             ? updateNode(createCatchClause(variableDeclaration, block), node)
72116             : node;
72117     }
72118     ts.updateCatchClause = updateCatchClause;
72119     // Property assignments
72120     function createPropertyAssignment(name, initializer) {
72121         var node = createSynthesizedNode(281 /* PropertyAssignment */);
72122         node.name = asName(name);
72123         node.questionToken = undefined;
72124         node.initializer = ts.parenthesizeExpressionForList(initializer);
72125         return node;
72126     }
72127     ts.createPropertyAssignment = createPropertyAssignment;
72128     function updatePropertyAssignment(node, name, initializer) {
72129         return node.name !== name
72130             || node.initializer !== initializer
72131             ? updateNode(createPropertyAssignment(name, initializer), node)
72132             : node;
72133     }
72134     ts.updatePropertyAssignment = updatePropertyAssignment;
72135     function createShorthandPropertyAssignment(name, objectAssignmentInitializer) {
72136         var node = createSynthesizedNode(282 /* ShorthandPropertyAssignment */);
72137         node.name = asName(name);
72138         node.objectAssignmentInitializer = objectAssignmentInitializer !== undefined ? ts.parenthesizeExpressionForList(objectAssignmentInitializer) : undefined;
72139         return node;
72140     }
72141     ts.createShorthandPropertyAssignment = createShorthandPropertyAssignment;
72142     function updateShorthandPropertyAssignment(node, name, objectAssignmentInitializer) {
72143         return node.name !== name
72144             || node.objectAssignmentInitializer !== objectAssignmentInitializer
72145             ? updateNode(createShorthandPropertyAssignment(name, objectAssignmentInitializer), node)
72146             : node;
72147     }
72148     ts.updateShorthandPropertyAssignment = updateShorthandPropertyAssignment;
72149     function createSpreadAssignment(expression) {
72150         var node = createSynthesizedNode(283 /* SpreadAssignment */);
72151         node.expression = ts.parenthesizeExpressionForList(expression);
72152         return node;
72153     }
72154     ts.createSpreadAssignment = createSpreadAssignment;
72155     function updateSpreadAssignment(node, expression) {
72156         return node.expression !== expression
72157             ? updateNode(createSpreadAssignment(expression), node)
72158             : node;
72159     }
72160     ts.updateSpreadAssignment = updateSpreadAssignment;
72161     // Enum
72162     function createEnumMember(name, initializer) {
72163         var node = createSynthesizedNode(284 /* EnumMember */);
72164         node.name = asName(name);
72165         node.initializer = initializer && ts.parenthesizeExpressionForList(initializer);
72166         return node;
72167     }
72168     ts.createEnumMember = createEnumMember;
72169     function updateEnumMember(node, name, initializer) {
72170         return node.name !== name
72171             || node.initializer !== initializer
72172             ? updateNode(createEnumMember(name, initializer), node)
72173             : node;
72174     }
72175     ts.updateEnumMember = updateEnumMember;
72176     // Top-level nodes
72177     function updateSourceFileNode(node, statements, isDeclarationFile, referencedFiles, typeReferences, hasNoDefaultLib, libReferences) {
72178         if (node.statements !== statements ||
72179             (isDeclarationFile !== undefined && node.isDeclarationFile !== isDeclarationFile) ||
72180             (referencedFiles !== undefined && node.referencedFiles !== referencedFiles) ||
72181             (typeReferences !== undefined && node.typeReferenceDirectives !== typeReferences) ||
72182             (libReferences !== undefined && node.libReferenceDirectives !== libReferences) ||
72183             (hasNoDefaultLib !== undefined && node.hasNoDefaultLib !== hasNoDefaultLib)) {
72184             var updated = createSynthesizedNode(290 /* SourceFile */);
72185             updated.flags |= node.flags;
72186             updated.statements = createNodeArray(statements);
72187             updated.endOfFileToken = node.endOfFileToken;
72188             updated.fileName = node.fileName;
72189             updated.path = node.path;
72190             updated.text = node.text;
72191             updated.isDeclarationFile = isDeclarationFile === undefined ? node.isDeclarationFile : isDeclarationFile;
72192             updated.referencedFiles = referencedFiles === undefined ? node.referencedFiles : referencedFiles;
72193             updated.typeReferenceDirectives = typeReferences === undefined ? node.typeReferenceDirectives : typeReferences;
72194             updated.hasNoDefaultLib = hasNoDefaultLib === undefined ? node.hasNoDefaultLib : hasNoDefaultLib;
72195             updated.libReferenceDirectives = libReferences === undefined ? node.libReferenceDirectives : libReferences;
72196             if (node.amdDependencies !== undefined)
72197                 updated.amdDependencies = node.amdDependencies;
72198             if (node.moduleName !== undefined)
72199                 updated.moduleName = node.moduleName;
72200             if (node.languageVariant !== undefined)
72201                 updated.languageVariant = node.languageVariant;
72202             if (node.renamedDependencies !== undefined)
72203                 updated.renamedDependencies = node.renamedDependencies;
72204             if (node.languageVersion !== undefined)
72205                 updated.languageVersion = node.languageVersion;
72206             if (node.scriptKind !== undefined)
72207                 updated.scriptKind = node.scriptKind;
72208             if (node.externalModuleIndicator !== undefined)
72209                 updated.externalModuleIndicator = node.externalModuleIndicator;
72210             if (node.commonJsModuleIndicator !== undefined)
72211                 updated.commonJsModuleIndicator = node.commonJsModuleIndicator;
72212             if (node.identifiers !== undefined)
72213                 updated.identifiers = node.identifiers;
72214             if (node.nodeCount !== undefined)
72215                 updated.nodeCount = node.nodeCount;
72216             if (node.identifierCount !== undefined)
72217                 updated.identifierCount = node.identifierCount;
72218             if (node.symbolCount !== undefined)
72219                 updated.symbolCount = node.symbolCount;
72220             if (node.parseDiagnostics !== undefined)
72221                 updated.parseDiagnostics = node.parseDiagnostics;
72222             if (node.bindDiagnostics !== undefined)
72223                 updated.bindDiagnostics = node.bindDiagnostics;
72224             if (node.bindSuggestionDiagnostics !== undefined)
72225                 updated.bindSuggestionDiagnostics = node.bindSuggestionDiagnostics;
72226             if (node.lineMap !== undefined)
72227                 updated.lineMap = node.lineMap;
72228             if (node.classifiableNames !== undefined)
72229                 updated.classifiableNames = node.classifiableNames;
72230             if (node.resolvedModules !== undefined)
72231                 updated.resolvedModules = node.resolvedModules;
72232             if (node.resolvedTypeReferenceDirectiveNames !== undefined)
72233                 updated.resolvedTypeReferenceDirectiveNames = node.resolvedTypeReferenceDirectiveNames;
72234             if (node.imports !== undefined)
72235                 updated.imports = node.imports;
72236             if (node.moduleAugmentations !== undefined)
72237                 updated.moduleAugmentations = node.moduleAugmentations;
72238             if (node.pragmas !== undefined)
72239                 updated.pragmas = node.pragmas;
72240             if (node.localJsxFactory !== undefined)
72241                 updated.localJsxFactory = node.localJsxFactory;
72242             if (node.localJsxNamespace !== undefined)
72243                 updated.localJsxNamespace = node.localJsxNamespace;
72244             return updateNode(updated, node);
72245         }
72246         return node;
72247     }
72248     ts.updateSourceFileNode = updateSourceFileNode;
72249     /**
72250      * Creates a shallow, memberwise clone of a node for mutation.
72251      */
72252     function getMutableClone(node) {
72253         var clone = getSynthesizedClone(node);
72254         clone.pos = node.pos;
72255         clone.end = node.end;
72256         clone.parent = node.parent;
72257         return clone;
72258     }
72259     ts.getMutableClone = getMutableClone;
72260     // Transformation nodes
72261     /**
72262      * Creates a synthetic statement to act as a placeholder for a not-emitted statement in
72263      * order to preserve comments.
72264      *
72265      * @param original The original statement.
72266      */
72267     function createNotEmittedStatement(original) {
72268         var node = createSynthesizedNode(325 /* NotEmittedStatement */);
72269         node.original = original;
72270         setTextRange(node, original);
72271         return node;
72272     }
72273     ts.createNotEmittedStatement = createNotEmittedStatement;
72274     /**
72275      * Creates a synthetic element to act as a placeholder for the end of an emitted declaration in
72276      * order to properly emit exports.
72277      */
72278     /* @internal */
72279     function createEndOfDeclarationMarker(original) {
72280         var node = createSynthesizedNode(329 /* EndOfDeclarationMarker */);
72281         node.emitNode = {};
72282         node.original = original;
72283         return node;
72284     }
72285     ts.createEndOfDeclarationMarker = createEndOfDeclarationMarker;
72286     /**
72287      * Creates a synthetic element to act as a placeholder for the beginning of a merged declaration in
72288      * order to properly emit exports.
72289      */
72290     /* @internal */
72291     function createMergeDeclarationMarker(original) {
72292         var node = createSynthesizedNode(328 /* MergeDeclarationMarker */);
72293         node.emitNode = {};
72294         node.original = original;
72295         return node;
72296     }
72297     ts.createMergeDeclarationMarker = createMergeDeclarationMarker;
72298     /**
72299      * Creates a synthetic expression to act as a placeholder for a not-emitted expression in
72300      * order to preserve comments or sourcemap positions.
72301      *
72302      * @param expression The inner expression to emit.
72303      * @param original The original outer expression.
72304      * @param location The location for the expression. Defaults to the positions from "original" if provided.
72305      */
72306     function createPartiallyEmittedExpression(expression, original) {
72307         var node = createSynthesizedNode(326 /* PartiallyEmittedExpression */);
72308         node.expression = expression;
72309         node.original = original;
72310         setTextRange(node, original);
72311         return node;
72312     }
72313     ts.createPartiallyEmittedExpression = createPartiallyEmittedExpression;
72314     function updatePartiallyEmittedExpression(node, expression) {
72315         if (node.expression !== expression) {
72316             return updateNode(createPartiallyEmittedExpression(expression, node.original), node);
72317         }
72318         return node;
72319     }
72320     ts.updatePartiallyEmittedExpression = updatePartiallyEmittedExpression;
72321     function flattenCommaElements(node) {
72322         if (ts.nodeIsSynthesized(node) && !ts.isParseTreeNode(node) && !node.original && !node.emitNode && !node.id) {
72323             if (node.kind === 327 /* CommaListExpression */) {
72324                 return node.elements;
72325             }
72326             if (ts.isBinaryExpression(node) && node.operatorToken.kind === 27 /* CommaToken */) {
72327                 return [node.left, node.right];
72328             }
72329         }
72330         return node;
72331     }
72332     function createCommaList(elements) {
72333         var node = createSynthesizedNode(327 /* CommaListExpression */);
72334         node.elements = createNodeArray(ts.sameFlatMap(elements, flattenCommaElements));
72335         return node;
72336     }
72337     ts.createCommaList = createCommaList;
72338     function updateCommaList(node, elements) {
72339         return node.elements !== elements
72340             ? updateNode(createCommaList(elements), node)
72341             : node;
72342     }
72343     ts.updateCommaList = updateCommaList;
72344     /* @internal */
72345     function createSyntheticReferenceExpression(expression, thisArg) {
72346         var node = createSynthesizedNode(330 /* SyntheticReferenceExpression */);
72347         node.expression = expression;
72348         node.thisArg = thisArg;
72349         return node;
72350     }
72351     ts.createSyntheticReferenceExpression = createSyntheticReferenceExpression;
72352     /* @internal */
72353     function updateSyntheticReferenceExpression(node, expression, thisArg) {
72354         return node.expression !== expression
72355             || node.thisArg !== thisArg
72356             ? updateNode(createSyntheticReferenceExpression(expression, thisArg), node)
72357             : node;
72358     }
72359     ts.updateSyntheticReferenceExpression = updateSyntheticReferenceExpression;
72360     function createBundle(sourceFiles, prepends) {
72361         if (prepends === void 0) { prepends = ts.emptyArray; }
72362         var node = ts.createNode(291 /* Bundle */);
72363         node.prepends = prepends;
72364         node.sourceFiles = sourceFiles;
72365         return node;
72366     }
72367     ts.createBundle = createBundle;
72368     var allUnscopedEmitHelpers;
72369     function getAllUnscopedEmitHelpers() {
72370         return allUnscopedEmitHelpers || (allUnscopedEmitHelpers = ts.arrayToMap([
72371             ts.valuesHelper,
72372             ts.readHelper,
72373             ts.spreadHelper,
72374             ts.spreadArraysHelper,
72375             ts.restHelper,
72376             ts.decorateHelper,
72377             ts.metadataHelper,
72378             ts.paramHelper,
72379             ts.awaiterHelper,
72380             ts.assignHelper,
72381             ts.awaitHelper,
72382             ts.asyncGeneratorHelper,
72383             ts.asyncDelegator,
72384             ts.asyncValues,
72385             ts.extendsHelper,
72386             ts.templateObjectHelper,
72387             ts.generatorHelper,
72388             ts.importStarHelper,
72389             ts.importDefaultHelper,
72390             ts.classPrivateFieldGetHelper,
72391             ts.classPrivateFieldSetHelper,
72392             ts.createBindingHelper,
72393             ts.setModuleDefaultHelper
72394         ], function (helper) { return helper.name; }));
72395     }
72396     function createUnparsedSource() {
72397         var node = ts.createNode(292 /* UnparsedSource */);
72398         node.prologues = ts.emptyArray;
72399         node.referencedFiles = ts.emptyArray;
72400         node.libReferenceDirectives = ts.emptyArray;
72401         node.getLineAndCharacterOfPosition = function (pos) { return ts.getLineAndCharacterOfPosition(node, pos); };
72402         return node;
72403     }
72404     function createUnparsedSourceFile(textOrInputFiles, mapPathOrType, mapTextOrStripInternal) {
72405         var node = createUnparsedSource();
72406         var stripInternal;
72407         var bundleFileInfo;
72408         if (!ts.isString(textOrInputFiles)) {
72409             ts.Debug.assert(mapPathOrType === "js" || mapPathOrType === "dts");
72410             node.fileName = (mapPathOrType === "js" ? textOrInputFiles.javascriptPath : textOrInputFiles.declarationPath) || "";
72411             node.sourceMapPath = mapPathOrType === "js" ? textOrInputFiles.javascriptMapPath : textOrInputFiles.declarationMapPath;
72412             Object.defineProperties(node, {
72413                 text: { get: function () { return mapPathOrType === "js" ? textOrInputFiles.javascriptText : textOrInputFiles.declarationText; } },
72414                 sourceMapText: { get: function () { return mapPathOrType === "js" ? textOrInputFiles.javascriptMapText : textOrInputFiles.declarationMapText; } },
72415             });
72416             if (textOrInputFiles.buildInfo && textOrInputFiles.buildInfo.bundle) {
72417                 node.oldFileOfCurrentEmit = textOrInputFiles.oldFileOfCurrentEmit;
72418                 ts.Debug.assert(mapTextOrStripInternal === undefined || typeof mapTextOrStripInternal === "boolean");
72419                 stripInternal = mapTextOrStripInternal;
72420                 bundleFileInfo = mapPathOrType === "js" ? textOrInputFiles.buildInfo.bundle.js : textOrInputFiles.buildInfo.bundle.dts;
72421                 if (node.oldFileOfCurrentEmit) {
72422                     parseOldFileOfCurrentEmit(node, ts.Debug.checkDefined(bundleFileInfo));
72423                     return node;
72424                 }
72425             }
72426         }
72427         else {
72428             node.fileName = "";
72429             node.text = textOrInputFiles;
72430             node.sourceMapPath = mapPathOrType;
72431             node.sourceMapText = mapTextOrStripInternal;
72432         }
72433         ts.Debug.assert(!node.oldFileOfCurrentEmit);
72434         parseUnparsedSourceFile(node, bundleFileInfo, stripInternal);
72435         return node;
72436     }
72437     ts.createUnparsedSourceFile = createUnparsedSourceFile;
72438     function parseUnparsedSourceFile(node, bundleFileInfo, stripInternal) {
72439         var prologues;
72440         var helpers;
72441         var referencedFiles;
72442         var typeReferenceDirectives;
72443         var libReferenceDirectives;
72444         var texts;
72445         for (var _i = 0, _a = bundleFileInfo ? bundleFileInfo.sections : ts.emptyArray; _i < _a.length; _i++) {
72446             var section = _a[_i];
72447             switch (section.kind) {
72448                 case "prologue" /* Prologue */:
72449                     (prologues || (prologues = [])).push(createUnparsedNode(section, node));
72450                     break;
72451                 case "emitHelpers" /* EmitHelpers */:
72452                     (helpers || (helpers = [])).push(getAllUnscopedEmitHelpers().get(section.data));
72453                     break;
72454                 case "no-default-lib" /* NoDefaultLib */:
72455                     node.hasNoDefaultLib = true;
72456                     break;
72457                 case "reference" /* Reference */:
72458                     (referencedFiles || (referencedFiles = [])).push({ pos: -1, end: -1, fileName: section.data });
72459                     break;
72460                 case "type" /* Type */:
72461                     (typeReferenceDirectives || (typeReferenceDirectives = [])).push(section.data);
72462                     break;
72463                 case "lib" /* Lib */:
72464                     (libReferenceDirectives || (libReferenceDirectives = [])).push({ pos: -1, end: -1, fileName: section.data });
72465                     break;
72466                 case "prepend" /* Prepend */:
72467                     var prependNode = createUnparsedNode(section, node);
72468                     var prependTexts = void 0;
72469                     for (var _b = 0, _c = section.texts; _b < _c.length; _b++) {
72470                         var text = _c[_b];
72471                         if (!stripInternal || text.kind !== "internal" /* Internal */) {
72472                             (prependTexts || (prependTexts = [])).push(createUnparsedNode(text, node));
72473                         }
72474                     }
72475                     prependNode.texts = prependTexts || ts.emptyArray;
72476                     (texts || (texts = [])).push(prependNode);
72477                     break;
72478                 case "internal" /* Internal */:
72479                     if (stripInternal) {
72480                         if (!texts)
72481                             texts = [];
72482                         break;
72483                     }
72484                 // falls through
72485                 case "text" /* Text */:
72486                     (texts || (texts = [])).push(createUnparsedNode(section, node));
72487                     break;
72488                 default:
72489                     ts.Debug.assertNever(section);
72490             }
72491         }
72492         node.prologues = prologues || ts.emptyArray;
72493         node.helpers = helpers;
72494         node.referencedFiles = referencedFiles || ts.emptyArray;
72495         node.typeReferenceDirectives = typeReferenceDirectives;
72496         node.libReferenceDirectives = libReferenceDirectives || ts.emptyArray;
72497         node.texts = texts || [createUnparsedNode({ kind: "text" /* Text */, pos: 0, end: node.text.length }, node)];
72498     }
72499     function parseOldFileOfCurrentEmit(node, bundleFileInfo) {
72500         ts.Debug.assert(!!node.oldFileOfCurrentEmit);
72501         var texts;
72502         var syntheticReferences;
72503         for (var _i = 0, _a = bundleFileInfo.sections; _i < _a.length; _i++) {
72504             var section = _a[_i];
72505             switch (section.kind) {
72506                 case "internal" /* Internal */:
72507                 case "text" /* Text */:
72508                     (texts || (texts = [])).push(createUnparsedNode(section, node));
72509                     break;
72510                 case "no-default-lib" /* NoDefaultLib */:
72511                 case "reference" /* Reference */:
72512                 case "type" /* Type */:
72513                 case "lib" /* Lib */:
72514                     (syntheticReferences || (syntheticReferences = [])).push(createUnparsedSyntheticReference(section, node));
72515                     break;
72516                 // Ignore
72517                 case "prologue" /* Prologue */:
72518                 case "emitHelpers" /* EmitHelpers */:
72519                 case "prepend" /* Prepend */:
72520                     break;
72521                 default:
72522                     ts.Debug.assertNever(section);
72523             }
72524         }
72525         node.texts = texts || ts.emptyArray;
72526         node.helpers = ts.map(bundleFileInfo.sources && bundleFileInfo.sources.helpers, function (name) { return getAllUnscopedEmitHelpers().get(name); });
72527         node.syntheticReferences = syntheticReferences;
72528         return node;
72529     }
72530     function mapBundleFileSectionKindToSyntaxKind(kind) {
72531         switch (kind) {
72532             case "prologue" /* Prologue */: return 285 /* UnparsedPrologue */;
72533             case "prepend" /* Prepend */: return 286 /* UnparsedPrepend */;
72534             case "internal" /* Internal */: return 288 /* UnparsedInternalText */;
72535             case "text" /* Text */: return 287 /* UnparsedText */;
72536             case "emitHelpers" /* EmitHelpers */:
72537             case "no-default-lib" /* NoDefaultLib */:
72538             case "reference" /* Reference */:
72539             case "type" /* Type */:
72540             case "lib" /* Lib */:
72541                 return ts.Debug.fail("BundleFileSectionKind: " + kind + " not yet mapped to SyntaxKind");
72542             default:
72543                 return ts.Debug.assertNever(kind);
72544         }
72545     }
72546     function createUnparsedNode(section, parent) {
72547         var node = ts.createNode(mapBundleFileSectionKindToSyntaxKind(section.kind), section.pos, section.end);
72548         node.parent = parent;
72549         node.data = section.data;
72550         return node;
72551     }
72552     function createUnparsedSyntheticReference(section, parent) {
72553         var node = ts.createNode(289 /* UnparsedSyntheticReference */, section.pos, section.end);
72554         node.parent = parent;
72555         node.data = section.data;
72556         node.section = section;
72557         return node;
72558     }
72559     function createInputFiles(javascriptTextOrReadFileText, declarationTextOrJavascriptPath, javascriptMapPath, javascriptMapTextOrDeclarationPath, declarationMapPath, declarationMapTextOrBuildInfoPath, javascriptPath, declarationPath, buildInfoPath, buildInfo, oldFileOfCurrentEmit) {
72560         var node = ts.createNode(293 /* InputFiles */);
72561         if (!ts.isString(javascriptTextOrReadFileText)) {
72562             var cache_1 = ts.createMap();
72563             var textGetter_1 = function (path) {
72564                 if (path === undefined)
72565                     return undefined;
72566                 var value = cache_1.get(path);
72567                 if (value === undefined) {
72568                     value = javascriptTextOrReadFileText(path);
72569                     cache_1.set(path, value !== undefined ? value : false);
72570                 }
72571                 return value !== false ? value : undefined;
72572             };
72573             var definedTextGetter_1 = function (path) {
72574                 var result = textGetter_1(path);
72575                 return result !== undefined ? result : "/* Input file " + path + " was missing */\r\n";
72576             };
72577             var buildInfo_1;
72578             var getAndCacheBuildInfo_1 = function (getText) {
72579                 if (buildInfo_1 === undefined) {
72580                     var result = getText();
72581                     buildInfo_1 = result !== undefined ? ts.getBuildInfo(result) : false;
72582                 }
72583                 return buildInfo_1 || undefined;
72584             };
72585             node.javascriptPath = declarationTextOrJavascriptPath;
72586             node.javascriptMapPath = javascriptMapPath;
72587             node.declarationPath = ts.Debug.checkDefined(javascriptMapTextOrDeclarationPath);
72588             node.declarationMapPath = declarationMapPath;
72589             node.buildInfoPath = declarationMapTextOrBuildInfoPath;
72590             Object.defineProperties(node, {
72591                 javascriptText: { get: function () { return definedTextGetter_1(declarationTextOrJavascriptPath); } },
72592                 javascriptMapText: { get: function () { return textGetter_1(javascriptMapPath); } },
72593                 declarationText: { get: function () { return definedTextGetter_1(ts.Debug.checkDefined(javascriptMapTextOrDeclarationPath)); } },
72594                 declarationMapText: { get: function () { return textGetter_1(declarationMapPath); } },
72595                 buildInfo: { get: function () { return getAndCacheBuildInfo_1(function () { return textGetter_1(declarationMapTextOrBuildInfoPath); }); } }
72596             });
72597         }
72598         else {
72599             node.javascriptText = javascriptTextOrReadFileText;
72600             node.javascriptMapPath = javascriptMapPath;
72601             node.javascriptMapText = javascriptMapTextOrDeclarationPath;
72602             node.declarationText = declarationTextOrJavascriptPath;
72603             node.declarationMapPath = declarationMapPath;
72604             node.declarationMapText = declarationMapTextOrBuildInfoPath;
72605             node.javascriptPath = javascriptPath;
72606             node.declarationPath = declarationPath;
72607             node.buildInfoPath = buildInfoPath;
72608             node.buildInfo = buildInfo;
72609             node.oldFileOfCurrentEmit = oldFileOfCurrentEmit;
72610         }
72611         return node;
72612     }
72613     ts.createInputFiles = createInputFiles;
72614     function updateBundle(node, sourceFiles, prepends) {
72615         if (prepends === void 0) { prepends = ts.emptyArray; }
72616         if (node.sourceFiles !== sourceFiles || node.prepends !== prepends) {
72617             return createBundle(sourceFiles, prepends);
72618         }
72619         return node;
72620     }
72621     ts.updateBundle = updateBundle;
72622     function createImmediatelyInvokedFunctionExpression(statements, param, paramValue) {
72623         return createCall(createFunctionExpression(
72624         /*modifiers*/ undefined, 
72625         /*asteriskToken*/ undefined, 
72626         /*name*/ undefined, 
72627         /*typeParameters*/ undefined, 
72628         /*parameters*/ param ? [param] : [], 
72629         /*type*/ undefined, createBlock(statements, /*multiLine*/ true)), 
72630         /*typeArguments*/ undefined, 
72631         /*argumentsArray*/ paramValue ? [paramValue] : []);
72632     }
72633     ts.createImmediatelyInvokedFunctionExpression = createImmediatelyInvokedFunctionExpression;
72634     function createImmediatelyInvokedArrowFunction(statements, param, paramValue) {
72635         return createCall(createArrowFunction(
72636         /*modifiers*/ undefined, 
72637         /*typeParameters*/ undefined, 
72638         /*parameters*/ param ? [param] : [], 
72639         /*type*/ undefined, 
72640         /*equalsGreaterThanToken*/ undefined, createBlock(statements, /*multiLine*/ true)), 
72641         /*typeArguments*/ undefined, 
72642         /*argumentsArray*/ paramValue ? [paramValue] : []);
72643     }
72644     ts.createImmediatelyInvokedArrowFunction = createImmediatelyInvokedArrowFunction;
72645     function createComma(left, right) {
72646         return createBinary(left, 27 /* CommaToken */, right);
72647     }
72648     ts.createComma = createComma;
72649     function createLessThan(left, right) {
72650         return createBinary(left, 29 /* LessThanToken */, right);
72651     }
72652     ts.createLessThan = createLessThan;
72653     function createAssignment(left, right) {
72654         return createBinary(left, 62 /* EqualsToken */, right);
72655     }
72656     ts.createAssignment = createAssignment;
72657     function createStrictEquality(left, right) {
72658         return createBinary(left, 36 /* EqualsEqualsEqualsToken */, right);
72659     }
72660     ts.createStrictEquality = createStrictEquality;
72661     function createStrictInequality(left, right) {
72662         return createBinary(left, 37 /* ExclamationEqualsEqualsToken */, right);
72663     }
72664     ts.createStrictInequality = createStrictInequality;
72665     function createAdd(left, right) {
72666         return createBinary(left, 39 /* PlusToken */, right);
72667     }
72668     ts.createAdd = createAdd;
72669     function createSubtract(left, right) {
72670         return createBinary(left, 40 /* MinusToken */, right);
72671     }
72672     ts.createSubtract = createSubtract;
72673     function createPostfixIncrement(operand) {
72674         return createPostfix(operand, 45 /* PlusPlusToken */);
72675     }
72676     ts.createPostfixIncrement = createPostfixIncrement;
72677     function createLogicalAnd(left, right) {
72678         return createBinary(left, 55 /* AmpersandAmpersandToken */, right);
72679     }
72680     ts.createLogicalAnd = createLogicalAnd;
72681     function createLogicalOr(left, right) {
72682         return createBinary(left, 56 /* BarBarToken */, right);
72683     }
72684     ts.createLogicalOr = createLogicalOr;
72685     function createNullishCoalesce(left, right) {
72686         return createBinary(left, 60 /* QuestionQuestionToken */, right);
72687     }
72688     ts.createNullishCoalesce = createNullishCoalesce;
72689     function createLogicalNot(operand) {
72690         return createPrefix(53 /* ExclamationToken */, operand);
72691     }
72692     ts.createLogicalNot = createLogicalNot;
72693     function createVoidZero() {
72694         return createVoid(createLiteral(0));
72695     }
72696     ts.createVoidZero = createVoidZero;
72697     function createExportDefault(expression) {
72698         return createExportAssignment(/*decorators*/ undefined, /*modifiers*/ undefined, /*isExportEquals*/ false, expression);
72699     }
72700     ts.createExportDefault = createExportDefault;
72701     function createExternalModuleExport(exportName) {
72702         return createExportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, createNamedExports([createExportSpecifier(/*propertyName*/ undefined, exportName)]));
72703     }
72704     ts.createExternalModuleExport = createExternalModuleExport;
72705     // Utilities
72706     function asName(name) {
72707         return ts.isString(name) ? createIdentifier(name) : name;
72708     }
72709     function asExpression(value) {
72710         return typeof value === "string" ? createStringLiteral(value) :
72711             typeof value === "number" ? createNumericLiteral("" + value) :
72712                 typeof value === "boolean" ? value ? createTrue() : createFalse() :
72713                     value;
72714     }
72715     function asNodeArray(array) {
72716         return array ? createNodeArray(array) : undefined;
72717     }
72718     function asToken(value) {
72719         return typeof value === "number" ? createToken(value) : value;
72720     }
72721     function asEmbeddedStatement(statement) {
72722         return statement && ts.isNotEmittedStatement(statement) ? setTextRange(setOriginalNode(createEmptyStatement(), statement), statement) : statement;
72723     }
72724     /**
72725      * Clears any EmitNode entries from parse-tree nodes.
72726      * @param sourceFile A source file.
72727      */
72728     function disposeEmitNodes(sourceFile) {
72729         // During transformation we may need to annotate a parse tree node with transient
72730         // transformation properties. As parse tree nodes live longer than transformation
72731         // nodes, we need to make sure we reclaim any memory allocated for custom ranges
72732         // from these nodes to ensure we do not hold onto entire subtrees just for position
72733         // information. We also need to reset these nodes to a pre-transformation state
72734         // for incremental parsing scenarios so that we do not impact later emit.
72735         sourceFile = ts.getSourceFileOfNode(ts.getParseTreeNode(sourceFile));
72736         var emitNode = sourceFile && sourceFile.emitNode;
72737         var annotatedNodes = emitNode && emitNode.annotatedNodes;
72738         if (annotatedNodes) {
72739             for (var _i = 0, annotatedNodes_1 = annotatedNodes; _i < annotatedNodes_1.length; _i++) {
72740                 var node = annotatedNodes_1[_i];
72741                 node.emitNode = undefined;
72742             }
72743         }
72744     }
72745     ts.disposeEmitNodes = disposeEmitNodes;
72746     /**
72747      * Associates a node with the current transformation, initializing
72748      * various transient transformation properties.
72749      */
72750     /* @internal */
72751     function getOrCreateEmitNode(node) {
72752         if (!node.emitNode) {
72753             if (ts.isParseTreeNode(node)) {
72754                 // To avoid holding onto transformation artifacts, we keep track of any
72755                 // parse tree node we are annotating. This allows us to clean them up after
72756                 // all transformations have completed.
72757                 if (node.kind === 290 /* SourceFile */) {
72758                     return node.emitNode = { annotatedNodes: [node] };
72759                 }
72760                 var sourceFile = ts.getSourceFileOfNode(ts.getParseTreeNode(ts.getSourceFileOfNode(node)));
72761                 getOrCreateEmitNode(sourceFile).annotatedNodes.push(node);
72762             }
72763             node.emitNode = {};
72764         }
72765         return node.emitNode;
72766     }
72767     ts.getOrCreateEmitNode = getOrCreateEmitNode;
72768     /**
72769      * Sets `EmitFlags.NoComments` on a node and removes any leading and trailing synthetic comments.
72770      * @internal
72771      */
72772     function removeAllComments(node) {
72773         var emitNode = getOrCreateEmitNode(node);
72774         emitNode.flags |= 1536 /* NoComments */;
72775         emitNode.leadingComments = undefined;
72776         emitNode.trailingComments = undefined;
72777         return node;
72778     }
72779     ts.removeAllComments = removeAllComments;
72780     function setTextRange(range, location) {
72781         if (location) {
72782             range.pos = location.pos;
72783             range.end = location.end;
72784         }
72785         return range;
72786     }
72787     ts.setTextRange = setTextRange;
72788     /**
72789      * Sets flags that control emit behavior of a node.
72790      */
72791     function setEmitFlags(node, emitFlags) {
72792         getOrCreateEmitNode(node).flags = emitFlags;
72793         return node;
72794     }
72795     ts.setEmitFlags = setEmitFlags;
72796     /**
72797      * Sets flags that control emit behavior of a node.
72798      */
72799     /* @internal */
72800     function addEmitFlags(node, emitFlags) {
72801         var emitNode = getOrCreateEmitNode(node);
72802         emitNode.flags = emitNode.flags | emitFlags;
72803         return node;
72804     }
72805     ts.addEmitFlags = addEmitFlags;
72806     /**
72807      * Gets a custom text range to use when emitting source maps.
72808      */
72809     function getSourceMapRange(node) {
72810         var emitNode = node.emitNode;
72811         return (emitNode && emitNode.sourceMapRange) || node;
72812     }
72813     ts.getSourceMapRange = getSourceMapRange;
72814     /**
72815      * Sets a custom text range to use when emitting source maps.
72816      */
72817     function setSourceMapRange(node, range) {
72818         getOrCreateEmitNode(node).sourceMapRange = range;
72819         return node;
72820     }
72821     ts.setSourceMapRange = setSourceMapRange;
72822     var SourceMapSource;
72823     /**
72824      * Create an external source map source file reference
72825      */
72826     function createSourceMapSource(fileName, text, skipTrivia) {
72827         return new (SourceMapSource || (SourceMapSource = ts.objectAllocator.getSourceMapSourceConstructor()))(fileName, text, skipTrivia);
72828     }
72829     ts.createSourceMapSource = createSourceMapSource;
72830     /**
72831      * Gets the TextRange to use for source maps for a token of a node.
72832      */
72833     function getTokenSourceMapRange(node, token) {
72834         var emitNode = node.emitNode;
72835         var tokenSourceMapRanges = emitNode && emitNode.tokenSourceMapRanges;
72836         return tokenSourceMapRanges && tokenSourceMapRanges[token];
72837     }
72838     ts.getTokenSourceMapRange = getTokenSourceMapRange;
72839     /**
72840      * Sets the TextRange to use for source maps for a token of a node.
72841      */
72842     function setTokenSourceMapRange(node, token, range) {
72843         var emitNode = getOrCreateEmitNode(node);
72844         var tokenSourceMapRanges = emitNode.tokenSourceMapRanges || (emitNode.tokenSourceMapRanges = []);
72845         tokenSourceMapRanges[token] = range;
72846         return node;
72847     }
72848     ts.setTokenSourceMapRange = setTokenSourceMapRange;
72849     /**
72850      * Gets a custom text range to use when emitting comments.
72851      */
72852     /*@internal*/
72853     function getStartsOnNewLine(node) {
72854         var emitNode = node.emitNode;
72855         return emitNode && emitNode.startsOnNewLine;
72856     }
72857     ts.getStartsOnNewLine = getStartsOnNewLine;
72858     /**
72859      * Sets a custom text range to use when emitting comments.
72860      */
72861     /*@internal*/
72862     function setStartsOnNewLine(node, newLine) {
72863         getOrCreateEmitNode(node).startsOnNewLine = newLine;
72864         return node;
72865     }
72866     ts.setStartsOnNewLine = setStartsOnNewLine;
72867     /**
72868      * Gets a custom text range to use when emitting comments.
72869      */
72870     function getCommentRange(node) {
72871         var emitNode = node.emitNode;
72872         return (emitNode && emitNode.commentRange) || node;
72873     }
72874     ts.getCommentRange = getCommentRange;
72875     /**
72876      * Sets a custom text range to use when emitting comments.
72877      */
72878     function setCommentRange(node, range) {
72879         getOrCreateEmitNode(node).commentRange = range;
72880         return node;
72881     }
72882     ts.setCommentRange = setCommentRange;
72883     function getSyntheticLeadingComments(node) {
72884         var emitNode = node.emitNode;
72885         return emitNode && emitNode.leadingComments;
72886     }
72887     ts.getSyntheticLeadingComments = getSyntheticLeadingComments;
72888     function setSyntheticLeadingComments(node, comments) {
72889         getOrCreateEmitNode(node).leadingComments = comments;
72890         return node;
72891     }
72892     ts.setSyntheticLeadingComments = setSyntheticLeadingComments;
72893     function addSyntheticLeadingComment(node, kind, text, hasTrailingNewLine) {
72894         return setSyntheticLeadingComments(node, ts.append(getSyntheticLeadingComments(node), { kind: kind, pos: -1, end: -1, hasTrailingNewLine: hasTrailingNewLine, text: text }));
72895     }
72896     ts.addSyntheticLeadingComment = addSyntheticLeadingComment;
72897     function getSyntheticTrailingComments(node) {
72898         var emitNode = node.emitNode;
72899         return emitNode && emitNode.trailingComments;
72900     }
72901     ts.getSyntheticTrailingComments = getSyntheticTrailingComments;
72902     function setSyntheticTrailingComments(node, comments) {
72903         getOrCreateEmitNode(node).trailingComments = comments;
72904         return node;
72905     }
72906     ts.setSyntheticTrailingComments = setSyntheticTrailingComments;
72907     function addSyntheticTrailingComment(node, kind, text, hasTrailingNewLine) {
72908         return setSyntheticTrailingComments(node, ts.append(getSyntheticTrailingComments(node), { kind: kind, pos: -1, end: -1, hasTrailingNewLine: hasTrailingNewLine, text: text }));
72909     }
72910     ts.addSyntheticTrailingComment = addSyntheticTrailingComment;
72911     function moveSyntheticComments(node, original) {
72912         setSyntheticLeadingComments(node, getSyntheticLeadingComments(original));
72913         setSyntheticTrailingComments(node, getSyntheticTrailingComments(original));
72914         var emit = getOrCreateEmitNode(original);
72915         emit.leadingComments = undefined;
72916         emit.trailingComments = undefined;
72917         return node;
72918     }
72919     ts.moveSyntheticComments = moveSyntheticComments;
72920     /** @internal */
72921     function ignoreSourceNewlines(node) {
72922         getOrCreateEmitNode(node).flags |= 134217728 /* IgnoreSourceNewlines */;
72923         return node;
72924     }
72925     ts.ignoreSourceNewlines = ignoreSourceNewlines;
72926     /**
72927      * Gets the constant value to emit for an expression.
72928      */
72929     function getConstantValue(node) {
72930         var emitNode = node.emitNode;
72931         return emitNode && emitNode.constantValue;
72932     }
72933     ts.getConstantValue = getConstantValue;
72934     /**
72935      * Sets the constant value to emit for an expression.
72936      */
72937     function setConstantValue(node, value) {
72938         var emitNode = getOrCreateEmitNode(node);
72939         emitNode.constantValue = value;
72940         return node;
72941     }
72942     ts.setConstantValue = setConstantValue;
72943     /**
72944      * Adds an EmitHelper to a node.
72945      */
72946     function addEmitHelper(node, helper) {
72947         var emitNode = getOrCreateEmitNode(node);
72948         emitNode.helpers = ts.append(emitNode.helpers, helper);
72949         return node;
72950     }
72951     ts.addEmitHelper = addEmitHelper;
72952     /**
72953      * Add EmitHelpers to a node.
72954      */
72955     function addEmitHelpers(node, helpers) {
72956         if (ts.some(helpers)) {
72957             var emitNode = getOrCreateEmitNode(node);
72958             for (var _i = 0, helpers_1 = helpers; _i < helpers_1.length; _i++) {
72959                 var helper = helpers_1[_i];
72960                 emitNode.helpers = ts.appendIfUnique(emitNode.helpers, helper);
72961             }
72962         }
72963         return node;
72964     }
72965     ts.addEmitHelpers = addEmitHelpers;
72966     /**
72967      * Removes an EmitHelper from a node.
72968      */
72969     function removeEmitHelper(node, helper) {
72970         var emitNode = node.emitNode;
72971         if (emitNode) {
72972             var helpers = emitNode.helpers;
72973             if (helpers) {
72974                 return ts.orderedRemoveItem(helpers, helper);
72975             }
72976         }
72977         return false;
72978     }
72979     ts.removeEmitHelper = removeEmitHelper;
72980     /**
72981      * Gets the EmitHelpers of a node.
72982      */
72983     function getEmitHelpers(node) {
72984         var emitNode = node.emitNode;
72985         return emitNode && emitNode.helpers;
72986     }
72987     ts.getEmitHelpers = getEmitHelpers;
72988     /**
72989      * Moves matching emit helpers from a source node to a target node.
72990      */
72991     function moveEmitHelpers(source, target, predicate) {
72992         var sourceEmitNode = source.emitNode;
72993         var sourceEmitHelpers = sourceEmitNode && sourceEmitNode.helpers;
72994         if (!ts.some(sourceEmitHelpers))
72995             return;
72996         var targetEmitNode = getOrCreateEmitNode(target);
72997         var helpersRemoved = 0;
72998         for (var i = 0; i < sourceEmitHelpers.length; i++) {
72999             var helper = sourceEmitHelpers[i];
73000             if (predicate(helper)) {
73001                 helpersRemoved++;
73002                 targetEmitNode.helpers = ts.appendIfUnique(targetEmitNode.helpers, helper);
73003             }
73004             else if (helpersRemoved > 0) {
73005                 sourceEmitHelpers[i - helpersRemoved] = helper;
73006             }
73007         }
73008         if (helpersRemoved > 0) {
73009             sourceEmitHelpers.length -= helpersRemoved;
73010         }
73011     }
73012     ts.moveEmitHelpers = moveEmitHelpers;
73013     /* @internal */
73014     function compareEmitHelpers(x, y) {
73015         if (x === y)
73016             return 0 /* EqualTo */;
73017         if (x.priority === y.priority)
73018             return 0 /* EqualTo */;
73019         if (x.priority === undefined)
73020             return 1 /* GreaterThan */;
73021         if (y.priority === undefined)
73022             return -1 /* LessThan */;
73023         return ts.compareValues(x.priority, y.priority);
73024     }
73025     ts.compareEmitHelpers = compareEmitHelpers;
73026     function setOriginalNode(node, original) {
73027         node.original = original;
73028         if (original) {
73029             var emitNode = original.emitNode;
73030             if (emitNode)
73031                 node.emitNode = mergeEmitNode(emitNode, node.emitNode);
73032         }
73033         return node;
73034     }
73035     ts.setOriginalNode = setOriginalNode;
73036     function mergeEmitNode(sourceEmitNode, destEmitNode) {
73037         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;
73038         if (!destEmitNode)
73039             destEmitNode = {};
73040         // We are using `.slice()` here in case `destEmitNode.leadingComments` is pushed to later.
73041         if (leadingComments)
73042             destEmitNode.leadingComments = ts.addRange(leadingComments.slice(), destEmitNode.leadingComments);
73043         if (trailingComments)
73044             destEmitNode.trailingComments = ts.addRange(trailingComments.slice(), destEmitNode.trailingComments);
73045         if (flags)
73046             destEmitNode.flags = flags;
73047         if (commentRange)
73048             destEmitNode.commentRange = commentRange;
73049         if (sourceMapRange)
73050             destEmitNode.sourceMapRange = sourceMapRange;
73051         if (tokenSourceMapRanges)
73052             destEmitNode.tokenSourceMapRanges = mergeTokenSourceMapRanges(tokenSourceMapRanges, destEmitNode.tokenSourceMapRanges);
73053         if (constantValue !== undefined)
73054             destEmitNode.constantValue = constantValue;
73055         if (helpers)
73056             destEmitNode.helpers = ts.addRange(destEmitNode.helpers, helpers);
73057         if (startsOnNewLine !== undefined)
73058             destEmitNode.startsOnNewLine = startsOnNewLine;
73059         return destEmitNode;
73060     }
73061     function mergeTokenSourceMapRanges(sourceRanges, destRanges) {
73062         if (!destRanges)
73063             destRanges = [];
73064         for (var key in sourceRanges) {
73065             destRanges[key] = sourceRanges[key];
73066         }
73067         return destRanges;
73068     }
73069 })(ts || (ts = {}));
73070 /* @internal */
73071 var ts;
73072 (function (ts) {
73073     ts.nullTransformationContext = {
73074         enableEmitNotification: ts.noop,
73075         enableSubstitution: ts.noop,
73076         endLexicalEnvironment: ts.returnUndefined,
73077         getCompilerOptions: function () { return ({}); },
73078         getEmitHost: ts.notImplemented,
73079         getEmitResolver: ts.notImplemented,
73080         setLexicalEnvironmentFlags: ts.noop,
73081         getLexicalEnvironmentFlags: function () { return 0; },
73082         hoistFunctionDeclaration: ts.noop,
73083         hoistVariableDeclaration: ts.noop,
73084         addInitializationStatement: ts.noop,
73085         isEmitNotificationEnabled: ts.notImplemented,
73086         isSubstitutionEnabled: ts.notImplemented,
73087         onEmitNode: ts.noop,
73088         onSubstituteNode: ts.notImplemented,
73089         readEmitHelpers: ts.notImplemented,
73090         requestEmitHelper: ts.noop,
73091         resumeLexicalEnvironment: ts.noop,
73092         startLexicalEnvironment: ts.noop,
73093         suspendLexicalEnvironment: ts.noop,
73094         addDiagnostic: ts.noop,
73095     };
73096     function createTypeCheck(value, tag) {
73097         return tag === "undefined"
73098             ? ts.createStrictEquality(value, ts.createVoidZero())
73099             : ts.createStrictEquality(ts.createTypeOf(value), ts.createLiteral(tag));
73100     }
73101     ts.createTypeCheck = createTypeCheck;
73102     function createMemberAccessForPropertyName(target, memberName, location) {
73103         if (ts.isComputedPropertyName(memberName)) {
73104             return ts.setTextRange(ts.createElementAccess(target, memberName.expression), location);
73105         }
73106         else {
73107             var expression = ts.setTextRange((ts.isIdentifier(memberName) || ts.isPrivateIdentifier(memberName))
73108                 ? ts.createPropertyAccess(target, memberName)
73109                 : ts.createElementAccess(target, memberName), memberName);
73110             ts.getOrCreateEmitNode(expression).flags |= 64 /* NoNestedSourceMaps */;
73111             return expression;
73112         }
73113     }
73114     ts.createMemberAccessForPropertyName = createMemberAccessForPropertyName;
73115     function createFunctionCall(func, thisArg, argumentsList, location) {
73116         return ts.setTextRange(ts.createCall(ts.createPropertyAccess(func, "call"), 
73117         /*typeArguments*/ undefined, __spreadArrays([
73118             thisArg
73119         ], argumentsList)), location);
73120     }
73121     ts.createFunctionCall = createFunctionCall;
73122     function createFunctionApply(func, thisArg, argumentsExpression, location) {
73123         return ts.setTextRange(ts.createCall(ts.createPropertyAccess(func, "apply"), 
73124         /*typeArguments*/ undefined, [
73125             thisArg,
73126             argumentsExpression
73127         ]), location);
73128     }
73129     ts.createFunctionApply = createFunctionApply;
73130     function createArraySlice(array, start) {
73131         var argumentsList = [];
73132         if (start !== undefined) {
73133             argumentsList.push(typeof start === "number" ? ts.createLiteral(start) : start);
73134         }
73135         return ts.createCall(ts.createPropertyAccess(array, "slice"), /*typeArguments*/ undefined, argumentsList);
73136     }
73137     ts.createArraySlice = createArraySlice;
73138     function createArrayConcat(array, values) {
73139         return ts.createCall(ts.createPropertyAccess(array, "concat"), 
73140         /*typeArguments*/ undefined, values);
73141     }
73142     ts.createArrayConcat = createArrayConcat;
73143     function createMathPow(left, right, location) {
73144         return ts.setTextRange(ts.createCall(ts.createPropertyAccess(ts.createIdentifier("Math"), "pow"), 
73145         /*typeArguments*/ undefined, [left, right]), location);
73146     }
73147     ts.createMathPow = createMathPow;
73148     function createReactNamespace(reactNamespace, parent) {
73149         // To ensure the emit resolver can properly resolve the namespace, we need to
73150         // treat this identifier as if it were a source tree node by clearing the `Synthesized`
73151         // flag and setting a parent node.
73152         var react = ts.createIdentifier(reactNamespace || "React");
73153         react.flags &= ~8 /* Synthesized */;
73154         // Set the parent that is in parse tree
73155         // this makes sure that parent chain is intact for checker to traverse complete scope tree
73156         react.parent = ts.getParseTreeNode(parent);
73157         return react;
73158     }
73159     function createJsxFactoryExpressionFromEntityName(jsxFactory, parent) {
73160         if (ts.isQualifiedName(jsxFactory)) {
73161             var left = createJsxFactoryExpressionFromEntityName(jsxFactory.left, parent);
73162             var right = ts.createIdentifier(ts.idText(jsxFactory.right));
73163             right.escapedText = jsxFactory.right.escapedText;
73164             return ts.createPropertyAccess(left, right);
73165         }
73166         else {
73167             return createReactNamespace(ts.idText(jsxFactory), parent);
73168         }
73169     }
73170     function createJsxFactoryExpression(jsxFactoryEntity, reactNamespace, parent) {
73171         return jsxFactoryEntity ?
73172             createJsxFactoryExpressionFromEntityName(jsxFactoryEntity, parent) :
73173             ts.createPropertyAccess(createReactNamespace(reactNamespace, parent), "createElement");
73174     }
73175     function createExpressionForJsxElement(jsxFactoryEntity, reactNamespace, tagName, props, children, parentElement, location) {
73176         var argumentsList = [tagName];
73177         if (props) {
73178             argumentsList.push(props);
73179         }
73180         if (children && children.length > 0) {
73181             if (!props) {
73182                 argumentsList.push(ts.createNull());
73183             }
73184             if (children.length > 1) {
73185                 for (var _i = 0, children_2 = children; _i < children_2.length; _i++) {
73186                     var child = children_2[_i];
73187                     startOnNewLine(child);
73188                     argumentsList.push(child);
73189                 }
73190             }
73191             else {
73192                 argumentsList.push(children[0]);
73193             }
73194         }
73195         return ts.setTextRange(ts.createCall(createJsxFactoryExpression(jsxFactoryEntity, reactNamespace, parentElement), 
73196         /*typeArguments*/ undefined, argumentsList), location);
73197     }
73198     ts.createExpressionForJsxElement = createExpressionForJsxElement;
73199     function createExpressionForJsxFragment(jsxFactoryEntity, reactNamespace, children, parentElement, location) {
73200         var tagName = ts.createPropertyAccess(createReactNamespace(reactNamespace, parentElement), "Fragment");
73201         var argumentsList = [tagName];
73202         argumentsList.push(ts.createNull());
73203         if (children && children.length > 0) {
73204             if (children.length > 1) {
73205                 for (var _i = 0, children_3 = children; _i < children_3.length; _i++) {
73206                     var child = children_3[_i];
73207                     startOnNewLine(child);
73208                     argumentsList.push(child);
73209                 }
73210             }
73211             else {
73212                 argumentsList.push(children[0]);
73213             }
73214         }
73215         return ts.setTextRange(ts.createCall(createJsxFactoryExpression(jsxFactoryEntity, reactNamespace, parentElement), 
73216         /*typeArguments*/ undefined, argumentsList), location);
73217     }
73218     ts.createExpressionForJsxFragment = createExpressionForJsxFragment;
73219     // Helpers
73220     /**
73221      * Gets an identifier for the name of an *unscoped* emit helper.
73222      */
73223     function getUnscopedHelperName(name) {
73224         return ts.setEmitFlags(ts.createIdentifier(name), 4096 /* HelperName */ | 2 /* AdviseOnEmitNode */);
73225     }
73226     ts.getUnscopedHelperName = getUnscopedHelperName;
73227     ts.valuesHelper = {
73228         name: "typescript:values",
73229         importName: "__values",
73230         scoped: false,
73231         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            };"
73232     };
73233     function createValuesHelper(context, expression, location) {
73234         context.requestEmitHelper(ts.valuesHelper);
73235         return ts.setTextRange(ts.createCall(getUnscopedHelperName("__values"), 
73236         /*typeArguments*/ undefined, [expression]), location);
73237     }
73238     ts.createValuesHelper = createValuesHelper;
73239     ts.readHelper = {
73240         name: "typescript:read",
73241         importName: "__read",
73242         scoped: false,
73243         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            };"
73244     };
73245     function createReadHelper(context, iteratorRecord, count, location) {
73246         context.requestEmitHelper(ts.readHelper);
73247         return ts.setTextRange(ts.createCall(getUnscopedHelperName("__read"), 
73248         /*typeArguments*/ undefined, count !== undefined
73249             ? [iteratorRecord, ts.createLiteral(count)]
73250             : [iteratorRecord]), location);
73251     }
73252     ts.createReadHelper = createReadHelper;
73253     ts.spreadHelper = {
73254         name: "typescript:spread",
73255         importName: "__spread",
73256         scoped: false,
73257         dependencies: [ts.readHelper],
73258         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            };"
73259     };
73260     function createSpreadHelper(context, argumentList, location) {
73261         context.requestEmitHelper(ts.spreadHelper);
73262         return ts.setTextRange(ts.createCall(getUnscopedHelperName("__spread"), 
73263         /*typeArguments*/ undefined, argumentList), location);
73264     }
73265     ts.createSpreadHelper = createSpreadHelper;
73266     ts.spreadArraysHelper = {
73267         name: "typescript:spreadArrays",
73268         importName: "__spreadArrays",
73269         scoped: false,
73270         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            };"
73271     };
73272     function createSpreadArraysHelper(context, argumentList, location) {
73273         context.requestEmitHelper(ts.spreadArraysHelper);
73274         return ts.setTextRange(ts.createCall(getUnscopedHelperName("__spreadArrays"), 
73275         /*typeArguments*/ undefined, argumentList), location);
73276     }
73277     ts.createSpreadArraysHelper = createSpreadArraysHelper;
73278     // Utilities
73279     function createForOfBindingStatement(node, boundValue) {
73280         if (ts.isVariableDeclarationList(node)) {
73281             var firstDeclaration = ts.first(node.declarations);
73282             var updatedDeclaration = ts.updateVariableDeclaration(firstDeclaration, firstDeclaration.name, 
73283             /*typeNode*/ undefined, boundValue);
73284             return ts.setTextRange(ts.createVariableStatement(
73285             /*modifiers*/ undefined, ts.updateVariableDeclarationList(node, [updatedDeclaration])), 
73286             /*location*/ node);
73287         }
73288         else {
73289             var updatedExpression = ts.setTextRange(ts.createAssignment(node, boundValue), /*location*/ node);
73290             return ts.setTextRange(ts.createStatement(updatedExpression), /*location*/ node);
73291         }
73292     }
73293     ts.createForOfBindingStatement = createForOfBindingStatement;
73294     function insertLeadingStatement(dest, source) {
73295         if (ts.isBlock(dest)) {
73296             return ts.updateBlock(dest, ts.setTextRange(ts.createNodeArray(__spreadArrays([source], dest.statements)), dest.statements));
73297         }
73298         else {
73299             return ts.createBlock(ts.createNodeArray([dest, source]), /*multiLine*/ true);
73300         }
73301     }
73302     ts.insertLeadingStatement = insertLeadingStatement;
73303     function restoreEnclosingLabel(node, outermostLabeledStatement, afterRestoreLabelCallback) {
73304         if (!outermostLabeledStatement) {
73305             return node;
73306         }
73307         var updated = ts.updateLabel(outermostLabeledStatement, outermostLabeledStatement.label, outermostLabeledStatement.statement.kind === 238 /* LabeledStatement */
73308             ? restoreEnclosingLabel(node, outermostLabeledStatement.statement)
73309             : node);
73310         if (afterRestoreLabelCallback) {
73311             afterRestoreLabelCallback(outermostLabeledStatement);
73312         }
73313         return updated;
73314     }
73315     ts.restoreEnclosingLabel = restoreEnclosingLabel;
73316     function shouldBeCapturedInTempVariable(node, cacheIdentifiers) {
73317         var target = ts.skipParentheses(node);
73318         switch (target.kind) {
73319             case 75 /* Identifier */:
73320                 return cacheIdentifiers;
73321             case 104 /* ThisKeyword */:
73322             case 8 /* NumericLiteral */:
73323             case 9 /* BigIntLiteral */:
73324             case 10 /* StringLiteral */:
73325                 return false;
73326             case 192 /* ArrayLiteralExpression */:
73327                 var elements = target.elements;
73328                 if (elements.length === 0) {
73329                     return false;
73330                 }
73331                 return true;
73332             case 193 /* ObjectLiteralExpression */:
73333                 return target.properties.length > 0;
73334             default:
73335                 return true;
73336         }
73337     }
73338     function createCallBinding(expression, recordTempVariable, languageVersion, cacheIdentifiers) {
73339         if (cacheIdentifiers === void 0) { cacheIdentifiers = false; }
73340         var callee = skipOuterExpressions(expression, 15 /* All */);
73341         var thisArg;
73342         var target;
73343         if (ts.isSuperProperty(callee)) {
73344             thisArg = ts.createThis();
73345             target = callee;
73346         }
73347         else if (callee.kind === 102 /* SuperKeyword */) {
73348             thisArg = ts.createThis();
73349             target = languageVersion < 2 /* ES2015 */
73350                 ? ts.setTextRange(ts.createIdentifier("_super"), callee)
73351                 : callee;
73352         }
73353         else if (ts.getEmitFlags(callee) & 4096 /* HelperName */) {
73354             thisArg = ts.createVoidZero();
73355             target = parenthesizeForAccess(callee);
73356         }
73357         else {
73358             switch (callee.kind) {
73359                 case 194 /* PropertyAccessExpression */: {
73360                     if (shouldBeCapturedInTempVariable(callee.expression, cacheIdentifiers)) {
73361                         // for `a.b()` target is `(_a = a).b` and thisArg is `_a`
73362                         thisArg = ts.createTempVariable(recordTempVariable);
73363                         target = ts.createPropertyAccess(ts.setTextRange(ts.createAssignment(thisArg, callee.expression), callee.expression), callee.name);
73364                         ts.setTextRange(target, callee);
73365                     }
73366                     else {
73367                         thisArg = callee.expression;
73368                         target = callee;
73369                     }
73370                     break;
73371                 }
73372                 case 195 /* ElementAccessExpression */: {
73373                     if (shouldBeCapturedInTempVariable(callee.expression, cacheIdentifiers)) {
73374                         // for `a[b]()` target is `(_a = a)[b]` and thisArg is `_a`
73375                         thisArg = ts.createTempVariable(recordTempVariable);
73376                         target = ts.createElementAccess(ts.setTextRange(ts.createAssignment(thisArg, callee.expression), callee.expression), callee.argumentExpression);
73377                         ts.setTextRange(target, callee);
73378                     }
73379                     else {
73380                         thisArg = callee.expression;
73381                         target = callee;
73382                     }
73383                     break;
73384                 }
73385                 default: {
73386                     // for `a()` target is `a` and thisArg is `void 0`
73387                     thisArg = ts.createVoidZero();
73388                     target = parenthesizeForAccess(expression);
73389                     break;
73390                 }
73391             }
73392         }
73393         return { target: target, thisArg: thisArg };
73394     }
73395     ts.createCallBinding = createCallBinding;
73396     function inlineExpressions(expressions) {
73397         // Avoid deeply nested comma expressions as traversing them during emit can result in "Maximum call
73398         // stack size exceeded" errors.
73399         return expressions.length > 10
73400             ? ts.createCommaList(expressions)
73401             : ts.reduceLeft(expressions, ts.createComma);
73402     }
73403     ts.inlineExpressions = inlineExpressions;
73404     function createExpressionFromEntityName(node) {
73405         if (ts.isQualifiedName(node)) {
73406             var left = createExpressionFromEntityName(node.left);
73407             var right = ts.getMutableClone(node.right);
73408             return ts.setTextRange(ts.createPropertyAccess(left, right), node);
73409         }
73410         else {
73411             return ts.getMutableClone(node);
73412         }
73413     }
73414     ts.createExpressionFromEntityName = createExpressionFromEntityName;
73415     function createExpressionForPropertyName(memberName) {
73416         if (ts.isIdentifier(memberName)) {
73417             return ts.createLiteral(memberName);
73418         }
73419         else if (ts.isComputedPropertyName(memberName)) {
73420             return ts.getMutableClone(memberName.expression);
73421         }
73422         else {
73423             return ts.getMutableClone(memberName);
73424         }
73425     }
73426     ts.createExpressionForPropertyName = createExpressionForPropertyName;
73427     function createExpressionForObjectLiteralElementLike(node, property, receiver) {
73428         if (property.name && ts.isPrivateIdentifier(property.name)) {
73429             ts.Debug.failBadSyntaxKind(property.name, "Private identifiers are not allowed in object literals.");
73430         }
73431         switch (property.kind) {
73432             case 163 /* GetAccessor */:
73433             case 164 /* SetAccessor */:
73434                 return createExpressionForAccessorDeclaration(node.properties, property, receiver, !!node.multiLine);
73435             case 281 /* PropertyAssignment */:
73436                 return createExpressionForPropertyAssignment(property, receiver);
73437             case 282 /* ShorthandPropertyAssignment */:
73438                 return createExpressionForShorthandPropertyAssignment(property, receiver);
73439             case 161 /* MethodDeclaration */:
73440                 return createExpressionForMethodDeclaration(property, receiver);
73441         }
73442     }
73443     ts.createExpressionForObjectLiteralElementLike = createExpressionForObjectLiteralElementLike;
73444     function createExpressionForAccessorDeclaration(properties, property, receiver, multiLine) {
73445         var _a = ts.getAllAccessorDeclarations(properties, property), firstAccessor = _a.firstAccessor, getAccessor = _a.getAccessor, setAccessor = _a.setAccessor;
73446         if (property === firstAccessor) {
73447             var properties_7 = [];
73448             if (getAccessor) {
73449                 var getterFunction = ts.createFunctionExpression(getAccessor.modifiers, 
73450                 /*asteriskToken*/ undefined, 
73451                 /*name*/ undefined, 
73452                 /*typeParameters*/ undefined, getAccessor.parameters, 
73453                 /*type*/ undefined, getAccessor.body // TODO: GH#18217
73454                 );
73455                 ts.setTextRange(getterFunction, getAccessor);
73456                 ts.setOriginalNode(getterFunction, getAccessor);
73457                 var getter = ts.createPropertyAssignment("get", getterFunction);
73458                 properties_7.push(getter);
73459             }
73460             if (setAccessor) {
73461                 var setterFunction = ts.createFunctionExpression(setAccessor.modifiers, 
73462                 /*asteriskToken*/ undefined, 
73463                 /*name*/ undefined, 
73464                 /*typeParameters*/ undefined, setAccessor.parameters, 
73465                 /*type*/ undefined, setAccessor.body // TODO: GH#18217
73466                 );
73467                 ts.setTextRange(setterFunction, setAccessor);
73468                 ts.setOriginalNode(setterFunction, setAccessor);
73469                 var setter = ts.createPropertyAssignment("set", setterFunction);
73470                 properties_7.push(setter);
73471             }
73472             properties_7.push(ts.createPropertyAssignment("enumerable", getAccessor || setAccessor ? ts.createFalse() : ts.createTrue()));
73473             properties_7.push(ts.createPropertyAssignment("configurable", ts.createTrue()));
73474             var expression = ts.setTextRange(ts.createCall(ts.createPropertyAccess(ts.createIdentifier("Object"), "defineProperty"), 
73475             /*typeArguments*/ undefined, [
73476                 receiver,
73477                 createExpressionForPropertyName(property.name),
73478                 ts.createObjectLiteral(properties_7, multiLine)
73479             ]), 
73480             /*location*/ firstAccessor);
73481             return ts.aggregateTransformFlags(expression);
73482         }
73483         return undefined;
73484     }
73485     function createExpressionForPropertyAssignment(property, receiver) {
73486         return ts.aggregateTransformFlags(ts.setOriginalNode(ts.setTextRange(ts.createAssignment(createMemberAccessForPropertyName(receiver, property.name, /*location*/ property.name), property.initializer), property), property));
73487     }
73488     function createExpressionForShorthandPropertyAssignment(property, receiver) {
73489         return ts.aggregateTransformFlags(ts.setOriginalNode(ts.setTextRange(ts.createAssignment(createMemberAccessForPropertyName(receiver, property.name, /*location*/ property.name), ts.getSynthesizedClone(property.name)), 
73490         /*location*/ property), 
73491         /*original*/ property));
73492     }
73493     function createExpressionForMethodDeclaration(method, receiver) {
73494         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, 
73495         /*name*/ undefined, 
73496         /*typeParameters*/ undefined, method.parameters, 
73497         /*type*/ undefined, method.body // TODO: GH#18217
73498         ), 
73499         /*location*/ method), 
73500         /*original*/ method)), 
73501         /*location*/ method), 
73502         /*original*/ method));
73503     }
73504     /**
73505      * Gets the internal name of a declaration. This is primarily used for declarations that can be
73506      * referred to by name in the body of an ES5 class function body. An internal name will *never*
73507      * be prefixed with an module or namespace export modifier like "exports." when emitted as an
73508      * expression. An internal name will also *never* be renamed due to a collision with a block
73509      * scoped variable.
73510      *
73511      * @param node The declaration.
73512      * @param allowComments A value indicating whether comments may be emitted for the name.
73513      * @param allowSourceMaps A value indicating whether source maps may be emitted for the name.
73514      */
73515     function getInternalName(node, allowComments, allowSourceMaps) {
73516         return getName(node, allowComments, allowSourceMaps, 16384 /* LocalName */ | 32768 /* InternalName */);
73517     }
73518     ts.getInternalName = getInternalName;
73519     /**
73520      * Gets whether an identifier should only be referred to by its internal name.
73521      */
73522     function isInternalName(node) {
73523         return (ts.getEmitFlags(node) & 32768 /* InternalName */) !== 0;
73524     }
73525     ts.isInternalName = isInternalName;
73526     /**
73527      * Gets the local name of a declaration. This is primarily used for declarations that can be
73528      * referred to by name in the declaration's immediate scope (classes, enums, namespaces). A
73529      * local name will *never* be prefixed with an module or namespace export modifier like
73530      * "exports." when emitted as an expression.
73531      *
73532      * @param node The declaration.
73533      * @param allowComments A value indicating whether comments may be emitted for the name.
73534      * @param allowSourceMaps A value indicating whether source maps may be emitted for the name.
73535      */
73536     function getLocalName(node, allowComments, allowSourceMaps) {
73537         return getName(node, allowComments, allowSourceMaps, 16384 /* LocalName */);
73538     }
73539     ts.getLocalName = getLocalName;
73540     /**
73541      * Gets whether an identifier should only be referred to by its local name.
73542      */
73543     function isLocalName(node) {
73544         return (ts.getEmitFlags(node) & 16384 /* LocalName */) !== 0;
73545     }
73546     ts.isLocalName = isLocalName;
73547     /**
73548      * Gets the export name of a declaration. This is primarily used for declarations that can be
73549      * referred to by name in the declaration's immediate scope (classes, enums, namespaces). An
73550      * export name will *always* be prefixed with an module or namespace export modifier like
73551      * `"exports."` when emitted as an expression if the name points to an exported symbol.
73552      *
73553      * @param node The declaration.
73554      * @param allowComments A value indicating whether comments may be emitted for the name.
73555      * @param allowSourceMaps A value indicating whether source maps may be emitted for the name.
73556      */
73557     function getExportName(node, allowComments, allowSourceMaps) {
73558         return getName(node, allowComments, allowSourceMaps, 8192 /* ExportName */);
73559     }
73560     ts.getExportName = getExportName;
73561     /**
73562      * Gets whether an identifier should only be referred to by its export representation if the
73563      * name points to an exported symbol.
73564      */
73565     function isExportName(node) {
73566         return (ts.getEmitFlags(node) & 8192 /* ExportName */) !== 0;
73567     }
73568     ts.isExportName = isExportName;
73569     /**
73570      * Gets the name of a declaration for use in declarations.
73571      *
73572      * @param node The declaration.
73573      * @param allowComments A value indicating whether comments may be emitted for the name.
73574      * @param allowSourceMaps A value indicating whether source maps may be emitted for the name.
73575      */
73576     function getDeclarationName(node, allowComments, allowSourceMaps) {
73577         return getName(node, allowComments, allowSourceMaps);
73578     }
73579     ts.getDeclarationName = getDeclarationName;
73580     function getName(node, allowComments, allowSourceMaps, emitFlags) {
73581         if (emitFlags === void 0) { emitFlags = 0; }
73582         var nodeName = ts.getNameOfDeclaration(node);
73583         if (nodeName && ts.isIdentifier(nodeName) && !ts.isGeneratedIdentifier(nodeName)) {
73584             var name = ts.getMutableClone(nodeName);
73585             emitFlags |= ts.getEmitFlags(nodeName);
73586             if (!allowSourceMaps)
73587                 emitFlags |= 48 /* NoSourceMap */;
73588             if (!allowComments)
73589                 emitFlags |= 1536 /* NoComments */;
73590             if (emitFlags)
73591                 ts.setEmitFlags(name, emitFlags);
73592             return name;
73593         }
73594         return ts.getGeneratedNameForNode(node);
73595     }
73596     /**
73597      * Gets the exported name of a declaration for use in expressions.
73598      *
73599      * An exported name will *always* be prefixed with an module or namespace export modifier like
73600      * "exports." if the name points to an exported symbol.
73601      *
73602      * @param ns The namespace identifier.
73603      * @param node The declaration.
73604      * @param allowComments A value indicating whether comments may be emitted for the name.
73605      * @param allowSourceMaps A value indicating whether source maps may be emitted for the name.
73606      */
73607     function getExternalModuleOrNamespaceExportName(ns, node, allowComments, allowSourceMaps) {
73608         if (ns && ts.hasModifier(node, 1 /* Export */)) {
73609             return getNamespaceMemberName(ns, getName(node), allowComments, allowSourceMaps);
73610         }
73611         return getExportName(node, allowComments, allowSourceMaps);
73612     }
73613     ts.getExternalModuleOrNamespaceExportName = getExternalModuleOrNamespaceExportName;
73614     /**
73615      * Gets a namespace-qualified name for use in expressions.
73616      *
73617      * @param ns The namespace identifier.
73618      * @param name The name.
73619      * @param allowComments A value indicating whether comments may be emitted for the name.
73620      * @param allowSourceMaps A value indicating whether source maps may be emitted for the name.
73621      */
73622     function getNamespaceMemberName(ns, name, allowComments, allowSourceMaps) {
73623         var qualifiedName = ts.createPropertyAccess(ns, ts.nodeIsSynthesized(name) ? name : ts.getSynthesizedClone(name));
73624         ts.setTextRange(qualifiedName, name);
73625         var emitFlags = 0;
73626         if (!allowSourceMaps)
73627             emitFlags |= 48 /* NoSourceMap */;
73628         if (!allowComments)
73629             emitFlags |= 1536 /* NoComments */;
73630         if (emitFlags)
73631             ts.setEmitFlags(qualifiedName, emitFlags);
73632         return qualifiedName;
73633     }
73634     ts.getNamespaceMemberName = getNamespaceMemberName;
73635     function convertToFunctionBody(node, multiLine) {
73636         return ts.isBlock(node) ? node : ts.setTextRange(ts.createBlock([ts.setTextRange(ts.createReturn(node), node)], multiLine), node);
73637     }
73638     ts.convertToFunctionBody = convertToFunctionBody;
73639     function convertFunctionDeclarationToExpression(node) {
73640         if (!node.body)
73641             return ts.Debug.fail();
73642         var updated = ts.createFunctionExpression(node.modifiers, node.asteriskToken, node.name, node.typeParameters, node.parameters, node.type, node.body);
73643         ts.setOriginalNode(updated, node);
73644         ts.setTextRange(updated, node);
73645         if (ts.getStartsOnNewLine(node)) {
73646             ts.setStartsOnNewLine(updated, /*newLine*/ true);
73647         }
73648         ts.aggregateTransformFlags(updated);
73649         return updated;
73650     }
73651     ts.convertFunctionDeclarationToExpression = convertFunctionDeclarationToExpression;
73652     function isUseStrictPrologue(node) {
73653         return ts.isStringLiteral(node.expression) && node.expression.text === "use strict";
73654     }
73655     /**
73656      * Add any necessary prologue-directives into target statement-array.
73657      * The function needs to be called during each transformation step.
73658      * This function needs to be called whenever we transform the statement
73659      * list of a source file, namespace, or function-like body.
73660      *
73661      * @param target: result statements array
73662      * @param source: origin statements array
73663      * @param ensureUseStrict: boolean determining whether the function need to add prologue-directives
73664      * @param visitor: Optional callback used to visit any custom prologue directives.
73665      */
73666     function addPrologue(target, source, ensureUseStrict, visitor) {
73667         var offset = addStandardPrologue(target, source, ensureUseStrict);
73668         return addCustomPrologue(target, source, offset, visitor);
73669     }
73670     ts.addPrologue = addPrologue;
73671     /**
73672      * Add just the standard (string-expression) prologue-directives into target statement-array.
73673      * The function needs to be called during each transformation step.
73674      * This function needs to be called whenever we transform the statement
73675      * list of a source file, namespace, or function-like body.
73676      */
73677     function addStandardPrologue(target, source, ensureUseStrict) {
73678         ts.Debug.assert(target.length === 0, "Prologue directives should be at the first statement in the target statements array");
73679         var foundUseStrict = false;
73680         var statementOffset = 0;
73681         var numStatements = source.length;
73682         while (statementOffset < numStatements) {
73683             var statement = source[statementOffset];
73684             if (ts.isPrologueDirective(statement)) {
73685                 if (isUseStrictPrologue(statement)) {
73686                     foundUseStrict = true;
73687                 }
73688                 target.push(statement);
73689             }
73690             else {
73691                 break;
73692             }
73693             statementOffset++;
73694         }
73695         if (ensureUseStrict && !foundUseStrict) {
73696             target.push(startOnNewLine(ts.createStatement(ts.createLiteral("use strict"))));
73697         }
73698         return statementOffset;
73699     }
73700     ts.addStandardPrologue = addStandardPrologue;
73701     function addCustomPrologue(target, source, statementOffset, visitor, filter) {
73702         if (filter === void 0) { filter = ts.returnTrue; }
73703         var numStatements = source.length;
73704         while (statementOffset !== undefined && statementOffset < numStatements) {
73705             var statement = source[statementOffset];
73706             if (ts.getEmitFlags(statement) & 1048576 /* CustomPrologue */ && filter(statement)) {
73707                 ts.append(target, visitor ? ts.visitNode(statement, visitor, ts.isStatement) : statement);
73708             }
73709             else {
73710                 break;
73711             }
73712             statementOffset++;
73713         }
73714         return statementOffset;
73715     }
73716     ts.addCustomPrologue = addCustomPrologue;
73717     function findUseStrictPrologue(statements) {
73718         for (var _i = 0, statements_4 = statements; _i < statements_4.length; _i++) {
73719             var statement = statements_4[_i];
73720             if (ts.isPrologueDirective(statement)) {
73721                 if (isUseStrictPrologue(statement)) {
73722                     return statement;
73723                 }
73724             }
73725             else {
73726                 break;
73727             }
73728         }
73729         return undefined;
73730     }
73731     ts.findUseStrictPrologue = findUseStrictPrologue;
73732     function startsWithUseStrict(statements) {
73733         var firstStatement = ts.firstOrUndefined(statements);
73734         return firstStatement !== undefined
73735             && ts.isPrologueDirective(firstStatement)
73736             && isUseStrictPrologue(firstStatement);
73737     }
73738     ts.startsWithUseStrict = startsWithUseStrict;
73739     /**
73740      * Ensures "use strict" directive is added
73741      *
73742      * @param statements An array of statements
73743      */
73744     function ensureUseStrict(statements) {
73745         var foundUseStrict = findUseStrictPrologue(statements);
73746         if (!foundUseStrict) {
73747             return ts.setTextRange(ts.createNodeArray(__spreadArrays([
73748                 startOnNewLine(ts.createStatement(ts.createLiteral("use strict")))
73749             ], statements)), statements);
73750         }
73751         return statements;
73752     }
73753     ts.ensureUseStrict = ensureUseStrict;
73754     /**
73755      * Wraps the operand to a BinaryExpression in parentheses if they are needed to preserve the intended
73756      * order of operations.
73757      *
73758      * @param binaryOperator The operator for the BinaryExpression.
73759      * @param operand The operand for the BinaryExpression.
73760      * @param isLeftSideOfBinary A value indicating whether the operand is the left side of the
73761      *                           BinaryExpression.
73762      */
73763     function parenthesizeBinaryOperand(binaryOperator, operand, isLeftSideOfBinary, leftOperand) {
73764         var skipped = ts.skipPartiallyEmittedExpressions(operand);
73765         // If the resulting expression is already parenthesized, we do not need to do any further processing.
73766         if (skipped.kind === 200 /* ParenthesizedExpression */) {
73767             return operand;
73768         }
73769         return binaryOperandNeedsParentheses(binaryOperator, operand, isLeftSideOfBinary, leftOperand)
73770             ? ts.createParen(operand)
73771             : operand;
73772     }
73773     ts.parenthesizeBinaryOperand = parenthesizeBinaryOperand;
73774     /**
73775      * Determines whether the operand to a BinaryExpression needs to be parenthesized.
73776      *
73777      * @param binaryOperator The operator for the BinaryExpression.
73778      * @param operand The operand for the BinaryExpression.
73779      * @param isLeftSideOfBinary A value indicating whether the operand is the left side of the
73780      *                           BinaryExpression.
73781      */
73782     function binaryOperandNeedsParentheses(binaryOperator, operand, isLeftSideOfBinary, leftOperand) {
73783         // If the operand has lower precedence, then it needs to be parenthesized to preserve the
73784         // intent of the expression. For example, if the operand is `a + b` and the operator is
73785         // `*`, then we need to parenthesize the operand to preserve the intended order of
73786         // operations: `(a + b) * x`.
73787         //
73788         // If the operand has higher precedence, then it does not need to be parenthesized. For
73789         // example, if the operand is `a * b` and the operator is `+`, then we do not need to
73790         // parenthesize to preserve the intended order of operations: `a * b + x`.
73791         //
73792         // If the operand has the same precedence, then we need to check the associativity of
73793         // the operator based on whether this is the left or right operand of the expression.
73794         //
73795         // For example, if `a / d` is on the right of operator `*`, we need to parenthesize
73796         // to preserve the intended order of operations: `x * (a / d)`
73797         //
73798         // If `a ** d` is on the left of operator `**`, we need to parenthesize to preserve
73799         // the intended order of operations: `(a ** b) ** c`
73800         var binaryOperatorPrecedence = ts.getOperatorPrecedence(209 /* BinaryExpression */, binaryOperator);
73801         var binaryOperatorAssociativity = ts.getOperatorAssociativity(209 /* BinaryExpression */, binaryOperator);
73802         var emittedOperand = ts.skipPartiallyEmittedExpressions(operand);
73803         if (!isLeftSideOfBinary && operand.kind === 202 /* ArrowFunction */ && binaryOperatorPrecedence > 3) {
73804             // We need to parenthesize arrow functions on the right side to avoid it being
73805             // parsed as parenthesized expression: `a && (() => {})`
73806             return true;
73807         }
73808         var operandPrecedence = ts.getExpressionPrecedence(emittedOperand);
73809         switch (ts.compareValues(operandPrecedence, binaryOperatorPrecedence)) {
73810             case -1 /* LessThan */:
73811                 // If the operand is the right side of a right-associative binary operation
73812                 // and is a yield expression, then we do not need parentheses.
73813                 if (!isLeftSideOfBinary
73814                     && binaryOperatorAssociativity === 1 /* Right */
73815                     && operand.kind === 212 /* YieldExpression */) {
73816                     return false;
73817                 }
73818                 return true;
73819             case 1 /* GreaterThan */:
73820                 return false;
73821             case 0 /* EqualTo */:
73822                 if (isLeftSideOfBinary) {
73823                     // No need to parenthesize the left operand when the binary operator is
73824                     // left associative:
73825                     //  (a*b)/x    -> a*b/x
73826                     //  (a**b)/x   -> a**b/x
73827                     //
73828                     // Parentheses are needed for the left operand when the binary operator is
73829                     // right associative:
73830                     //  (a/b)**x   -> (a/b)**x
73831                     //  (a**b)**x  -> (a**b)**x
73832                     return binaryOperatorAssociativity === 1 /* Right */;
73833                 }
73834                 else {
73835                     if (ts.isBinaryExpression(emittedOperand)
73836                         && emittedOperand.operatorToken.kind === binaryOperator) {
73837                         // No need to parenthesize the right operand when the binary operator and
73838                         // operand are the same and one of the following:
73839                         //  x*(a*b)     => x*a*b
73840                         //  x|(a|b)     => x|a|b
73841                         //  x&(a&b)     => x&a&b
73842                         //  x^(a^b)     => x^a^b
73843                         if (operatorHasAssociativeProperty(binaryOperator)) {
73844                             return false;
73845                         }
73846                         // No need to parenthesize the right operand when the binary operator
73847                         // is plus (+) if both the left and right operands consist solely of either
73848                         // literals of the same kind or binary plus (+) expressions for literals of
73849                         // the same kind (recursively).
73850                         //  "a"+(1+2)       => "a"+(1+2)
73851                         //  "a"+("b"+"c")   => "a"+"b"+"c"
73852                         if (binaryOperator === 39 /* PlusToken */) {
73853                             var leftKind = leftOperand ? getLiteralKindOfBinaryPlusOperand(leftOperand) : 0 /* Unknown */;
73854                             if (ts.isLiteralKind(leftKind) && leftKind === getLiteralKindOfBinaryPlusOperand(emittedOperand)) {
73855                                 return false;
73856                             }
73857                         }
73858                     }
73859                     // No need to parenthesize the right operand when the operand is right
73860                     // associative:
73861                     //  x/(a**b)    -> x/a**b
73862                     //  x**(a**b)   -> x**a**b
73863                     //
73864                     // Parentheses are needed for the right operand when the operand is left
73865                     // associative:
73866                     //  x/(a*b)     -> x/(a*b)
73867                     //  x**(a/b)    -> x**(a/b)
73868                     var operandAssociativity = ts.getExpressionAssociativity(emittedOperand);
73869                     return operandAssociativity === 0 /* Left */;
73870                 }
73871         }
73872     }
73873     /**
73874      * Determines whether a binary operator is mathematically associative.
73875      *
73876      * @param binaryOperator The binary operator.
73877      */
73878     function operatorHasAssociativeProperty(binaryOperator) {
73879         // The following operators are associative in JavaScript:
73880         //  (a*b)*c     -> a*(b*c)  -> a*b*c
73881         //  (a|b)|c     -> a|(b|c)  -> a|b|c
73882         //  (a&b)&c     -> a&(b&c)  -> a&b&c
73883         //  (a^b)^c     -> a^(b^c)  -> a^b^c
73884         //
73885         // While addition is associative in mathematics, JavaScript's `+` is not
73886         // guaranteed to be associative as it is overloaded with string concatenation.
73887         return binaryOperator === 41 /* AsteriskToken */
73888             || binaryOperator === 51 /* BarToken */
73889             || binaryOperator === 50 /* AmpersandToken */
73890             || binaryOperator === 52 /* CaretToken */;
73891     }
73892     /**
73893      * This function determines whether an expression consists of a homogeneous set of
73894      * literal expressions or binary plus expressions that all share the same literal kind.
73895      * It is used to determine whether the right-hand operand of a binary plus expression can be
73896      * emitted without parentheses.
73897      */
73898     function getLiteralKindOfBinaryPlusOperand(node) {
73899         node = ts.skipPartiallyEmittedExpressions(node);
73900         if (ts.isLiteralKind(node.kind)) {
73901             return node.kind;
73902         }
73903         if (node.kind === 209 /* BinaryExpression */ && node.operatorToken.kind === 39 /* PlusToken */) {
73904             if (node.cachedLiteralKind !== undefined) {
73905                 return node.cachedLiteralKind;
73906             }
73907             var leftKind = getLiteralKindOfBinaryPlusOperand(node.left);
73908             var literalKind = ts.isLiteralKind(leftKind) && leftKind === getLiteralKindOfBinaryPlusOperand(node.right) ? leftKind :
73909                 0 /* Unknown */;
73910             node.cachedLiteralKind = literalKind;
73911             return literalKind;
73912         }
73913         return 0 /* Unknown */;
73914     }
73915     function parenthesizeForConditionalHead(condition) {
73916         var conditionalPrecedence = ts.getOperatorPrecedence(210 /* ConditionalExpression */, 57 /* QuestionToken */);
73917         var emittedCondition = ts.skipPartiallyEmittedExpressions(condition);
73918         var conditionPrecedence = ts.getExpressionPrecedence(emittedCondition);
73919         if (ts.compareValues(conditionPrecedence, conditionalPrecedence) !== 1 /* GreaterThan */) {
73920             return ts.createParen(condition);
73921         }
73922         return condition;
73923     }
73924     ts.parenthesizeForConditionalHead = parenthesizeForConditionalHead;
73925     function parenthesizeSubexpressionOfConditionalExpression(e) {
73926         // per ES grammar both 'whenTrue' and 'whenFalse' parts of conditional expression are assignment expressions
73927         // so in case when comma expression is introduced as a part of previous transformations
73928         // if should be wrapped in parens since comma operator has the lowest precedence
73929         var emittedExpression = ts.skipPartiallyEmittedExpressions(e);
73930         return isCommaSequence(emittedExpression)
73931             ? ts.createParen(e)
73932             : e;
73933     }
73934     ts.parenthesizeSubexpressionOfConditionalExpression = parenthesizeSubexpressionOfConditionalExpression;
73935     /**
73936      *  [Per the spec](https://tc39.github.io/ecma262/#prod-ExportDeclaration), `export default` accepts _AssigmentExpression_ but
73937      *  has a lookahead restriction for `function`, `async function`, and `class`.
73938      *
73939      * Basically, that means we need to parenthesize in the following cases:
73940      *
73941      * - BinaryExpression of CommaToken
73942      * - CommaList (synthetic list of multiple comma expressions)
73943      * - FunctionExpression
73944      * - ClassExpression
73945      */
73946     function parenthesizeDefaultExpression(e) {
73947         var check = ts.skipPartiallyEmittedExpressions(e);
73948         var needsParens = isCommaSequence(check);
73949         if (!needsParens) {
73950             switch (getLeftmostExpression(check, /*stopAtCallExpression*/ false).kind) {
73951                 case 214 /* ClassExpression */:
73952                 case 201 /* FunctionExpression */:
73953                     needsParens = true;
73954             }
73955         }
73956         return needsParens ? ts.createParen(e) : e;
73957     }
73958     ts.parenthesizeDefaultExpression = parenthesizeDefaultExpression;
73959     /**
73960      * Wraps an expression in parentheses if it is needed in order to use the expression
73961      * as the expression of a NewExpression node.
73962      *
73963      * @param expression The Expression node.
73964      */
73965     function parenthesizeForNew(expression) {
73966         var leftmostExpr = getLeftmostExpression(expression, /*stopAtCallExpressions*/ true);
73967         switch (leftmostExpr.kind) {
73968             case 196 /* CallExpression */:
73969                 return ts.createParen(expression);
73970             case 197 /* NewExpression */:
73971                 return !leftmostExpr.arguments
73972                     ? ts.createParen(expression)
73973                     : expression;
73974         }
73975         return parenthesizeForAccess(expression);
73976     }
73977     ts.parenthesizeForNew = parenthesizeForNew;
73978     /**
73979      * Wraps an expression in parentheses if it is needed in order to use the expression for
73980      * property or element access.
73981      *
73982      * @param expr The expression node.
73983      */
73984     function parenthesizeForAccess(expression) {
73985         // isLeftHandSideExpression is almost the correct criterion for when it is not necessary
73986         // to parenthesize the expression before a dot. The known exception is:
73987         //
73988         //    NewExpression:
73989         //       new C.x        -> not the same as (new C).x
73990         //
73991         var emittedExpression = ts.skipPartiallyEmittedExpressions(expression);
73992         if (ts.isLeftHandSideExpression(emittedExpression)
73993             && (emittedExpression.kind !== 197 /* NewExpression */ || emittedExpression.arguments)) {
73994             return expression;
73995         }
73996         return ts.setTextRange(ts.createParen(expression), expression);
73997     }
73998     ts.parenthesizeForAccess = parenthesizeForAccess;
73999     function parenthesizePostfixOperand(operand) {
74000         return ts.isLeftHandSideExpression(operand)
74001             ? operand
74002             : ts.setTextRange(ts.createParen(operand), operand);
74003     }
74004     ts.parenthesizePostfixOperand = parenthesizePostfixOperand;
74005     function parenthesizePrefixOperand(operand) {
74006         return ts.isUnaryExpression(operand)
74007             ? operand
74008             : ts.setTextRange(ts.createParen(operand), operand);
74009     }
74010     ts.parenthesizePrefixOperand = parenthesizePrefixOperand;
74011     function parenthesizeListElements(elements) {
74012         var result;
74013         for (var i = 0; i < elements.length; i++) {
74014             var element = parenthesizeExpressionForList(elements[i]);
74015             if (result !== undefined || element !== elements[i]) {
74016                 if (result === undefined) {
74017                     result = elements.slice(0, i);
74018                 }
74019                 result.push(element);
74020             }
74021         }
74022         if (result !== undefined) {
74023             return ts.setTextRange(ts.createNodeArray(result, elements.hasTrailingComma), elements);
74024         }
74025         return elements;
74026     }
74027     ts.parenthesizeListElements = parenthesizeListElements;
74028     function parenthesizeExpressionForList(expression) {
74029         var emittedExpression = ts.skipPartiallyEmittedExpressions(expression);
74030         var expressionPrecedence = ts.getExpressionPrecedence(emittedExpression);
74031         var commaPrecedence = ts.getOperatorPrecedence(209 /* BinaryExpression */, 27 /* CommaToken */);
74032         return expressionPrecedence > commaPrecedence
74033             ? expression
74034             : ts.setTextRange(ts.createParen(expression), expression);
74035     }
74036     ts.parenthesizeExpressionForList = parenthesizeExpressionForList;
74037     function parenthesizeExpressionForExpressionStatement(expression) {
74038         var emittedExpression = ts.skipPartiallyEmittedExpressions(expression);
74039         if (ts.isCallExpression(emittedExpression)) {
74040             var callee = emittedExpression.expression;
74041             var kind = ts.skipPartiallyEmittedExpressions(callee).kind;
74042             if (kind === 201 /* FunctionExpression */ || kind === 202 /* ArrowFunction */) {
74043                 var mutableCall = ts.getMutableClone(emittedExpression);
74044                 mutableCall.expression = ts.setTextRange(ts.createParen(callee), callee);
74045                 return recreateOuterExpressions(expression, mutableCall, 8 /* PartiallyEmittedExpressions */);
74046             }
74047         }
74048         var leftmostExpressionKind = getLeftmostExpression(emittedExpression, /*stopAtCallExpressions*/ false).kind;
74049         if (leftmostExpressionKind === 193 /* ObjectLiteralExpression */ || leftmostExpressionKind === 201 /* FunctionExpression */) {
74050             return ts.setTextRange(ts.createParen(expression), expression);
74051         }
74052         return expression;
74053     }
74054     ts.parenthesizeExpressionForExpressionStatement = parenthesizeExpressionForExpressionStatement;
74055     function parenthesizeConditionalTypeMember(member) {
74056         return member.kind === 180 /* ConditionalType */ ? ts.createParenthesizedType(member) : member;
74057     }
74058     ts.parenthesizeConditionalTypeMember = parenthesizeConditionalTypeMember;
74059     function parenthesizeElementTypeMember(member) {
74060         switch (member.kind) {
74061             case 178 /* UnionType */:
74062             case 179 /* IntersectionType */:
74063             case 170 /* FunctionType */:
74064             case 171 /* ConstructorType */:
74065                 return ts.createParenthesizedType(member);
74066         }
74067         return parenthesizeConditionalTypeMember(member);
74068     }
74069     ts.parenthesizeElementTypeMember = parenthesizeElementTypeMember;
74070     function parenthesizeArrayTypeMember(member) {
74071         switch (member.kind) {
74072             case 172 /* TypeQuery */:
74073             case 184 /* TypeOperator */:
74074             case 181 /* InferType */:
74075                 return ts.createParenthesizedType(member);
74076         }
74077         return parenthesizeElementTypeMember(member);
74078     }
74079     ts.parenthesizeArrayTypeMember = parenthesizeArrayTypeMember;
74080     function parenthesizeElementTypeMembers(members) {
74081         return ts.createNodeArray(ts.sameMap(members, parenthesizeElementTypeMember));
74082     }
74083     ts.parenthesizeElementTypeMembers = parenthesizeElementTypeMembers;
74084     function parenthesizeTypeParameters(typeParameters) {
74085         if (ts.some(typeParameters)) {
74086             var params = [];
74087             for (var i = 0; i < typeParameters.length; ++i) {
74088                 var entry = typeParameters[i];
74089                 params.push(i === 0 && ts.isFunctionOrConstructorTypeNode(entry) && entry.typeParameters ?
74090                     ts.createParenthesizedType(entry) :
74091                     entry);
74092             }
74093             return ts.createNodeArray(params);
74094         }
74095     }
74096     ts.parenthesizeTypeParameters = parenthesizeTypeParameters;
74097     function getLeftmostExpression(node, stopAtCallExpressions) {
74098         while (true) {
74099             switch (node.kind) {
74100                 case 208 /* PostfixUnaryExpression */:
74101                     node = node.operand;
74102                     continue;
74103                 case 209 /* BinaryExpression */:
74104                     node = node.left;
74105                     continue;
74106                 case 210 /* ConditionalExpression */:
74107                     node = node.condition;
74108                     continue;
74109                 case 198 /* TaggedTemplateExpression */:
74110                     node = node.tag;
74111                     continue;
74112                 case 196 /* CallExpression */:
74113                     if (stopAtCallExpressions) {
74114                         return node;
74115                     }
74116                 // falls through
74117                 case 217 /* AsExpression */:
74118                 case 195 /* ElementAccessExpression */:
74119                 case 194 /* PropertyAccessExpression */:
74120                 case 218 /* NonNullExpression */:
74121                 case 326 /* PartiallyEmittedExpression */:
74122                     node = node.expression;
74123                     continue;
74124             }
74125             return node;
74126         }
74127     }
74128     ts.getLeftmostExpression = getLeftmostExpression;
74129     function parenthesizeConciseBody(body) {
74130         if (!ts.isBlock(body) && (isCommaSequence(body) || getLeftmostExpression(body, /*stopAtCallExpressions*/ false).kind === 193 /* ObjectLiteralExpression */)) {
74131             return ts.setTextRange(ts.createParen(body), body);
74132         }
74133         return body;
74134     }
74135     ts.parenthesizeConciseBody = parenthesizeConciseBody;
74136     function isCommaSequence(node) {
74137         return node.kind === 209 /* BinaryExpression */ && node.operatorToken.kind === 27 /* CommaToken */ ||
74138             node.kind === 327 /* CommaListExpression */;
74139     }
74140     ts.isCommaSequence = isCommaSequence;
74141     var OuterExpressionKinds;
74142     (function (OuterExpressionKinds) {
74143         OuterExpressionKinds[OuterExpressionKinds["Parentheses"] = 1] = "Parentheses";
74144         OuterExpressionKinds[OuterExpressionKinds["TypeAssertions"] = 2] = "TypeAssertions";
74145         OuterExpressionKinds[OuterExpressionKinds["NonNullAssertions"] = 4] = "NonNullAssertions";
74146         OuterExpressionKinds[OuterExpressionKinds["PartiallyEmittedExpressions"] = 8] = "PartiallyEmittedExpressions";
74147         OuterExpressionKinds[OuterExpressionKinds["Assertions"] = 6] = "Assertions";
74148         OuterExpressionKinds[OuterExpressionKinds["All"] = 15] = "All";
74149     })(OuterExpressionKinds = ts.OuterExpressionKinds || (ts.OuterExpressionKinds = {}));
74150     function isOuterExpression(node, kinds) {
74151         if (kinds === void 0) { kinds = 15 /* All */; }
74152         switch (node.kind) {
74153             case 200 /* ParenthesizedExpression */:
74154                 return (kinds & 1 /* Parentheses */) !== 0;
74155             case 199 /* TypeAssertionExpression */:
74156             case 217 /* AsExpression */:
74157                 return (kinds & 2 /* TypeAssertions */) !== 0;
74158             case 218 /* NonNullExpression */:
74159                 return (kinds & 4 /* NonNullAssertions */) !== 0;
74160             case 326 /* PartiallyEmittedExpression */:
74161                 return (kinds & 8 /* PartiallyEmittedExpressions */) !== 0;
74162         }
74163         return false;
74164     }
74165     ts.isOuterExpression = isOuterExpression;
74166     function skipOuterExpressions(node, kinds) {
74167         if (kinds === void 0) { kinds = 15 /* All */; }
74168         while (isOuterExpression(node, kinds)) {
74169             node = node.expression;
74170         }
74171         return node;
74172     }
74173     ts.skipOuterExpressions = skipOuterExpressions;
74174     function skipAssertions(node) {
74175         return skipOuterExpressions(node, 6 /* Assertions */);
74176     }
74177     ts.skipAssertions = skipAssertions;
74178     function updateOuterExpression(outerExpression, expression) {
74179         switch (outerExpression.kind) {
74180             case 200 /* ParenthesizedExpression */: return ts.updateParen(outerExpression, expression);
74181             case 199 /* TypeAssertionExpression */: return ts.updateTypeAssertion(outerExpression, outerExpression.type, expression);
74182             case 217 /* AsExpression */: return ts.updateAsExpression(outerExpression, expression, outerExpression.type);
74183             case 218 /* NonNullExpression */: return ts.updateNonNullExpression(outerExpression, expression);
74184             case 326 /* PartiallyEmittedExpression */: return ts.updatePartiallyEmittedExpression(outerExpression, expression);
74185         }
74186     }
74187     /**
74188      * Determines whether a node is a parenthesized expression that can be ignored when recreating outer expressions.
74189      *
74190      * A parenthesized expression can be ignored when all of the following are true:
74191      *
74192      * - It's `pos` and `end` are not -1
74193      * - It does not have a custom source map range
74194      * - It does not have a custom comment range
74195      * - It does not have synthetic leading or trailing comments
74196      *
74197      * If an outermost parenthesized expression is ignored, but the containing expression requires a parentheses around
74198      * the expression to maintain precedence, a new parenthesized expression should be created automatically when
74199      * the containing expression is created/updated.
74200      */
74201     function isIgnorableParen(node) {
74202         return node.kind === 200 /* ParenthesizedExpression */
74203             && ts.nodeIsSynthesized(node)
74204             && ts.nodeIsSynthesized(ts.getSourceMapRange(node))
74205             && ts.nodeIsSynthesized(ts.getCommentRange(node))
74206             && !ts.some(ts.getSyntheticLeadingComments(node))
74207             && !ts.some(ts.getSyntheticTrailingComments(node));
74208     }
74209     function recreateOuterExpressions(outerExpression, innerExpression, kinds) {
74210         if (kinds === void 0) { kinds = 15 /* All */; }
74211         if (outerExpression && isOuterExpression(outerExpression, kinds) && !isIgnorableParen(outerExpression)) {
74212             return updateOuterExpression(outerExpression, recreateOuterExpressions(outerExpression.expression, innerExpression));
74213         }
74214         return innerExpression;
74215     }
74216     ts.recreateOuterExpressions = recreateOuterExpressions;
74217     function startOnNewLine(node) {
74218         return ts.setStartsOnNewLine(node, /*newLine*/ true);
74219     }
74220     ts.startOnNewLine = startOnNewLine;
74221     function getExternalHelpersModuleName(node) {
74222         var parseNode = ts.getOriginalNode(node, ts.isSourceFile);
74223         var emitNode = parseNode && parseNode.emitNode;
74224         return emitNode && emitNode.externalHelpersModuleName;
74225     }
74226     ts.getExternalHelpersModuleName = getExternalHelpersModuleName;
74227     function hasRecordedExternalHelpers(sourceFile) {
74228         var parseNode = ts.getOriginalNode(sourceFile, ts.isSourceFile);
74229         var emitNode = parseNode && parseNode.emitNode;
74230         return !!emitNode && (!!emitNode.externalHelpersModuleName || !!emitNode.externalHelpers);
74231     }
74232     ts.hasRecordedExternalHelpers = hasRecordedExternalHelpers;
74233     function createExternalHelpersImportDeclarationIfNeeded(sourceFile, compilerOptions, hasExportStarsToExportValues, hasImportStar, hasImportDefault) {
74234         if (compilerOptions.importHelpers && ts.isEffectiveExternalModule(sourceFile, compilerOptions)) {
74235             var namedBindings = void 0;
74236             var moduleKind = ts.getEmitModuleKind(compilerOptions);
74237             if (moduleKind >= ts.ModuleKind.ES2015 && moduleKind <= ts.ModuleKind.ESNext) {
74238                 // use named imports
74239                 var helpers = ts.getEmitHelpers(sourceFile);
74240                 if (helpers) {
74241                     var helperNames = [];
74242                     for (var _i = 0, helpers_2 = helpers; _i < helpers_2.length; _i++) {
74243                         var helper = helpers_2[_i];
74244                         if (!helper.scoped) {
74245                             var importName = helper.importName;
74246                             if (importName) {
74247                                 ts.pushIfUnique(helperNames, importName);
74248                             }
74249                         }
74250                     }
74251                     if (ts.some(helperNames)) {
74252                         helperNames.sort(ts.compareStringsCaseSensitive);
74253                         // Alias the imports if the names are used somewhere in the file.
74254                         // NOTE: We don't need to care about global import collisions as this is a module.
74255                         namedBindings = ts.createNamedImports(ts.map(helperNames, function (name) { return ts.isFileLevelUniqueName(sourceFile, name)
74256                             ? ts.createImportSpecifier(/*propertyName*/ undefined, ts.createIdentifier(name))
74257                             : ts.createImportSpecifier(ts.createIdentifier(name), getUnscopedHelperName(name)); }));
74258                         var parseNode = ts.getOriginalNode(sourceFile, ts.isSourceFile);
74259                         var emitNode = ts.getOrCreateEmitNode(parseNode);
74260                         emitNode.externalHelpers = true;
74261                     }
74262                 }
74263             }
74264             else {
74265                 // use a namespace import
74266                 var externalHelpersModuleName = getOrCreateExternalHelpersModuleNameIfNeeded(sourceFile, compilerOptions, hasExportStarsToExportValues, hasImportStar || hasImportDefault);
74267                 if (externalHelpersModuleName) {
74268                     namedBindings = ts.createNamespaceImport(externalHelpersModuleName);
74269                 }
74270             }
74271             if (namedBindings) {
74272                 var externalHelpersImportDeclaration = ts.createImportDeclaration(
74273                 /*decorators*/ undefined, 
74274                 /*modifiers*/ undefined, ts.createImportClause(/*name*/ undefined, namedBindings), ts.createLiteral(ts.externalHelpersModuleNameText));
74275                 ts.addEmitFlags(externalHelpersImportDeclaration, 67108864 /* NeverApplyImportHelper */);
74276                 return externalHelpersImportDeclaration;
74277             }
74278         }
74279     }
74280     ts.createExternalHelpersImportDeclarationIfNeeded = createExternalHelpersImportDeclarationIfNeeded;
74281     function getOrCreateExternalHelpersModuleNameIfNeeded(node, compilerOptions, hasExportStarsToExportValues, hasImportStarOrImportDefault) {
74282         if (compilerOptions.importHelpers && ts.isEffectiveExternalModule(node, compilerOptions)) {
74283             var externalHelpersModuleName = getExternalHelpersModuleName(node);
74284             if (externalHelpersModuleName) {
74285                 return externalHelpersModuleName;
74286             }
74287             var moduleKind = ts.getEmitModuleKind(compilerOptions);
74288             var create = (hasExportStarsToExportValues || (compilerOptions.esModuleInterop && hasImportStarOrImportDefault))
74289                 && moduleKind !== ts.ModuleKind.System
74290                 && moduleKind < ts.ModuleKind.ES2015;
74291             if (!create) {
74292                 var helpers = ts.getEmitHelpers(node);
74293                 if (helpers) {
74294                     for (var _i = 0, helpers_3 = helpers; _i < helpers_3.length; _i++) {
74295                         var helper = helpers_3[_i];
74296                         if (!helper.scoped) {
74297                             create = true;
74298                             break;
74299                         }
74300                     }
74301                 }
74302             }
74303             if (create) {
74304                 var parseNode = ts.getOriginalNode(node, ts.isSourceFile);
74305                 var emitNode = ts.getOrCreateEmitNode(parseNode);
74306                 return emitNode.externalHelpersModuleName || (emitNode.externalHelpersModuleName = ts.createUniqueName(ts.externalHelpersModuleNameText));
74307             }
74308         }
74309     }
74310     ts.getOrCreateExternalHelpersModuleNameIfNeeded = getOrCreateExternalHelpersModuleNameIfNeeded;
74311     /**
74312      * Get the name of that target module from an import or export declaration
74313      */
74314     function getLocalNameForExternalImport(node, sourceFile) {
74315         var namespaceDeclaration = ts.getNamespaceDeclarationNode(node);
74316         if (namespaceDeclaration && !ts.isDefaultImport(node)) {
74317             var name = namespaceDeclaration.name;
74318             return ts.isGeneratedIdentifier(name) ? name : ts.createIdentifier(ts.getSourceTextOfNodeFromSourceFile(sourceFile, name) || ts.idText(name));
74319         }
74320         if (node.kind === 254 /* ImportDeclaration */ && node.importClause) {
74321             return ts.getGeneratedNameForNode(node);
74322         }
74323         if (node.kind === 260 /* ExportDeclaration */ && node.moduleSpecifier) {
74324             return ts.getGeneratedNameForNode(node);
74325         }
74326         return undefined;
74327     }
74328     ts.getLocalNameForExternalImport = getLocalNameForExternalImport;
74329     /**
74330      * Get the name of a target module from an import/export declaration as should be written in the emitted output.
74331      * The emitted output name can be different from the input if:
74332      *  1. The module has a /// <amd-module name="<new name>" />
74333      *  2. --out or --outFile is used, making the name relative to the rootDir
74334      *  3- The containing SourceFile has an entry in renamedDependencies for the import as requested by some module loaders (e.g. System).
74335      * Otherwise, a new StringLiteral node representing the module name will be returned.
74336      */
74337     function getExternalModuleNameLiteral(importNode, sourceFile, host, resolver, compilerOptions) {
74338         var moduleName = ts.getExternalModuleName(importNode); // TODO: GH#18217
74339         if (moduleName.kind === 10 /* StringLiteral */) {
74340             return tryGetModuleNameFromDeclaration(importNode, host, resolver, compilerOptions)
74341                 || tryRenameExternalModule(moduleName, sourceFile)
74342                 || ts.getSynthesizedClone(moduleName);
74343         }
74344         return undefined;
74345     }
74346     ts.getExternalModuleNameLiteral = getExternalModuleNameLiteral;
74347     /**
74348      * Some bundlers (SystemJS builder) sometimes want to rename dependencies.
74349      * Here we check if alternative name was provided for a given moduleName and return it if possible.
74350      */
74351     function tryRenameExternalModule(moduleName, sourceFile) {
74352         var rename = sourceFile.renamedDependencies && sourceFile.renamedDependencies.get(moduleName.text);
74353         return rename && ts.createLiteral(rename);
74354     }
74355     /**
74356      * Get the name of a module as should be written in the emitted output.
74357      * The emitted output name can be different from the input if:
74358      *  1. The module has a /// <amd-module name="<new name>" />
74359      *  2. --out or --outFile is used, making the name relative to the rootDir
74360      * Otherwise, a new StringLiteral node representing the module name will be returned.
74361      */
74362     function tryGetModuleNameFromFile(file, host, options) {
74363         if (!file) {
74364             return undefined;
74365         }
74366         if (file.moduleName) {
74367             return ts.createLiteral(file.moduleName);
74368         }
74369         if (!file.isDeclarationFile && (options.out || options.outFile)) {
74370             return ts.createLiteral(ts.getExternalModuleNameFromPath(host, file.fileName));
74371         }
74372         return undefined;
74373     }
74374     ts.tryGetModuleNameFromFile = tryGetModuleNameFromFile;
74375     function tryGetModuleNameFromDeclaration(declaration, host, resolver, compilerOptions) {
74376         return tryGetModuleNameFromFile(resolver.getExternalModuleFileFromDeclaration(declaration), host, compilerOptions);
74377     }
74378     /**
74379      * Gets the initializer of an BindingOrAssignmentElement.
74380      */
74381     function getInitializerOfBindingOrAssignmentElement(bindingElement) {
74382         if (ts.isDeclarationBindingElement(bindingElement)) {
74383             // `1` in `let { a = 1 } = ...`
74384             // `1` in `let { a: b = 1 } = ...`
74385             // `1` in `let { a: {b} = 1 } = ...`
74386             // `1` in `let { a: [b] = 1 } = ...`
74387             // `1` in `let [a = 1] = ...`
74388             // `1` in `let [{a} = 1] = ...`
74389             // `1` in `let [[a] = 1] = ...`
74390             return bindingElement.initializer;
74391         }
74392         if (ts.isPropertyAssignment(bindingElement)) {
74393             // `1` in `({ a: b = 1 } = ...)`
74394             // `1` in `({ a: {b} = 1 } = ...)`
74395             // `1` in `({ a: [b] = 1 } = ...)`
74396             var initializer = bindingElement.initializer;
74397             return ts.isAssignmentExpression(initializer, /*excludeCompoundAssignment*/ true)
74398                 ? initializer.right
74399                 : undefined;
74400         }
74401         if (ts.isShorthandPropertyAssignment(bindingElement)) {
74402             // `1` in `({ a = 1 } = ...)`
74403             return bindingElement.objectAssignmentInitializer;
74404         }
74405         if (ts.isAssignmentExpression(bindingElement, /*excludeCompoundAssignment*/ true)) {
74406             // `1` in `[a = 1] = ...`
74407             // `1` in `[{a} = 1] = ...`
74408             // `1` in `[[a] = 1] = ...`
74409             return bindingElement.right;
74410         }
74411         if (ts.isSpreadElement(bindingElement)) {
74412             // Recovery consistent with existing emit.
74413             return getInitializerOfBindingOrAssignmentElement(bindingElement.expression);
74414         }
74415     }
74416     ts.getInitializerOfBindingOrAssignmentElement = getInitializerOfBindingOrAssignmentElement;
74417     /**
74418      * Gets the name of an BindingOrAssignmentElement.
74419      */
74420     function getTargetOfBindingOrAssignmentElement(bindingElement) {
74421         if (ts.isDeclarationBindingElement(bindingElement)) {
74422             // `a` in `let { a } = ...`
74423             // `a` in `let { a = 1 } = ...`
74424             // `b` in `let { a: b } = ...`
74425             // `b` in `let { a: b = 1 } = ...`
74426             // `a` in `let { ...a } = ...`
74427             // `{b}` in `let { a: {b} } = ...`
74428             // `{b}` in `let { a: {b} = 1 } = ...`
74429             // `[b]` in `let { a: [b] } = ...`
74430             // `[b]` in `let { a: [b] = 1 } = ...`
74431             // `a` in `let [a] = ...`
74432             // `a` in `let [a = 1] = ...`
74433             // `a` in `let [...a] = ...`
74434             // `{a}` in `let [{a}] = ...`
74435             // `{a}` in `let [{a} = 1] = ...`
74436             // `[a]` in `let [[a]] = ...`
74437             // `[a]` in `let [[a] = 1] = ...`
74438             return bindingElement.name;
74439         }
74440         if (ts.isObjectLiteralElementLike(bindingElement)) {
74441             switch (bindingElement.kind) {
74442                 case 281 /* PropertyAssignment */:
74443                     // `b` in `({ a: b } = ...)`
74444                     // `b` in `({ a: b = 1 } = ...)`
74445                     // `{b}` in `({ a: {b} } = ...)`
74446                     // `{b}` in `({ a: {b} = 1 } = ...)`
74447                     // `[b]` in `({ a: [b] } = ...)`
74448                     // `[b]` in `({ a: [b] = 1 } = ...)`
74449                     // `b.c` in `({ a: b.c } = ...)`
74450                     // `b.c` in `({ a: b.c = 1 } = ...)`
74451                     // `b[0]` in `({ a: b[0] } = ...)`
74452                     // `b[0]` in `({ a: b[0] = 1 } = ...)`
74453                     return getTargetOfBindingOrAssignmentElement(bindingElement.initializer);
74454                 case 282 /* ShorthandPropertyAssignment */:
74455                     // `a` in `({ a } = ...)`
74456                     // `a` in `({ a = 1 } = ...)`
74457                     return bindingElement.name;
74458                 case 283 /* SpreadAssignment */:
74459                     // `a` in `({ ...a } = ...)`
74460                     return getTargetOfBindingOrAssignmentElement(bindingElement.expression);
74461             }
74462             // no target
74463             return undefined;
74464         }
74465         if (ts.isAssignmentExpression(bindingElement, /*excludeCompoundAssignment*/ true)) {
74466             // `a` in `[a = 1] = ...`
74467             // `{a}` in `[{a} = 1] = ...`
74468             // `[a]` in `[[a] = 1] = ...`
74469             // `a.b` in `[a.b = 1] = ...`
74470             // `a[0]` in `[a[0] = 1] = ...`
74471             return getTargetOfBindingOrAssignmentElement(bindingElement.left);
74472         }
74473         if (ts.isSpreadElement(bindingElement)) {
74474             // `a` in `[...a] = ...`
74475             return getTargetOfBindingOrAssignmentElement(bindingElement.expression);
74476         }
74477         // `a` in `[a] = ...`
74478         // `{a}` in `[{a}] = ...`
74479         // `[a]` in `[[a]] = ...`
74480         // `a.b` in `[a.b] = ...`
74481         // `a[0]` in `[a[0]] = ...`
74482         return bindingElement;
74483     }
74484     ts.getTargetOfBindingOrAssignmentElement = getTargetOfBindingOrAssignmentElement;
74485     /**
74486      * Determines whether an BindingOrAssignmentElement is a rest element.
74487      */
74488     function getRestIndicatorOfBindingOrAssignmentElement(bindingElement) {
74489         switch (bindingElement.kind) {
74490             case 156 /* Parameter */:
74491             case 191 /* BindingElement */:
74492                 // `...` in `let [...a] = ...`
74493                 return bindingElement.dotDotDotToken;
74494             case 213 /* SpreadElement */:
74495             case 283 /* SpreadAssignment */:
74496                 // `...` in `[...a] = ...`
74497                 return bindingElement;
74498         }
74499         return undefined;
74500     }
74501     ts.getRestIndicatorOfBindingOrAssignmentElement = getRestIndicatorOfBindingOrAssignmentElement;
74502     /**
74503      * Gets the property name of a BindingOrAssignmentElement
74504      */
74505     function getPropertyNameOfBindingOrAssignmentElement(bindingElement) {
74506         var propertyName = tryGetPropertyNameOfBindingOrAssignmentElement(bindingElement);
74507         ts.Debug.assert(!!propertyName || ts.isSpreadAssignment(bindingElement), "Invalid property name for binding element.");
74508         return propertyName;
74509     }
74510     ts.getPropertyNameOfBindingOrAssignmentElement = getPropertyNameOfBindingOrAssignmentElement;
74511     function tryGetPropertyNameOfBindingOrAssignmentElement(bindingElement) {
74512         switch (bindingElement.kind) {
74513             case 191 /* BindingElement */:
74514                 // `a` in `let { a: b } = ...`
74515                 // `[a]` in `let { [a]: b } = ...`
74516                 // `"a"` in `let { "a": b } = ...`
74517                 // `1` in `let { 1: b } = ...`
74518                 if (bindingElement.propertyName) {
74519                     var propertyName = bindingElement.propertyName;
74520                     if (ts.isPrivateIdentifier(propertyName)) {
74521                         return ts.Debug.failBadSyntaxKind(propertyName);
74522                     }
74523                     return ts.isComputedPropertyName(propertyName) && isStringOrNumericLiteral(propertyName.expression)
74524                         ? propertyName.expression
74525                         : propertyName;
74526                 }
74527                 break;
74528             case 281 /* PropertyAssignment */:
74529                 // `a` in `({ a: b } = ...)`
74530                 // `[a]` in `({ [a]: b } = ...)`
74531                 // `"a"` in `({ "a": b } = ...)`
74532                 // `1` in `({ 1: b } = ...)`
74533                 if (bindingElement.name) {
74534                     var propertyName = bindingElement.name;
74535                     if (ts.isPrivateIdentifier(propertyName)) {
74536                         return ts.Debug.failBadSyntaxKind(propertyName);
74537                     }
74538                     return ts.isComputedPropertyName(propertyName) && isStringOrNumericLiteral(propertyName.expression)
74539                         ? propertyName.expression
74540                         : propertyName;
74541                 }
74542                 break;
74543             case 283 /* SpreadAssignment */:
74544                 // `a` in `({ ...a } = ...)`
74545                 if (bindingElement.name && ts.isPrivateIdentifier(bindingElement.name)) {
74546                     return ts.Debug.failBadSyntaxKind(bindingElement.name);
74547                 }
74548                 return bindingElement.name;
74549         }
74550         var target = getTargetOfBindingOrAssignmentElement(bindingElement);
74551         if (target && ts.isPropertyName(target)) {
74552             return target;
74553         }
74554     }
74555     ts.tryGetPropertyNameOfBindingOrAssignmentElement = tryGetPropertyNameOfBindingOrAssignmentElement;
74556     function isStringOrNumericLiteral(node) {
74557         var kind = node.kind;
74558         return kind === 10 /* StringLiteral */
74559             || kind === 8 /* NumericLiteral */;
74560     }
74561     /**
74562      * Gets the elements of a BindingOrAssignmentPattern
74563      */
74564     function getElementsOfBindingOrAssignmentPattern(name) {
74565         switch (name.kind) {
74566             case 189 /* ObjectBindingPattern */:
74567             case 190 /* ArrayBindingPattern */:
74568             case 192 /* ArrayLiteralExpression */:
74569                 // `a` in `{a}`
74570                 // `a` in `[a]`
74571                 return name.elements;
74572             case 193 /* ObjectLiteralExpression */:
74573                 // `a` in `{a}`
74574                 return name.properties;
74575         }
74576     }
74577     ts.getElementsOfBindingOrAssignmentPattern = getElementsOfBindingOrAssignmentPattern;
74578     function convertToArrayAssignmentElement(element) {
74579         if (ts.isBindingElement(element)) {
74580             if (element.dotDotDotToken) {
74581                 ts.Debug.assertNode(element.name, ts.isIdentifier);
74582                 return ts.setOriginalNode(ts.setTextRange(ts.createSpread(element.name), element), element);
74583             }
74584             var expression = convertToAssignmentElementTarget(element.name);
74585             return element.initializer
74586                 ? ts.setOriginalNode(ts.setTextRange(ts.createAssignment(expression, element.initializer), element), element)
74587                 : expression;
74588         }
74589         ts.Debug.assertNode(element, ts.isExpression);
74590         return element;
74591     }
74592     ts.convertToArrayAssignmentElement = convertToArrayAssignmentElement;
74593     function convertToObjectAssignmentElement(element) {
74594         if (ts.isBindingElement(element)) {
74595             if (element.dotDotDotToken) {
74596                 ts.Debug.assertNode(element.name, ts.isIdentifier);
74597                 return ts.setOriginalNode(ts.setTextRange(ts.createSpreadAssignment(element.name), element), element);
74598             }
74599             if (element.propertyName) {
74600                 var expression = convertToAssignmentElementTarget(element.name);
74601                 return ts.setOriginalNode(ts.setTextRange(ts.createPropertyAssignment(element.propertyName, element.initializer ? ts.createAssignment(expression, element.initializer) : expression), element), element);
74602             }
74603             ts.Debug.assertNode(element.name, ts.isIdentifier);
74604             return ts.setOriginalNode(ts.setTextRange(ts.createShorthandPropertyAssignment(element.name, element.initializer), element), element);
74605         }
74606         ts.Debug.assertNode(element, ts.isObjectLiteralElementLike);
74607         return element;
74608     }
74609     ts.convertToObjectAssignmentElement = convertToObjectAssignmentElement;
74610     function convertToAssignmentPattern(node) {
74611         switch (node.kind) {
74612             case 190 /* ArrayBindingPattern */:
74613             case 192 /* ArrayLiteralExpression */:
74614                 return convertToArrayAssignmentPattern(node);
74615             case 189 /* ObjectBindingPattern */:
74616             case 193 /* ObjectLiteralExpression */:
74617                 return convertToObjectAssignmentPattern(node);
74618         }
74619     }
74620     ts.convertToAssignmentPattern = convertToAssignmentPattern;
74621     function convertToObjectAssignmentPattern(node) {
74622         if (ts.isObjectBindingPattern(node)) {
74623             return ts.setOriginalNode(ts.setTextRange(ts.createObjectLiteral(ts.map(node.elements, convertToObjectAssignmentElement)), node), node);
74624         }
74625         ts.Debug.assertNode(node, ts.isObjectLiteralExpression);
74626         return node;
74627     }
74628     ts.convertToObjectAssignmentPattern = convertToObjectAssignmentPattern;
74629     function convertToArrayAssignmentPattern(node) {
74630         if (ts.isArrayBindingPattern(node)) {
74631             return ts.setOriginalNode(ts.setTextRange(ts.createArrayLiteral(ts.map(node.elements, convertToArrayAssignmentElement)), node), node);
74632         }
74633         ts.Debug.assertNode(node, ts.isArrayLiteralExpression);
74634         return node;
74635     }
74636     ts.convertToArrayAssignmentPattern = convertToArrayAssignmentPattern;
74637     function convertToAssignmentElementTarget(node) {
74638         if (ts.isBindingPattern(node)) {
74639             return convertToAssignmentPattern(node);
74640         }
74641         ts.Debug.assertNode(node, ts.isExpression);
74642         return node;
74643     }
74644     ts.convertToAssignmentElementTarget = convertToAssignmentElementTarget;
74645 })(ts || (ts = {}));
74646 var ts;
74647 (function (ts) {
74648     var isTypeNodeOrTypeParameterDeclaration = ts.or(ts.isTypeNode, ts.isTypeParameterDeclaration);
74649     function visitNode(node, visitor, test, lift) {
74650         if (node === undefined || visitor === undefined) {
74651             return node;
74652         }
74653         ts.aggregateTransformFlags(node);
74654         var visited = visitor(node);
74655         if (visited === node) {
74656             return node;
74657         }
74658         var visitedNode;
74659         if (visited === undefined) {
74660             return undefined;
74661         }
74662         else if (ts.isArray(visited)) {
74663             visitedNode = (lift || extractSingleNode)(visited);
74664         }
74665         else {
74666             visitedNode = visited;
74667         }
74668         ts.Debug.assertNode(visitedNode, test);
74669         ts.aggregateTransformFlags(visitedNode);
74670         return visitedNode;
74671     }
74672     ts.visitNode = visitNode;
74673     /**
74674      * Visits a NodeArray using the supplied visitor, possibly returning a new NodeArray in its place.
74675      *
74676      * @param nodes The NodeArray to visit.
74677      * @param visitor The callback used to visit a Node.
74678      * @param test A node test to execute for each node.
74679      * @param start An optional value indicating the starting offset at which to start visiting.
74680      * @param count An optional value indicating the maximum number of nodes to visit.
74681      */
74682     function visitNodes(nodes, visitor, test, start, count) {
74683         if (nodes === undefined || visitor === undefined) {
74684             return nodes;
74685         }
74686         var updated;
74687         // Ensure start and count have valid values
74688         var length = nodes.length;
74689         if (start === undefined || start < 0) {
74690             start = 0;
74691         }
74692         if (count === undefined || count > length - start) {
74693             count = length - start;
74694         }
74695         if (start > 0 || count < length) {
74696             // If we are not visiting all of the original nodes, we must always create a new array.
74697             // Since this is a fragment of a node array, we do not copy over the previous location
74698             // and will only copy over `hasTrailingComma` if we are including the last element.
74699             updated = ts.createNodeArray([], /*hasTrailingComma*/ nodes.hasTrailingComma && start + count === length);
74700         }
74701         // Visit each original node.
74702         for (var i = 0; i < count; i++) {
74703             var node = nodes[i + start];
74704             ts.aggregateTransformFlags(node);
74705             var visited = node !== undefined ? visitor(node) : undefined;
74706             if (updated !== undefined || visited === undefined || visited !== node) {
74707                 if (updated === undefined) {
74708                     // Ensure we have a copy of `nodes`, up to the current index.
74709                     updated = ts.createNodeArray(nodes.slice(0, i), nodes.hasTrailingComma);
74710                     ts.setTextRange(updated, nodes);
74711                 }
74712                 if (visited) {
74713                     if (ts.isArray(visited)) {
74714                         for (var _i = 0, visited_1 = visited; _i < visited_1.length; _i++) {
74715                             var visitedNode = visited_1[_i];
74716                             ts.Debug.assertNode(visitedNode, test);
74717                             ts.aggregateTransformFlags(visitedNode);
74718                             updated.push(visitedNode);
74719                         }
74720                     }
74721                     else {
74722                         ts.Debug.assertNode(visited, test);
74723                         ts.aggregateTransformFlags(visited);
74724                         updated.push(visited);
74725                     }
74726                 }
74727             }
74728         }
74729         return updated || nodes;
74730     }
74731     ts.visitNodes = visitNodes;
74732     /**
74733      * Starts a new lexical environment and visits a statement list, ending the lexical environment
74734      * and merging hoisted declarations upon completion.
74735      */
74736     function visitLexicalEnvironment(statements, visitor, context, start, ensureUseStrict) {
74737         context.startLexicalEnvironment();
74738         statements = visitNodes(statements, visitor, ts.isStatement, start);
74739         if (ensureUseStrict)
74740             statements = ts.ensureUseStrict(statements); // eslint-disable-line @typescript-eslint/no-unnecessary-qualifier
74741         return ts.mergeLexicalEnvironment(statements, context.endLexicalEnvironment());
74742     }
74743     ts.visitLexicalEnvironment = visitLexicalEnvironment;
74744     function visitParameterList(nodes, visitor, context, nodesVisitor) {
74745         if (nodesVisitor === void 0) { nodesVisitor = visitNodes; }
74746         var updated;
74747         context.startLexicalEnvironment();
74748         if (nodes) {
74749             context.setLexicalEnvironmentFlags(1 /* InParameters */, true);
74750             updated = nodesVisitor(nodes, visitor, ts.isParameterDeclaration);
74751             // As of ES2015, any runtime execution of that occurs in for a parameter (such as evaluating an
74752             // initializer or a binding pattern), occurs in its own lexical scope. As a result, any expression
74753             // that we might transform that introduces a temporary variable would fail as the temporary variable
74754             // exists in a different lexical scope. To address this, we move any binding patterns and initializers
74755             // in a parameter list to the body if we detect a variable being hoisted while visiting a parameter list
74756             // when the emit target is greater than ES2015.
74757             if (context.getLexicalEnvironmentFlags() & 2 /* VariablesHoistedInParameters */ &&
74758                 ts.getEmitScriptTarget(context.getCompilerOptions()) >= 2 /* ES2015 */) {
74759                 updated = addDefaultValueAssignmentsIfNeeded(updated, context);
74760             }
74761             context.setLexicalEnvironmentFlags(1 /* InParameters */, false);
74762         }
74763         context.suspendLexicalEnvironment();
74764         return updated;
74765     }
74766     ts.visitParameterList = visitParameterList;
74767     function addDefaultValueAssignmentsIfNeeded(parameters, context) {
74768         var result;
74769         for (var i = 0; i < parameters.length; i++) {
74770             var parameter = parameters[i];
74771             var updated = addDefaultValueAssignmentIfNeeded(parameter, context);
74772             if (result || updated !== parameter) {
74773                 if (!result)
74774                     result = parameters.slice(0, i);
74775                 result[i] = updated;
74776             }
74777         }
74778         if (result) {
74779             return ts.setTextRange(ts.createNodeArray(result, parameters.hasTrailingComma), parameters);
74780         }
74781         return parameters;
74782     }
74783     function addDefaultValueAssignmentIfNeeded(parameter, context) {
74784         // A rest parameter cannot have a binding pattern or an initializer,
74785         // so let's just ignore it.
74786         return parameter.dotDotDotToken ? parameter :
74787             ts.isBindingPattern(parameter.name) ? addDefaultValueAssignmentForBindingPattern(parameter, context) :
74788                 parameter.initializer ? addDefaultValueAssignmentForInitializer(parameter, parameter.name, parameter.initializer, context) :
74789                     parameter;
74790     }
74791     function addDefaultValueAssignmentForBindingPattern(parameter, context) {
74792         context.addInitializationStatement(ts.createVariableStatement(
74793         /*modifiers*/ undefined, ts.createVariableDeclarationList([
74794             ts.createVariableDeclaration(parameter.name, parameter.type, parameter.initializer ?
74795                 ts.createConditional(ts.createStrictEquality(ts.getGeneratedNameForNode(parameter), ts.createVoidZero()), parameter.initializer, ts.getGeneratedNameForNode(parameter)) :
74796                 ts.getGeneratedNameForNode(parameter)),
74797         ])));
74798         return ts.updateParameter(parameter, parameter.decorators, parameter.modifiers, parameter.dotDotDotToken, ts.getGeneratedNameForNode(parameter), parameter.questionToken, parameter.type, 
74799         /*initializer*/ undefined);
74800     }
74801     function addDefaultValueAssignmentForInitializer(parameter, name, initializer, context) {
74802         context.addInitializationStatement(ts.createIf(ts.createTypeCheck(ts.getSynthesizedClone(name), "undefined"), ts.setEmitFlags(ts.setTextRange(ts.createBlock([
74803             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 */))
74804         ]), parameter), 1 /* SingleLine */ | 32 /* NoTrailingSourceMap */ | 384 /* NoTokenSourceMaps */ | 1536 /* NoComments */)));
74805         return ts.updateParameter(parameter, parameter.decorators, parameter.modifiers, parameter.dotDotDotToken, parameter.name, parameter.questionToken, parameter.type, 
74806         /*initializer*/ undefined);
74807     }
74808     function visitFunctionBody(node, visitor, context) {
74809         context.resumeLexicalEnvironment();
74810         var updated = visitNode(node, visitor, ts.isConciseBody);
74811         var declarations = context.endLexicalEnvironment();
74812         if (ts.some(declarations)) {
74813             var block = ts.convertToFunctionBody(updated);
74814             var statements = ts.mergeLexicalEnvironment(block.statements, declarations);
74815             return ts.updateBlock(block, statements);
74816         }
74817         return updated;
74818     }
74819     ts.visitFunctionBody = visitFunctionBody;
74820     function visitEachChild(node, visitor, context, nodesVisitor, tokenVisitor) {
74821         if (nodesVisitor === void 0) { nodesVisitor = visitNodes; }
74822         if (node === undefined) {
74823             return undefined;
74824         }
74825         var kind = node.kind;
74826         // No need to visit nodes with no children.
74827         if ((kind > 0 /* FirstToken */ && kind <= 152 /* LastToken */) || kind === 183 /* ThisType */) {
74828             return node;
74829         }
74830         switch (kind) {
74831             // Names
74832             case 75 /* Identifier */:
74833                 return ts.updateIdentifier(node, nodesVisitor(node.typeArguments, visitor, isTypeNodeOrTypeParameterDeclaration));
74834             case 153 /* QualifiedName */:
74835                 return ts.updateQualifiedName(node, visitNode(node.left, visitor, ts.isEntityName), visitNode(node.right, visitor, ts.isIdentifier));
74836             case 154 /* ComputedPropertyName */:
74837                 return ts.updateComputedPropertyName(node, visitNode(node.expression, visitor, ts.isExpression));
74838             // Signature elements
74839             case 155 /* TypeParameter */:
74840                 return ts.updateTypeParameterDeclaration(node, visitNode(node.name, visitor, ts.isIdentifier), visitNode(node.constraint, visitor, ts.isTypeNode), visitNode(node.default, visitor, ts.isTypeNode));
74841             case 156 /* Parameter */:
74842                 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));
74843             case 157 /* Decorator */:
74844                 return ts.updateDecorator(node, visitNode(node.expression, visitor, ts.isExpression));
74845             // Type elements
74846             case 158 /* PropertySignature */:
74847                 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));
74848             case 159 /* PropertyDeclaration */:
74849                 return ts.updateProperty(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isPropertyName), 
74850                 // QuestionToken and ExclamationToken is uniqued in Property Declaration and the signature of 'updateProperty' is that too
74851                 visitNode(node.questionToken || node.exclamationToken, tokenVisitor, ts.isToken), visitNode(node.type, visitor, ts.isTypeNode), visitNode(node.initializer, visitor, ts.isExpression));
74852             case 160 /* MethodSignature */:
74853                 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));
74854             case 161 /* MethodDeclaration */:
74855                 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));
74856             case 162 /* Constructor */:
74857                 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));
74858             case 163 /* GetAccessor */:
74859                 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));
74860             case 164 /* SetAccessor */:
74861                 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));
74862             case 165 /* CallSignature */:
74863                 return ts.updateCallSignature(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode));
74864             case 166 /* ConstructSignature */:
74865                 return ts.updateConstructSignature(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode));
74866             case 167 /* IndexSignature */:
74867                 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));
74868             // Types
74869             case 168 /* TypePredicate */:
74870                 return ts.updateTypePredicateNodeWithModifier(node, visitNode(node.assertsModifier, visitor), visitNode(node.parameterName, visitor), visitNode(node.type, visitor, ts.isTypeNode));
74871             case 169 /* TypeReference */:
74872                 return ts.updateTypeReferenceNode(node, visitNode(node.typeName, visitor, ts.isEntityName), nodesVisitor(node.typeArguments, visitor, ts.isTypeNode));
74873             case 170 /* FunctionType */:
74874                 return ts.updateFunctionTypeNode(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode));
74875             case 171 /* ConstructorType */:
74876                 return ts.updateConstructorTypeNode(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode));
74877             case 172 /* TypeQuery */:
74878                 return ts.updateTypeQueryNode(node, visitNode(node.exprName, visitor, ts.isEntityName));
74879             case 173 /* TypeLiteral */:
74880                 return ts.updateTypeLiteralNode(node, nodesVisitor(node.members, visitor, ts.isTypeElement));
74881             case 174 /* ArrayType */:
74882                 return ts.updateArrayTypeNode(node, visitNode(node.elementType, visitor, ts.isTypeNode));
74883             case 175 /* TupleType */:
74884                 return ts.updateTupleTypeNode(node, nodesVisitor(node.elementTypes, visitor, ts.isTypeNode));
74885             case 176 /* OptionalType */:
74886                 return ts.updateOptionalTypeNode(node, visitNode(node.type, visitor, ts.isTypeNode));
74887             case 177 /* RestType */:
74888                 return ts.updateRestTypeNode(node, visitNode(node.type, visitor, ts.isTypeNode));
74889             case 178 /* UnionType */:
74890                 return ts.updateUnionTypeNode(node, nodesVisitor(node.types, visitor, ts.isTypeNode));
74891             case 179 /* IntersectionType */:
74892                 return ts.updateIntersectionTypeNode(node, nodesVisitor(node.types, visitor, ts.isTypeNode));
74893             case 180 /* ConditionalType */:
74894                 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));
74895             case 181 /* InferType */:
74896                 return ts.updateInferTypeNode(node, visitNode(node.typeParameter, visitor, ts.isTypeParameterDeclaration));
74897             case 188 /* ImportType */:
74898                 return ts.updateImportTypeNode(node, visitNode(node.argument, visitor, ts.isTypeNode), visitNode(node.qualifier, visitor, ts.isEntityName), visitNodes(node.typeArguments, visitor, ts.isTypeNode), node.isTypeOf);
74899             case 182 /* ParenthesizedType */:
74900                 return ts.updateParenthesizedType(node, visitNode(node.type, visitor, ts.isTypeNode));
74901             case 184 /* TypeOperator */:
74902                 return ts.updateTypeOperatorNode(node, visitNode(node.type, visitor, ts.isTypeNode));
74903             case 185 /* IndexedAccessType */:
74904                 return ts.updateIndexedAccessTypeNode(node, visitNode(node.objectType, visitor, ts.isTypeNode), visitNode(node.indexType, visitor, ts.isTypeNode));
74905             case 186 /* MappedType */:
74906                 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));
74907             case 187 /* LiteralType */:
74908                 return ts.updateLiteralTypeNode(node, visitNode(node.literal, visitor, ts.isExpression));
74909             // Binding patterns
74910             case 189 /* ObjectBindingPattern */:
74911                 return ts.updateObjectBindingPattern(node, nodesVisitor(node.elements, visitor, ts.isBindingElement));
74912             case 190 /* ArrayBindingPattern */:
74913                 return ts.updateArrayBindingPattern(node, nodesVisitor(node.elements, visitor, ts.isArrayBindingElement));
74914             case 191 /* BindingElement */:
74915                 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));
74916             // Expression
74917             case 192 /* ArrayLiteralExpression */:
74918                 return ts.updateArrayLiteral(node, nodesVisitor(node.elements, visitor, ts.isExpression));
74919             case 193 /* ObjectLiteralExpression */:
74920                 return ts.updateObjectLiteral(node, nodesVisitor(node.properties, visitor, ts.isObjectLiteralElementLike));
74921             case 194 /* PropertyAccessExpression */:
74922                 if (node.flags & 32 /* OptionalChain */) {
74923                     return ts.updatePropertyAccessChain(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.questionDotToken, tokenVisitor, ts.isToken), visitNode(node.name, visitor, ts.isIdentifier));
74924                 }
74925                 return ts.updatePropertyAccess(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.name, visitor, ts.isIdentifierOrPrivateIdentifier));
74926             case 195 /* ElementAccessExpression */:
74927                 if (node.flags & 32 /* OptionalChain */) {
74928                     return ts.updateElementAccessChain(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.questionDotToken, tokenVisitor, ts.isToken), visitNode(node.argumentExpression, visitor, ts.isExpression));
74929                 }
74930                 return ts.updateElementAccess(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.argumentExpression, visitor, ts.isExpression));
74931             case 196 /* CallExpression */:
74932                 if (node.flags & 32 /* OptionalChain */) {
74933                     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));
74934                 }
74935                 return ts.updateCall(node, visitNode(node.expression, visitor, ts.isExpression), nodesVisitor(node.typeArguments, visitor, ts.isTypeNode), nodesVisitor(node.arguments, visitor, ts.isExpression));
74936             case 197 /* NewExpression */:
74937                 return ts.updateNew(node, visitNode(node.expression, visitor, ts.isExpression), nodesVisitor(node.typeArguments, visitor, ts.isTypeNode), nodesVisitor(node.arguments, visitor, ts.isExpression));
74938             case 198 /* TaggedTemplateExpression */:
74939                 return ts.updateTaggedTemplate(node, visitNode(node.tag, visitor, ts.isExpression), visitNodes(node.typeArguments, visitor, ts.isExpression), visitNode(node.template, visitor, ts.isTemplateLiteral));
74940             case 199 /* TypeAssertionExpression */:
74941                 return ts.updateTypeAssertion(node, visitNode(node.type, visitor, ts.isTypeNode), visitNode(node.expression, visitor, ts.isExpression));
74942             case 200 /* ParenthesizedExpression */:
74943                 return ts.updateParen(node, visitNode(node.expression, visitor, ts.isExpression));
74944             case 201 /* FunctionExpression */:
74945                 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));
74946             case 202 /* ArrowFunction */:
74947                 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));
74948             case 203 /* DeleteExpression */:
74949                 return ts.updateDelete(node, visitNode(node.expression, visitor, ts.isExpression));
74950             case 204 /* TypeOfExpression */:
74951                 return ts.updateTypeOf(node, visitNode(node.expression, visitor, ts.isExpression));
74952             case 205 /* VoidExpression */:
74953                 return ts.updateVoid(node, visitNode(node.expression, visitor, ts.isExpression));
74954             case 206 /* AwaitExpression */:
74955                 return ts.updateAwait(node, visitNode(node.expression, visitor, ts.isExpression));
74956             case 207 /* PrefixUnaryExpression */:
74957                 return ts.updatePrefix(node, visitNode(node.operand, visitor, ts.isExpression));
74958             case 208 /* PostfixUnaryExpression */:
74959                 return ts.updatePostfix(node, visitNode(node.operand, visitor, ts.isExpression));
74960             case 209 /* BinaryExpression */:
74961                 return ts.updateBinary(node, visitNode(node.left, visitor, ts.isExpression), visitNode(node.right, visitor, ts.isExpression), visitNode(node.operatorToken, tokenVisitor, ts.isToken));
74962             case 210 /* ConditionalExpression */:
74963                 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));
74964             case 211 /* TemplateExpression */:
74965                 return ts.updateTemplateExpression(node, visitNode(node.head, visitor, ts.isTemplateHead), nodesVisitor(node.templateSpans, visitor, ts.isTemplateSpan));
74966             case 212 /* YieldExpression */:
74967                 return ts.updateYield(node, visitNode(node.asteriskToken, tokenVisitor, ts.isToken), visitNode(node.expression, visitor, ts.isExpression));
74968             case 213 /* SpreadElement */:
74969                 return ts.updateSpread(node, visitNode(node.expression, visitor, ts.isExpression));
74970             case 214 /* ClassExpression */:
74971                 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));
74972             case 216 /* ExpressionWithTypeArguments */:
74973                 return ts.updateExpressionWithTypeArguments(node, nodesVisitor(node.typeArguments, visitor, ts.isTypeNode), visitNode(node.expression, visitor, ts.isExpression));
74974             case 217 /* AsExpression */:
74975                 return ts.updateAsExpression(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.type, visitor, ts.isTypeNode));
74976             case 218 /* NonNullExpression */:
74977                 return ts.updateNonNullExpression(node, visitNode(node.expression, visitor, ts.isExpression));
74978             case 219 /* MetaProperty */:
74979                 return ts.updateMetaProperty(node, visitNode(node.name, visitor, ts.isIdentifier));
74980             // Misc
74981             case 221 /* TemplateSpan */:
74982                 return ts.updateTemplateSpan(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.literal, visitor, ts.isTemplateMiddleOrTemplateTail));
74983             // Element
74984             case 223 /* Block */:
74985                 return ts.updateBlock(node, nodesVisitor(node.statements, visitor, ts.isStatement));
74986             case 225 /* VariableStatement */:
74987                 return ts.updateVariableStatement(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.declarationList, visitor, ts.isVariableDeclarationList));
74988             case 226 /* ExpressionStatement */:
74989                 return ts.updateExpressionStatement(node, visitNode(node.expression, visitor, ts.isExpression));
74990             case 227 /* IfStatement */:
74991                 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));
74992             case 228 /* DoStatement */:
74993                 return ts.updateDo(node, visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock), visitNode(node.expression, visitor, ts.isExpression));
74994             case 229 /* WhileStatement */:
74995                 return ts.updateWhile(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock));
74996             case 230 /* ForStatement */:
74997                 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));
74998             case 231 /* ForInStatement */:
74999                 return ts.updateForIn(node, visitNode(node.initializer, visitor, ts.isForInitializer), visitNode(node.expression, visitor, ts.isExpression), visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock));
75000             case 232 /* ForOfStatement */:
75001                 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));
75002             case 233 /* ContinueStatement */:
75003                 return ts.updateContinue(node, visitNode(node.label, visitor, ts.isIdentifier));
75004             case 234 /* BreakStatement */:
75005                 return ts.updateBreak(node, visitNode(node.label, visitor, ts.isIdentifier));
75006             case 235 /* ReturnStatement */:
75007                 return ts.updateReturn(node, visitNode(node.expression, visitor, ts.isExpression));
75008             case 236 /* WithStatement */:
75009                 return ts.updateWith(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock));
75010             case 237 /* SwitchStatement */:
75011                 return ts.updateSwitch(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.caseBlock, visitor, ts.isCaseBlock));
75012             case 238 /* LabeledStatement */:
75013                 return ts.updateLabel(node, visitNode(node.label, visitor, ts.isIdentifier), visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock));
75014             case 239 /* ThrowStatement */:
75015                 return ts.updateThrow(node, visitNode(node.expression, visitor, ts.isExpression));
75016             case 240 /* TryStatement */:
75017                 return ts.updateTry(node, visitNode(node.tryBlock, visitor, ts.isBlock), visitNode(node.catchClause, visitor, ts.isCatchClause), visitNode(node.finallyBlock, visitor, ts.isBlock));
75018             case 242 /* VariableDeclaration */:
75019                 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));
75020             case 243 /* VariableDeclarationList */:
75021                 return ts.updateVariableDeclarationList(node, nodesVisitor(node.declarations, visitor, ts.isVariableDeclaration));
75022             case 244 /* FunctionDeclaration */:
75023                 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));
75024             case 245 /* ClassDeclaration */:
75025                 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));
75026             case 246 /* InterfaceDeclaration */:
75027                 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));
75028             case 247 /* TypeAliasDeclaration */:
75029                 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));
75030             case 248 /* EnumDeclaration */:
75031                 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));
75032             case 249 /* ModuleDeclaration */:
75033                 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));
75034             case 250 /* ModuleBlock */:
75035                 return ts.updateModuleBlock(node, nodesVisitor(node.statements, visitor, ts.isStatement));
75036             case 251 /* CaseBlock */:
75037                 return ts.updateCaseBlock(node, nodesVisitor(node.clauses, visitor, ts.isCaseOrDefaultClause));
75038             case 252 /* NamespaceExportDeclaration */:
75039                 return ts.updateNamespaceExportDeclaration(node, visitNode(node.name, visitor, ts.isIdentifier));
75040             case 253 /* ImportEqualsDeclaration */:
75041                 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));
75042             case 254 /* ImportDeclaration */:
75043                 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));
75044             case 255 /* ImportClause */:
75045                 return ts.updateImportClause(node, visitNode(node.name, visitor, ts.isIdentifier), visitNode(node.namedBindings, visitor, ts.isNamedImportBindings), node.isTypeOnly);
75046             case 256 /* NamespaceImport */:
75047                 return ts.updateNamespaceImport(node, visitNode(node.name, visitor, ts.isIdentifier));
75048             case 262 /* NamespaceExport */:
75049                 return ts.updateNamespaceExport(node, visitNode(node.name, visitor, ts.isIdentifier));
75050             case 257 /* NamedImports */:
75051                 return ts.updateNamedImports(node, nodesVisitor(node.elements, visitor, ts.isImportSpecifier));
75052             case 258 /* ImportSpecifier */:
75053                 return ts.updateImportSpecifier(node, visitNode(node.propertyName, visitor, ts.isIdentifier), visitNode(node.name, visitor, ts.isIdentifier));
75054             case 259 /* ExportAssignment */:
75055                 return ts.updateExportAssignment(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.expression, visitor, ts.isExpression));
75056             case 260 /* ExportDeclaration */:
75057                 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);
75058             case 261 /* NamedExports */:
75059                 return ts.updateNamedExports(node, nodesVisitor(node.elements, visitor, ts.isExportSpecifier));
75060             case 263 /* ExportSpecifier */:
75061                 return ts.updateExportSpecifier(node, visitNode(node.propertyName, visitor, ts.isIdentifier), visitNode(node.name, visitor, ts.isIdentifier));
75062             // Module references
75063             case 265 /* ExternalModuleReference */:
75064                 return ts.updateExternalModuleReference(node, visitNode(node.expression, visitor, ts.isExpression));
75065             // JSX
75066             case 266 /* JsxElement */:
75067                 return ts.updateJsxElement(node, visitNode(node.openingElement, visitor, ts.isJsxOpeningElement), nodesVisitor(node.children, visitor, ts.isJsxChild), visitNode(node.closingElement, visitor, ts.isJsxClosingElement));
75068             case 267 /* JsxSelfClosingElement */:
75069                 return ts.updateJsxSelfClosingElement(node, visitNode(node.tagName, visitor, ts.isJsxTagNameExpression), nodesVisitor(node.typeArguments, visitor, ts.isTypeNode), visitNode(node.attributes, visitor, ts.isJsxAttributes));
75070             case 268 /* JsxOpeningElement */:
75071                 return ts.updateJsxOpeningElement(node, visitNode(node.tagName, visitor, ts.isJsxTagNameExpression), nodesVisitor(node.typeArguments, visitor, ts.isTypeNode), visitNode(node.attributes, visitor, ts.isJsxAttributes));
75072             case 269 /* JsxClosingElement */:
75073                 return ts.updateJsxClosingElement(node, visitNode(node.tagName, visitor, ts.isJsxTagNameExpression));
75074             case 270 /* JsxFragment */:
75075                 return ts.updateJsxFragment(node, visitNode(node.openingFragment, visitor, ts.isJsxOpeningFragment), nodesVisitor(node.children, visitor, ts.isJsxChild), visitNode(node.closingFragment, visitor, ts.isJsxClosingFragment));
75076             case 273 /* JsxAttribute */:
75077                 return ts.updateJsxAttribute(node, visitNode(node.name, visitor, ts.isIdentifier), visitNode(node.initializer, visitor, ts.isStringLiteralOrJsxExpression));
75078             case 274 /* JsxAttributes */:
75079                 return ts.updateJsxAttributes(node, nodesVisitor(node.properties, visitor, ts.isJsxAttributeLike));
75080             case 275 /* JsxSpreadAttribute */:
75081                 return ts.updateJsxSpreadAttribute(node, visitNode(node.expression, visitor, ts.isExpression));
75082             case 276 /* JsxExpression */:
75083                 return ts.updateJsxExpression(node, visitNode(node.expression, visitor, ts.isExpression));
75084             // Clauses
75085             case 277 /* CaseClause */:
75086                 return ts.updateCaseClause(node, visitNode(node.expression, visitor, ts.isExpression), nodesVisitor(node.statements, visitor, ts.isStatement));
75087             case 278 /* DefaultClause */:
75088                 return ts.updateDefaultClause(node, nodesVisitor(node.statements, visitor, ts.isStatement));
75089             case 279 /* HeritageClause */:
75090                 return ts.updateHeritageClause(node, nodesVisitor(node.types, visitor, ts.isExpressionWithTypeArguments));
75091             case 280 /* CatchClause */:
75092                 return ts.updateCatchClause(node, visitNode(node.variableDeclaration, visitor, ts.isVariableDeclaration), visitNode(node.block, visitor, ts.isBlock));
75093             // Property assignments
75094             case 281 /* PropertyAssignment */:
75095                 return ts.updatePropertyAssignment(node, visitNode(node.name, visitor, ts.isPropertyName), visitNode(node.initializer, visitor, ts.isExpression));
75096             case 282 /* ShorthandPropertyAssignment */:
75097                 return ts.updateShorthandPropertyAssignment(node, visitNode(node.name, visitor, ts.isIdentifier), visitNode(node.objectAssignmentInitializer, visitor, ts.isExpression));
75098             case 283 /* SpreadAssignment */:
75099                 return ts.updateSpreadAssignment(node, visitNode(node.expression, visitor, ts.isExpression));
75100             // Enum
75101             case 284 /* EnumMember */:
75102                 return ts.updateEnumMember(node, visitNode(node.name, visitor, ts.isPropertyName), visitNode(node.initializer, visitor, ts.isExpression));
75103             // Top-level nodes
75104             case 290 /* SourceFile */:
75105                 return ts.updateSourceFileNode(node, visitLexicalEnvironment(node.statements, visitor, context));
75106             // Transformation nodes
75107             case 326 /* PartiallyEmittedExpression */:
75108                 return ts.updatePartiallyEmittedExpression(node, visitNode(node.expression, visitor, ts.isExpression));
75109             case 327 /* CommaListExpression */:
75110                 return ts.updateCommaList(node, nodesVisitor(node.elements, visitor, ts.isExpression));
75111             default:
75112                 // No need to visit nodes with no children.
75113                 return node;
75114         }
75115     }
75116     ts.visitEachChild = visitEachChild;
75117     /**
75118      * Extracts the single node from a NodeArray.
75119      *
75120      * @param nodes The NodeArray.
75121      */
75122     function extractSingleNode(nodes) {
75123         ts.Debug.assert(nodes.length <= 1, "Too many nodes written to output.");
75124         return ts.singleOrUndefined(nodes);
75125     }
75126 })(ts || (ts = {}));
75127 /* @internal */
75128 var ts;
75129 (function (ts) {
75130     function reduceNode(node, f, initial) {
75131         return node ? f(initial, node) : initial;
75132     }
75133     function reduceNodeArray(nodes, f, initial) {
75134         return nodes ? f(initial, nodes) : initial;
75135     }
75136     /**
75137      * Similar to `reduceLeft`, performs a reduction against each child of a node.
75138      * NOTE: Unlike `forEachChild`, this does *not* visit every node.
75139      *
75140      * @param node The node containing the children to reduce.
75141      * @param initial The initial value to supply to the reduction.
75142      * @param f The callback function
75143      */
75144     function reduceEachChild(node, initial, cbNode, cbNodeArray) {
75145         if (node === undefined) {
75146             return initial;
75147         }
75148         var reduceNodes = cbNodeArray ? reduceNodeArray : ts.reduceLeft;
75149         var cbNodes = cbNodeArray || cbNode;
75150         var kind = node.kind;
75151         // No need to visit nodes with no children.
75152         if ((kind > 0 /* FirstToken */ && kind <= 152 /* LastToken */)) {
75153             return initial;
75154         }
75155         // We do not yet support types.
75156         if ((kind >= 168 /* TypePredicate */ && kind <= 187 /* LiteralType */)) {
75157             return initial;
75158         }
75159         var result = initial;
75160         switch (node.kind) {
75161             // Leaf nodes
75162             case 222 /* SemicolonClassElement */:
75163             case 224 /* EmptyStatement */:
75164             case 215 /* OmittedExpression */:
75165             case 241 /* DebuggerStatement */:
75166             case 325 /* NotEmittedStatement */:
75167                 // No need to visit nodes with no children.
75168                 break;
75169             // Names
75170             case 153 /* QualifiedName */:
75171                 result = reduceNode(node.left, cbNode, result);
75172                 result = reduceNode(node.right, cbNode, result);
75173                 break;
75174             case 154 /* ComputedPropertyName */:
75175                 result = reduceNode(node.expression, cbNode, result);
75176                 break;
75177             // Signature elements
75178             case 156 /* Parameter */:
75179                 result = reduceNodes(node.decorators, cbNodes, result);
75180                 result = reduceNodes(node.modifiers, cbNodes, result);
75181                 result = reduceNode(node.name, cbNode, result);
75182                 result = reduceNode(node.type, cbNode, result);
75183                 result = reduceNode(node.initializer, cbNode, result);
75184                 break;
75185             case 157 /* Decorator */:
75186                 result = reduceNode(node.expression, cbNode, result);
75187                 break;
75188             // Type member
75189             case 158 /* PropertySignature */:
75190                 result = reduceNodes(node.modifiers, cbNodes, result);
75191                 result = reduceNode(node.name, cbNode, result);
75192                 result = reduceNode(node.questionToken, cbNode, result);
75193                 result = reduceNode(node.type, cbNode, result);
75194                 result = reduceNode(node.initializer, cbNode, result);
75195                 break;
75196             case 159 /* PropertyDeclaration */:
75197                 result = reduceNodes(node.decorators, cbNodes, result);
75198                 result = reduceNodes(node.modifiers, cbNodes, result);
75199                 result = reduceNode(node.name, cbNode, result);
75200                 result = reduceNode(node.type, cbNode, result);
75201                 result = reduceNode(node.initializer, cbNode, result);
75202                 break;
75203             case 161 /* MethodDeclaration */:
75204                 result = reduceNodes(node.decorators, cbNodes, result);
75205                 result = reduceNodes(node.modifiers, cbNodes, result);
75206                 result = reduceNode(node.name, cbNode, result);
75207                 result = reduceNodes(node.typeParameters, cbNodes, result);
75208                 result = reduceNodes(node.parameters, cbNodes, result);
75209                 result = reduceNode(node.type, cbNode, result);
75210                 result = reduceNode(node.body, cbNode, result);
75211                 break;
75212             case 162 /* Constructor */:
75213                 result = reduceNodes(node.modifiers, cbNodes, result);
75214                 result = reduceNodes(node.parameters, cbNodes, result);
75215                 result = reduceNode(node.body, cbNode, result);
75216                 break;
75217             case 163 /* GetAccessor */:
75218                 result = reduceNodes(node.decorators, cbNodes, result);
75219                 result = reduceNodes(node.modifiers, cbNodes, result);
75220                 result = reduceNode(node.name, cbNode, result);
75221                 result = reduceNodes(node.parameters, cbNodes, result);
75222                 result = reduceNode(node.type, cbNode, result);
75223                 result = reduceNode(node.body, cbNode, result);
75224                 break;
75225             case 164 /* SetAccessor */:
75226                 result = reduceNodes(node.decorators, cbNodes, result);
75227                 result = reduceNodes(node.modifiers, cbNodes, result);
75228                 result = reduceNode(node.name, cbNode, result);
75229                 result = reduceNodes(node.parameters, cbNodes, result);
75230                 result = reduceNode(node.body, cbNode, result);
75231                 break;
75232             // Binding patterns
75233             case 189 /* ObjectBindingPattern */:
75234             case 190 /* ArrayBindingPattern */:
75235                 result = reduceNodes(node.elements, cbNodes, result);
75236                 break;
75237             case 191 /* BindingElement */:
75238                 result = reduceNode(node.propertyName, cbNode, result);
75239                 result = reduceNode(node.name, cbNode, result);
75240                 result = reduceNode(node.initializer, cbNode, result);
75241                 break;
75242             // Expression
75243             case 192 /* ArrayLiteralExpression */:
75244                 result = reduceNodes(node.elements, cbNodes, result);
75245                 break;
75246             case 193 /* ObjectLiteralExpression */:
75247                 result = reduceNodes(node.properties, cbNodes, result);
75248                 break;
75249             case 194 /* PropertyAccessExpression */:
75250                 result = reduceNode(node.expression, cbNode, result);
75251                 result = reduceNode(node.name, cbNode, result);
75252                 break;
75253             case 195 /* ElementAccessExpression */:
75254                 result = reduceNode(node.expression, cbNode, result);
75255                 result = reduceNode(node.argumentExpression, cbNode, result);
75256                 break;
75257             case 196 /* CallExpression */:
75258                 result = reduceNode(node.expression, cbNode, result);
75259                 result = reduceNodes(node.typeArguments, cbNodes, result);
75260                 result = reduceNodes(node.arguments, cbNodes, result);
75261                 break;
75262             case 197 /* NewExpression */:
75263                 result = reduceNode(node.expression, cbNode, result);
75264                 result = reduceNodes(node.typeArguments, cbNodes, result);
75265                 result = reduceNodes(node.arguments, cbNodes, result);
75266                 break;
75267             case 198 /* TaggedTemplateExpression */:
75268                 result = reduceNode(node.tag, cbNode, result);
75269                 result = reduceNodes(node.typeArguments, cbNodes, result);
75270                 result = reduceNode(node.template, cbNode, result);
75271                 break;
75272             case 199 /* TypeAssertionExpression */:
75273                 result = reduceNode(node.type, cbNode, result);
75274                 result = reduceNode(node.expression, cbNode, result);
75275                 break;
75276             case 201 /* FunctionExpression */:
75277                 result = reduceNodes(node.modifiers, cbNodes, result);
75278                 result = reduceNode(node.name, cbNode, result);
75279                 result = reduceNodes(node.typeParameters, cbNodes, result);
75280                 result = reduceNodes(node.parameters, cbNodes, result);
75281                 result = reduceNode(node.type, cbNode, result);
75282                 result = reduceNode(node.body, cbNode, result);
75283                 break;
75284             case 202 /* ArrowFunction */:
75285                 result = reduceNodes(node.modifiers, cbNodes, result);
75286                 result = reduceNodes(node.typeParameters, cbNodes, result);
75287                 result = reduceNodes(node.parameters, cbNodes, result);
75288                 result = reduceNode(node.type, cbNode, result);
75289                 result = reduceNode(node.body, cbNode, result);
75290                 break;
75291             case 200 /* ParenthesizedExpression */:
75292             case 203 /* DeleteExpression */:
75293             case 204 /* TypeOfExpression */:
75294             case 205 /* VoidExpression */:
75295             case 206 /* AwaitExpression */:
75296             case 212 /* YieldExpression */:
75297             case 213 /* SpreadElement */:
75298             case 218 /* NonNullExpression */:
75299                 result = reduceNode(node.expression, cbNode, result);
75300                 break;
75301             case 207 /* PrefixUnaryExpression */:
75302             case 208 /* PostfixUnaryExpression */:
75303                 result = reduceNode(node.operand, cbNode, result);
75304                 break;
75305             case 209 /* BinaryExpression */:
75306                 result = reduceNode(node.left, cbNode, result);
75307                 result = reduceNode(node.right, cbNode, result);
75308                 break;
75309             case 210 /* ConditionalExpression */:
75310                 result = reduceNode(node.condition, cbNode, result);
75311                 result = reduceNode(node.whenTrue, cbNode, result);
75312                 result = reduceNode(node.whenFalse, cbNode, result);
75313                 break;
75314             case 211 /* TemplateExpression */:
75315                 result = reduceNode(node.head, cbNode, result);
75316                 result = reduceNodes(node.templateSpans, cbNodes, result);
75317                 break;
75318             case 214 /* ClassExpression */:
75319                 result = reduceNodes(node.modifiers, cbNodes, result);
75320                 result = reduceNode(node.name, cbNode, result);
75321                 result = reduceNodes(node.typeParameters, cbNodes, result);
75322                 result = reduceNodes(node.heritageClauses, cbNodes, result);
75323                 result = reduceNodes(node.members, cbNodes, result);
75324                 break;
75325             case 216 /* ExpressionWithTypeArguments */:
75326                 result = reduceNode(node.expression, cbNode, result);
75327                 result = reduceNodes(node.typeArguments, cbNodes, result);
75328                 break;
75329             case 217 /* AsExpression */:
75330                 result = reduceNode(node.expression, cbNode, result);
75331                 result = reduceNode(node.type, cbNode, result);
75332                 break;
75333             // Misc
75334             case 221 /* TemplateSpan */:
75335                 result = reduceNode(node.expression, cbNode, result);
75336                 result = reduceNode(node.literal, cbNode, result);
75337                 break;
75338             // Element
75339             case 223 /* Block */:
75340                 result = reduceNodes(node.statements, cbNodes, result);
75341                 break;
75342             case 225 /* VariableStatement */:
75343                 result = reduceNodes(node.modifiers, cbNodes, result);
75344                 result = reduceNode(node.declarationList, cbNode, result);
75345                 break;
75346             case 226 /* ExpressionStatement */:
75347                 result = reduceNode(node.expression, cbNode, result);
75348                 break;
75349             case 227 /* IfStatement */:
75350                 result = reduceNode(node.expression, cbNode, result);
75351                 result = reduceNode(node.thenStatement, cbNode, result);
75352                 result = reduceNode(node.elseStatement, cbNode, result);
75353                 break;
75354             case 228 /* DoStatement */:
75355                 result = reduceNode(node.statement, cbNode, result);
75356                 result = reduceNode(node.expression, cbNode, result);
75357                 break;
75358             case 229 /* WhileStatement */:
75359             case 236 /* WithStatement */:
75360                 result = reduceNode(node.expression, cbNode, result);
75361                 result = reduceNode(node.statement, cbNode, result);
75362                 break;
75363             case 230 /* ForStatement */:
75364                 result = reduceNode(node.initializer, cbNode, result);
75365                 result = reduceNode(node.condition, cbNode, result);
75366                 result = reduceNode(node.incrementor, cbNode, result);
75367                 result = reduceNode(node.statement, cbNode, result);
75368                 break;
75369             case 231 /* ForInStatement */:
75370             case 232 /* ForOfStatement */:
75371                 result = reduceNode(node.initializer, cbNode, result);
75372                 result = reduceNode(node.expression, cbNode, result);
75373                 result = reduceNode(node.statement, cbNode, result);
75374                 break;
75375             case 235 /* ReturnStatement */:
75376             case 239 /* ThrowStatement */:
75377                 result = reduceNode(node.expression, cbNode, result);
75378                 break;
75379             case 237 /* SwitchStatement */:
75380                 result = reduceNode(node.expression, cbNode, result);
75381                 result = reduceNode(node.caseBlock, cbNode, result);
75382                 break;
75383             case 238 /* LabeledStatement */:
75384                 result = reduceNode(node.label, cbNode, result);
75385                 result = reduceNode(node.statement, cbNode, result);
75386                 break;
75387             case 240 /* TryStatement */:
75388                 result = reduceNode(node.tryBlock, cbNode, result);
75389                 result = reduceNode(node.catchClause, cbNode, result);
75390                 result = reduceNode(node.finallyBlock, cbNode, result);
75391                 break;
75392             case 242 /* VariableDeclaration */:
75393                 result = reduceNode(node.name, cbNode, result);
75394                 result = reduceNode(node.type, cbNode, result);
75395                 result = reduceNode(node.initializer, cbNode, result);
75396                 break;
75397             case 243 /* VariableDeclarationList */:
75398                 result = reduceNodes(node.declarations, cbNodes, result);
75399                 break;
75400             case 244 /* FunctionDeclaration */:
75401                 result = reduceNodes(node.decorators, cbNodes, result);
75402                 result = reduceNodes(node.modifiers, cbNodes, result);
75403                 result = reduceNode(node.name, cbNode, result);
75404                 result = reduceNodes(node.typeParameters, cbNodes, result);
75405                 result = reduceNodes(node.parameters, cbNodes, result);
75406                 result = reduceNode(node.type, cbNode, result);
75407                 result = reduceNode(node.body, cbNode, result);
75408                 break;
75409             case 245 /* ClassDeclaration */:
75410                 result = reduceNodes(node.decorators, cbNodes, result);
75411                 result = reduceNodes(node.modifiers, cbNodes, result);
75412                 result = reduceNode(node.name, cbNode, result);
75413                 result = reduceNodes(node.typeParameters, cbNodes, result);
75414                 result = reduceNodes(node.heritageClauses, cbNodes, result);
75415                 result = reduceNodes(node.members, cbNodes, result);
75416                 break;
75417             case 248 /* EnumDeclaration */:
75418                 result = reduceNodes(node.decorators, cbNodes, result);
75419                 result = reduceNodes(node.modifiers, cbNodes, result);
75420                 result = reduceNode(node.name, cbNode, result);
75421                 result = reduceNodes(node.members, cbNodes, result);
75422                 break;
75423             case 249 /* ModuleDeclaration */:
75424                 result = reduceNodes(node.decorators, cbNodes, result);
75425                 result = reduceNodes(node.modifiers, cbNodes, result);
75426                 result = reduceNode(node.name, cbNode, result);
75427                 result = reduceNode(node.body, cbNode, result);
75428                 break;
75429             case 250 /* ModuleBlock */:
75430                 result = reduceNodes(node.statements, cbNodes, result);
75431                 break;
75432             case 251 /* CaseBlock */:
75433                 result = reduceNodes(node.clauses, cbNodes, result);
75434                 break;
75435             case 253 /* ImportEqualsDeclaration */:
75436                 result = reduceNodes(node.decorators, cbNodes, result);
75437                 result = reduceNodes(node.modifiers, cbNodes, result);
75438                 result = reduceNode(node.name, cbNode, result);
75439                 result = reduceNode(node.moduleReference, cbNode, result);
75440                 break;
75441             case 254 /* ImportDeclaration */:
75442                 result = reduceNodes(node.decorators, cbNodes, result);
75443                 result = reduceNodes(node.modifiers, cbNodes, result);
75444                 result = reduceNode(node.importClause, cbNode, result);
75445                 result = reduceNode(node.moduleSpecifier, cbNode, result);
75446                 break;
75447             case 255 /* ImportClause */:
75448                 result = reduceNode(node.name, cbNode, result);
75449                 result = reduceNode(node.namedBindings, cbNode, result);
75450                 break;
75451             case 256 /* NamespaceImport */:
75452                 result = reduceNode(node.name, cbNode, result);
75453                 break;
75454             case 262 /* NamespaceExport */:
75455                 result = reduceNode(node.name, cbNode, result);
75456                 break;
75457             case 257 /* NamedImports */:
75458             case 261 /* NamedExports */:
75459                 result = reduceNodes(node.elements, cbNodes, result);
75460                 break;
75461             case 258 /* ImportSpecifier */:
75462             case 263 /* ExportSpecifier */:
75463                 result = reduceNode(node.propertyName, cbNode, result);
75464                 result = reduceNode(node.name, cbNode, result);
75465                 break;
75466             case 259 /* ExportAssignment */:
75467                 result = ts.reduceLeft(node.decorators, cbNode, result);
75468                 result = ts.reduceLeft(node.modifiers, cbNode, result);
75469                 result = reduceNode(node.expression, cbNode, result);
75470                 break;
75471             case 260 /* ExportDeclaration */:
75472                 result = ts.reduceLeft(node.decorators, cbNode, result);
75473                 result = ts.reduceLeft(node.modifiers, cbNode, result);
75474                 result = reduceNode(node.exportClause, cbNode, result);
75475                 result = reduceNode(node.moduleSpecifier, cbNode, result);
75476                 break;
75477             // Module references
75478             case 265 /* ExternalModuleReference */:
75479                 result = reduceNode(node.expression, cbNode, result);
75480                 break;
75481             // JSX
75482             case 266 /* JsxElement */:
75483                 result = reduceNode(node.openingElement, cbNode, result);
75484                 result = ts.reduceLeft(node.children, cbNode, result);
75485                 result = reduceNode(node.closingElement, cbNode, result);
75486                 break;
75487             case 270 /* JsxFragment */:
75488                 result = reduceNode(node.openingFragment, cbNode, result);
75489                 result = ts.reduceLeft(node.children, cbNode, result);
75490                 result = reduceNode(node.closingFragment, cbNode, result);
75491                 break;
75492             case 267 /* JsxSelfClosingElement */:
75493             case 268 /* JsxOpeningElement */:
75494                 result = reduceNode(node.tagName, cbNode, result);
75495                 result = reduceNodes(node.typeArguments, cbNode, result);
75496                 result = reduceNode(node.attributes, cbNode, result);
75497                 break;
75498             case 274 /* JsxAttributes */:
75499                 result = reduceNodes(node.properties, cbNodes, result);
75500                 break;
75501             case 269 /* JsxClosingElement */:
75502                 result = reduceNode(node.tagName, cbNode, result);
75503                 break;
75504             case 273 /* JsxAttribute */:
75505                 result = reduceNode(node.name, cbNode, result);
75506                 result = reduceNode(node.initializer, cbNode, result);
75507                 break;
75508             case 275 /* JsxSpreadAttribute */:
75509                 result = reduceNode(node.expression, cbNode, result);
75510                 break;
75511             case 276 /* JsxExpression */:
75512                 result = reduceNode(node.expression, cbNode, result);
75513                 break;
75514             // Clauses
75515             case 277 /* CaseClause */:
75516                 result = reduceNode(node.expression, cbNode, result);
75517             // falls through
75518             case 278 /* DefaultClause */:
75519                 result = reduceNodes(node.statements, cbNodes, result);
75520                 break;
75521             case 279 /* HeritageClause */:
75522                 result = reduceNodes(node.types, cbNodes, result);
75523                 break;
75524             case 280 /* CatchClause */:
75525                 result = reduceNode(node.variableDeclaration, cbNode, result);
75526                 result = reduceNode(node.block, cbNode, result);
75527                 break;
75528             // Property assignments
75529             case 281 /* PropertyAssignment */:
75530                 result = reduceNode(node.name, cbNode, result);
75531                 result = reduceNode(node.initializer, cbNode, result);
75532                 break;
75533             case 282 /* ShorthandPropertyAssignment */:
75534                 result = reduceNode(node.name, cbNode, result);
75535                 result = reduceNode(node.objectAssignmentInitializer, cbNode, result);
75536                 break;
75537             case 283 /* SpreadAssignment */:
75538                 result = reduceNode(node.expression, cbNode, result);
75539                 break;
75540             // Enum
75541             case 284 /* EnumMember */:
75542                 result = reduceNode(node.name, cbNode, result);
75543                 result = reduceNode(node.initializer, cbNode, result);
75544                 break;
75545             // Top-level nodes
75546             case 290 /* SourceFile */:
75547                 result = reduceNodes(node.statements, cbNodes, result);
75548                 break;
75549             // Transformation nodes
75550             case 326 /* PartiallyEmittedExpression */:
75551                 result = reduceNode(node.expression, cbNode, result);
75552                 break;
75553             case 327 /* CommaListExpression */:
75554                 result = reduceNodes(node.elements, cbNodes, result);
75555                 break;
75556             default:
75557                 break;
75558         }
75559         return result;
75560     }
75561     ts.reduceEachChild = reduceEachChild;
75562     function findSpanEnd(array, test, start) {
75563         var i = start;
75564         while (i < array.length && test(array[i])) {
75565             i++;
75566         }
75567         return i;
75568     }
75569     function mergeLexicalEnvironment(statements, declarations) {
75570         if (!ts.some(declarations)) {
75571             return statements;
75572         }
75573         // When we merge new lexical statements into an existing statement list, we merge them in the following manner:
75574         //
75575         // Given:
75576         //
75577         // | Left                               | Right                               |
75578         // |------------------------------------|-------------------------------------|
75579         // | [standard prologues (left)]        | [standard prologues (right)]        |
75580         // | [hoisted functions (left)]         | [hoisted functions (right)]         |
75581         // | [hoisted variables (left)]         | [hoisted variables (right)]         |
75582         // | [lexical init statements (left)]   | [lexical init statements (right)]   |
75583         // | [other statements (left)]          |                                     |
75584         //
75585         // The resulting statement list will be:
75586         //
75587         // | Result                              |
75588         // |-------------------------------------|
75589         // | [standard prologues (right)]        |
75590         // | [standard prologues (left)]         |
75591         // | [hoisted functions (right)]         |
75592         // | [hoisted functions (left)]          |
75593         // | [hoisted variables (right)]         |
75594         // | [hoisted variables (left)]          |
75595         // | [lexical init statements (right)]   |
75596         // | [lexical init statements (left)]    |
75597         // | [other statements (left)]           |
75598         //
75599         // NOTE: It is expected that new lexical init statements must be evaluated before existing lexical init statements,
75600         // as the prior transformation may depend on the evaluation of the lexical init statements to be in the correct state.
75601         // find standard prologues on left in the following order: standard directives, hoisted functions, hoisted variables, other custom
75602         var leftStandardPrologueEnd = findSpanEnd(statements, ts.isPrologueDirective, 0);
75603         var leftHoistedFunctionsEnd = findSpanEnd(statements, ts.isHoistedFunction, leftStandardPrologueEnd);
75604         var leftHoistedVariablesEnd = findSpanEnd(statements, ts.isHoistedVariableStatement, leftHoistedFunctionsEnd);
75605         // find standard prologues on right in the following order: standard directives, hoisted functions, hoisted variables, other custom
75606         var rightStandardPrologueEnd = findSpanEnd(declarations, ts.isPrologueDirective, 0);
75607         var rightHoistedFunctionsEnd = findSpanEnd(declarations, ts.isHoistedFunction, rightStandardPrologueEnd);
75608         var rightHoistedVariablesEnd = findSpanEnd(declarations, ts.isHoistedVariableStatement, rightHoistedFunctionsEnd);
75609         var rightCustomPrologueEnd = findSpanEnd(declarations, ts.isCustomPrologue, rightHoistedVariablesEnd);
75610         ts.Debug.assert(rightCustomPrologueEnd === declarations.length, "Expected declarations to be valid standard or custom prologues");
75611         // splice prologues from the right into the left. We do this in reverse order
75612         // so that we don't need to recompute the index on the left when we insert items.
75613         var left = ts.isNodeArray(statements) ? statements.slice() : statements;
75614         // splice other custom prologues from right into left
75615         if (rightCustomPrologueEnd > rightHoistedVariablesEnd) {
75616             left.splice.apply(left, __spreadArrays([leftHoistedVariablesEnd, 0], declarations.slice(rightHoistedVariablesEnd, rightCustomPrologueEnd)));
75617         }
75618         // splice hoisted variables from right into left
75619         if (rightHoistedVariablesEnd > rightHoistedFunctionsEnd) {
75620             left.splice.apply(left, __spreadArrays([leftHoistedFunctionsEnd, 0], declarations.slice(rightHoistedFunctionsEnd, rightHoistedVariablesEnd)));
75621         }
75622         // splice hoisted functions from right into left
75623         if (rightHoistedFunctionsEnd > rightStandardPrologueEnd) {
75624             left.splice.apply(left, __spreadArrays([leftStandardPrologueEnd, 0], declarations.slice(rightStandardPrologueEnd, rightHoistedFunctionsEnd)));
75625         }
75626         // splice standard prologues from right into left (that are not already in left)
75627         if (rightStandardPrologueEnd > 0) {
75628             if (leftStandardPrologueEnd === 0) {
75629                 left.splice.apply(left, __spreadArrays([0, 0], declarations.slice(0, rightStandardPrologueEnd)));
75630             }
75631             else {
75632                 var leftPrologues = ts.createMap();
75633                 for (var i = 0; i < leftStandardPrologueEnd; i++) {
75634                     var leftPrologue = statements[i];
75635                     leftPrologues.set(leftPrologue.expression.text, true);
75636                 }
75637                 for (var i = rightStandardPrologueEnd - 1; i >= 0; i--) {
75638                     var rightPrologue = declarations[i];
75639                     if (!leftPrologues.has(rightPrologue.expression.text)) {
75640                         left.unshift(rightPrologue);
75641                     }
75642                 }
75643             }
75644         }
75645         if (ts.isNodeArray(statements)) {
75646             return ts.setTextRange(ts.createNodeArray(left, statements.hasTrailingComma), statements);
75647         }
75648         return statements;
75649     }
75650     ts.mergeLexicalEnvironment = mergeLexicalEnvironment;
75651     /**
75652      * Lifts a NodeArray containing only Statement nodes to a block.
75653      *
75654      * @param nodes The NodeArray.
75655      */
75656     function liftToBlock(nodes) {
75657         ts.Debug.assert(ts.every(nodes, ts.isStatement), "Cannot lift nodes to a Block.");
75658         return ts.singleOrUndefined(nodes) || ts.createBlock(nodes);
75659     }
75660     ts.liftToBlock = liftToBlock;
75661     /**
75662      * Aggregates the TransformFlags for a Node and its subtree.
75663      */
75664     function aggregateTransformFlags(node) {
75665         aggregateTransformFlagsForNode(node);
75666         return node;
75667     }
75668     ts.aggregateTransformFlags = aggregateTransformFlags;
75669     /**
75670      * Aggregates the TransformFlags for a Node and its subtree. The flags for the subtree are
75671      * computed first, then the transform flags for the current node are computed from the subtree
75672      * flags and the state of the current node. Finally, the transform flags of the node are
75673      * returned, excluding any flags that should not be included in its parent node's subtree
75674      * flags.
75675      */
75676     function aggregateTransformFlagsForNode(node) {
75677         if (node === undefined) {
75678             return 0 /* None */;
75679         }
75680         if (node.transformFlags & 536870912 /* HasComputedFlags */) {
75681             return node.transformFlags & ~ts.getTransformFlagsSubtreeExclusions(node.kind);
75682         }
75683         var subtreeFlags = aggregateTransformFlagsForSubtree(node);
75684         return ts.computeTransformFlagsForNode(node, subtreeFlags);
75685     }
75686     function aggregateTransformFlagsForNodeArray(nodes) {
75687         if (nodes === undefined) {
75688             return 0 /* None */;
75689         }
75690         var subtreeFlags = 0 /* None */;
75691         var nodeArrayFlags = 0 /* None */;
75692         for (var _i = 0, nodes_3 = nodes; _i < nodes_3.length; _i++) {
75693             var node = nodes_3[_i];
75694             subtreeFlags |= aggregateTransformFlagsForNode(node);
75695             nodeArrayFlags |= node.transformFlags & ~536870912 /* HasComputedFlags */;
75696         }
75697         nodes.transformFlags = nodeArrayFlags | 536870912 /* HasComputedFlags */;
75698         return subtreeFlags;
75699     }
75700     /**
75701      * Aggregates the transform flags for the subtree of a node.
75702      */
75703     function aggregateTransformFlagsForSubtree(node) {
75704         // We do not transform ambient declarations or types, so there is no need to
75705         // recursively aggregate transform flags.
75706         if (ts.hasModifier(node, 2 /* Ambient */) || (ts.isTypeNode(node) && node.kind !== 216 /* ExpressionWithTypeArguments */)) {
75707             return 0 /* None */;
75708         }
75709         // Aggregate the transform flags of each child.
75710         return reduceEachChild(node, 0 /* None */, aggregateTransformFlagsForChildNode, aggregateTransformFlagsForChildNodes);
75711     }
75712     /**
75713      * Aggregates the TransformFlags of a child node with the TransformFlags of its
75714      * siblings.
75715      */
75716     function aggregateTransformFlagsForChildNode(transformFlags, node) {
75717         return transformFlags | aggregateTransformFlagsForNode(node);
75718     }
75719     function aggregateTransformFlagsForChildNodes(transformFlags, nodes) {
75720         return transformFlags | aggregateTransformFlagsForNodeArray(nodes);
75721     }
75722 })(ts || (ts = {}));
75723 /* @internal */
75724 var ts;
75725 (function (ts) {
75726     function createSourceMapGenerator(host, file, sourceRoot, sourcesDirectoryPath, generatorOptions) {
75727         var _a = generatorOptions.extendedDiagnostics
75728             ? ts.performance.createTimer("Source Map", "beforeSourcemap", "afterSourcemap")
75729             : ts.performance.nullTimer, enter = _a.enter, exit = _a.exit;
75730         // Current source map file and its index in the sources list
75731         var rawSources = [];
75732         var sources = [];
75733         var sourceToSourceIndexMap = ts.createMap();
75734         var sourcesContent;
75735         var names = [];
75736         var nameToNameIndexMap;
75737         var mappings = "";
75738         // Last recorded and encoded mappings
75739         var lastGeneratedLine = 0;
75740         var lastGeneratedCharacter = 0;
75741         var lastSourceIndex = 0;
75742         var lastSourceLine = 0;
75743         var lastSourceCharacter = 0;
75744         var lastNameIndex = 0;
75745         var hasLast = false;
75746         var pendingGeneratedLine = 0;
75747         var pendingGeneratedCharacter = 0;
75748         var pendingSourceIndex = 0;
75749         var pendingSourceLine = 0;
75750         var pendingSourceCharacter = 0;
75751         var pendingNameIndex = 0;
75752         var hasPending = false;
75753         var hasPendingSource = false;
75754         var hasPendingName = false;
75755         return {
75756             getSources: function () { return rawSources; },
75757             addSource: addSource,
75758             setSourceContent: setSourceContent,
75759             addName: addName,
75760             addMapping: addMapping,
75761             appendSourceMap: appendSourceMap,
75762             toJSON: toJSON,
75763             toString: function () { return JSON.stringify(toJSON()); }
75764         };
75765         function addSource(fileName) {
75766             enter();
75767             var source = ts.getRelativePathToDirectoryOrUrl(sourcesDirectoryPath, fileName, host.getCurrentDirectory(), host.getCanonicalFileName, 
75768             /*isAbsolutePathAnUrl*/ true);
75769             var sourceIndex = sourceToSourceIndexMap.get(source);
75770             if (sourceIndex === undefined) {
75771                 sourceIndex = sources.length;
75772                 sources.push(source);
75773                 rawSources.push(fileName);
75774                 sourceToSourceIndexMap.set(source, sourceIndex);
75775             }
75776             exit();
75777             return sourceIndex;
75778         }
75779         /* eslint-disable boolean-trivia, no-null/no-null */
75780         function setSourceContent(sourceIndex, content) {
75781             enter();
75782             if (content !== null) {
75783                 if (!sourcesContent)
75784                     sourcesContent = [];
75785                 while (sourcesContent.length < sourceIndex) {
75786                     sourcesContent.push(null);
75787                 }
75788                 sourcesContent[sourceIndex] = content;
75789             }
75790             exit();
75791         }
75792         /* eslint-enable boolean-trivia, no-null/no-null */
75793         function addName(name) {
75794             enter();
75795             if (!nameToNameIndexMap)
75796                 nameToNameIndexMap = ts.createMap();
75797             var nameIndex = nameToNameIndexMap.get(name);
75798             if (nameIndex === undefined) {
75799                 nameIndex = names.length;
75800                 names.push(name);
75801                 nameToNameIndexMap.set(name, nameIndex);
75802             }
75803             exit();
75804             return nameIndex;
75805         }
75806         function isNewGeneratedPosition(generatedLine, generatedCharacter) {
75807             return !hasPending
75808                 || pendingGeneratedLine !== generatedLine
75809                 || pendingGeneratedCharacter !== generatedCharacter;
75810         }
75811         function isBacktrackingSourcePosition(sourceIndex, sourceLine, sourceCharacter) {
75812             return sourceIndex !== undefined
75813                 && sourceLine !== undefined
75814                 && sourceCharacter !== undefined
75815                 && pendingSourceIndex === sourceIndex
75816                 && (pendingSourceLine > sourceLine
75817                     || pendingSourceLine === sourceLine && pendingSourceCharacter > sourceCharacter);
75818         }
75819         function addMapping(generatedLine, generatedCharacter, sourceIndex, sourceLine, sourceCharacter, nameIndex) {
75820             ts.Debug.assert(generatedLine >= pendingGeneratedLine, "generatedLine cannot backtrack");
75821             ts.Debug.assert(generatedCharacter >= 0, "generatedCharacter cannot be negative");
75822             ts.Debug.assert(sourceIndex === undefined || sourceIndex >= 0, "sourceIndex cannot be negative");
75823             ts.Debug.assert(sourceLine === undefined || sourceLine >= 0, "sourceLine cannot be negative");
75824             ts.Debug.assert(sourceCharacter === undefined || sourceCharacter >= 0, "sourceCharacter cannot be negative");
75825             enter();
75826             // If this location wasn't recorded or the location in source is going backwards, record the mapping
75827             if (isNewGeneratedPosition(generatedLine, generatedCharacter) ||
75828                 isBacktrackingSourcePosition(sourceIndex, sourceLine, sourceCharacter)) {
75829                 commitPendingMapping();
75830                 pendingGeneratedLine = generatedLine;
75831                 pendingGeneratedCharacter = generatedCharacter;
75832                 hasPendingSource = false;
75833                 hasPendingName = false;
75834                 hasPending = true;
75835             }
75836             if (sourceIndex !== undefined && sourceLine !== undefined && sourceCharacter !== undefined) {
75837                 pendingSourceIndex = sourceIndex;
75838                 pendingSourceLine = sourceLine;
75839                 pendingSourceCharacter = sourceCharacter;
75840                 hasPendingSource = true;
75841                 if (nameIndex !== undefined) {
75842                     pendingNameIndex = nameIndex;
75843                     hasPendingName = true;
75844                 }
75845             }
75846             exit();
75847         }
75848         function appendSourceMap(generatedLine, generatedCharacter, map, sourceMapPath, start, end) {
75849             ts.Debug.assert(generatedLine >= pendingGeneratedLine, "generatedLine cannot backtrack");
75850             ts.Debug.assert(generatedCharacter >= 0, "generatedCharacter cannot be negative");
75851             enter();
75852             // First, decode the old component sourcemap
75853             var sourceIndexToNewSourceIndexMap = [];
75854             var nameIndexToNewNameIndexMap;
75855             var mappingIterator = decodeMappings(map.mappings);
75856             for (var iterResult = mappingIterator.next(); !iterResult.done; iterResult = mappingIterator.next()) {
75857                 var raw = iterResult.value;
75858                 if (end && (raw.generatedLine > end.line ||
75859                     (raw.generatedLine === end.line && raw.generatedCharacter > end.character))) {
75860                     break;
75861                 }
75862                 if (start && (raw.generatedLine < start.line ||
75863                     (start.line === raw.generatedLine && raw.generatedCharacter < start.character))) {
75864                     continue;
75865                 }
75866                 // Then reencode all the updated mappings into the overall map
75867                 var newSourceIndex = void 0;
75868                 var newSourceLine = void 0;
75869                 var newSourceCharacter = void 0;
75870                 var newNameIndex = void 0;
75871                 if (raw.sourceIndex !== undefined) {
75872                     newSourceIndex = sourceIndexToNewSourceIndexMap[raw.sourceIndex];
75873                     if (newSourceIndex === undefined) {
75874                         // Apply offsets to each position and fixup source entries
75875                         var rawPath = map.sources[raw.sourceIndex];
75876                         var relativePath = map.sourceRoot ? ts.combinePaths(map.sourceRoot, rawPath) : rawPath;
75877                         var combinedPath = ts.combinePaths(ts.getDirectoryPath(sourceMapPath), relativePath);
75878                         sourceIndexToNewSourceIndexMap[raw.sourceIndex] = newSourceIndex = addSource(combinedPath);
75879                         if (map.sourcesContent && typeof map.sourcesContent[raw.sourceIndex] === "string") {
75880                             setSourceContent(newSourceIndex, map.sourcesContent[raw.sourceIndex]);
75881                         }
75882                     }
75883                     newSourceLine = raw.sourceLine;
75884                     newSourceCharacter = raw.sourceCharacter;
75885                     if (map.names && raw.nameIndex !== undefined) {
75886                         if (!nameIndexToNewNameIndexMap)
75887                             nameIndexToNewNameIndexMap = [];
75888                         newNameIndex = nameIndexToNewNameIndexMap[raw.nameIndex];
75889                         if (newNameIndex === undefined) {
75890                             nameIndexToNewNameIndexMap[raw.nameIndex] = newNameIndex = addName(map.names[raw.nameIndex]);
75891                         }
75892                     }
75893                 }
75894                 var rawGeneratedLine = raw.generatedLine - (start ? start.line : 0);
75895                 var newGeneratedLine = rawGeneratedLine + generatedLine;
75896                 var rawGeneratedCharacter = start && start.line === raw.generatedLine ? raw.generatedCharacter - start.character : raw.generatedCharacter;
75897                 var newGeneratedCharacter = rawGeneratedLine === 0 ? rawGeneratedCharacter + generatedCharacter : rawGeneratedCharacter;
75898                 addMapping(newGeneratedLine, newGeneratedCharacter, newSourceIndex, newSourceLine, newSourceCharacter, newNameIndex);
75899             }
75900             exit();
75901         }
75902         function shouldCommitMapping() {
75903             return !hasLast
75904                 || lastGeneratedLine !== pendingGeneratedLine
75905                 || lastGeneratedCharacter !== pendingGeneratedCharacter
75906                 || lastSourceIndex !== pendingSourceIndex
75907                 || lastSourceLine !== pendingSourceLine
75908                 || lastSourceCharacter !== pendingSourceCharacter
75909                 || lastNameIndex !== pendingNameIndex;
75910         }
75911         function commitPendingMapping() {
75912             if (!hasPending || !shouldCommitMapping()) {
75913                 return;
75914             }
75915             enter();
75916             // Line/Comma delimiters
75917             if (lastGeneratedLine < pendingGeneratedLine) {
75918                 // Emit line delimiters
75919                 do {
75920                     mappings += ";";
75921                     lastGeneratedLine++;
75922                     lastGeneratedCharacter = 0;
75923                 } while (lastGeneratedLine < pendingGeneratedLine);
75924             }
75925             else {
75926                 ts.Debug.assertEqual(lastGeneratedLine, pendingGeneratedLine, "generatedLine cannot backtrack");
75927                 // Emit comma to separate the entry
75928                 if (hasLast) {
75929                     mappings += ",";
75930                 }
75931             }
75932             // 1. Relative generated character
75933             mappings += base64VLQFormatEncode(pendingGeneratedCharacter - lastGeneratedCharacter);
75934             lastGeneratedCharacter = pendingGeneratedCharacter;
75935             if (hasPendingSource) {
75936                 // 2. Relative sourceIndex
75937                 mappings += base64VLQFormatEncode(pendingSourceIndex - lastSourceIndex);
75938                 lastSourceIndex = pendingSourceIndex;
75939                 // 3. Relative source line
75940                 mappings += base64VLQFormatEncode(pendingSourceLine - lastSourceLine);
75941                 lastSourceLine = pendingSourceLine;
75942                 // 4. Relative source character
75943                 mappings += base64VLQFormatEncode(pendingSourceCharacter - lastSourceCharacter);
75944                 lastSourceCharacter = pendingSourceCharacter;
75945                 if (hasPendingName) {
75946                     // 5. Relative nameIndex
75947                     mappings += base64VLQFormatEncode(pendingNameIndex - lastNameIndex);
75948                     lastNameIndex = pendingNameIndex;
75949                 }
75950             }
75951             hasLast = true;
75952             exit();
75953         }
75954         function toJSON() {
75955             commitPendingMapping();
75956             return {
75957                 version: 3,
75958                 file: file,
75959                 sourceRoot: sourceRoot,
75960                 sources: sources,
75961                 names: names,
75962                 mappings: mappings,
75963                 sourcesContent: sourcesContent,
75964             };
75965         }
75966     }
75967     ts.createSourceMapGenerator = createSourceMapGenerator;
75968     // Sometimes tools can see the following line as a source mapping url comment, so we mangle it a bit (the [M])
75969     var sourceMapCommentRegExp = /^\/\/[@#] source[M]appingURL=(.+)\s*$/;
75970     var whitespaceOrMapCommentRegExp = /^\s*(\/\/[@#] .*)?$/;
75971     function getLineInfo(text, lineStarts) {
75972         return {
75973             getLineCount: function () { return lineStarts.length; },
75974             getLineText: function (line) { return text.substring(lineStarts[line], lineStarts[line + 1]); }
75975         };
75976     }
75977     ts.getLineInfo = getLineInfo;
75978     /**
75979      * Tries to find the sourceMappingURL comment at the end of a file.
75980      */
75981     function tryGetSourceMappingURL(lineInfo) {
75982         for (var index = lineInfo.getLineCount() - 1; index >= 0; index--) {
75983             var line = lineInfo.getLineText(index);
75984             var comment = sourceMapCommentRegExp.exec(line);
75985             if (comment) {
75986                 return comment[1];
75987             }
75988             // If we see a non-whitespace/map comment-like line, break, to avoid scanning up the entire file
75989             else if (!line.match(whitespaceOrMapCommentRegExp)) {
75990                 break;
75991             }
75992         }
75993     }
75994     ts.tryGetSourceMappingURL = tryGetSourceMappingURL;
75995     /* eslint-disable no-null/no-null */
75996     function isStringOrNull(x) {
75997         return typeof x === "string" || x === null;
75998     }
75999     function isRawSourceMap(x) {
76000         return x !== null
76001             && typeof x === "object"
76002             && x.version === 3
76003             && typeof x.file === "string"
76004             && typeof x.mappings === "string"
76005             && ts.isArray(x.sources) && ts.every(x.sources, ts.isString)
76006             && (x.sourceRoot === undefined || x.sourceRoot === null || typeof x.sourceRoot === "string")
76007             && (x.sourcesContent === undefined || x.sourcesContent === null || ts.isArray(x.sourcesContent) && ts.every(x.sourcesContent, isStringOrNull))
76008             && (x.names === undefined || x.names === null || ts.isArray(x.names) && ts.every(x.names, ts.isString));
76009     }
76010     ts.isRawSourceMap = isRawSourceMap;
76011     /* eslint-enable no-null/no-null */
76012     function tryParseRawSourceMap(text) {
76013         try {
76014             var parsed = JSON.parse(text);
76015             if (isRawSourceMap(parsed)) {
76016                 return parsed;
76017             }
76018         }
76019         catch (_a) {
76020             // empty
76021         }
76022         return undefined;
76023     }
76024     ts.tryParseRawSourceMap = tryParseRawSourceMap;
76025     function decodeMappings(mappings) {
76026         var done = false;
76027         var pos = 0;
76028         var generatedLine = 0;
76029         var generatedCharacter = 0;
76030         var sourceIndex = 0;
76031         var sourceLine = 0;
76032         var sourceCharacter = 0;
76033         var nameIndex = 0;
76034         var error;
76035         return {
76036             get pos() { return pos; },
76037             get error() { return error; },
76038             get state() { return captureMapping(/*hasSource*/ true, /*hasName*/ true); },
76039             next: function () {
76040                 while (!done && pos < mappings.length) {
76041                     var ch = mappings.charCodeAt(pos);
76042                     if (ch === 59 /* semicolon */) {
76043                         // new line
76044                         generatedLine++;
76045                         generatedCharacter = 0;
76046                         pos++;
76047                         continue;
76048                     }
76049                     if (ch === 44 /* comma */) {
76050                         // Next entry is on same line - no action needed
76051                         pos++;
76052                         continue;
76053                     }
76054                     var hasSource = false;
76055                     var hasName = false;
76056                     generatedCharacter += base64VLQFormatDecode();
76057                     if (hasReportedError())
76058                         return stopIterating();
76059                     if (generatedCharacter < 0)
76060                         return setErrorAndStopIterating("Invalid generatedCharacter found");
76061                     if (!isSourceMappingSegmentEnd()) {
76062                         hasSource = true;
76063                         sourceIndex += base64VLQFormatDecode();
76064                         if (hasReportedError())
76065                             return stopIterating();
76066                         if (sourceIndex < 0)
76067                             return setErrorAndStopIterating("Invalid sourceIndex found");
76068                         if (isSourceMappingSegmentEnd())
76069                             return setErrorAndStopIterating("Unsupported Format: No entries after sourceIndex");
76070                         sourceLine += base64VLQFormatDecode();
76071                         if (hasReportedError())
76072                             return stopIterating();
76073                         if (sourceLine < 0)
76074                             return setErrorAndStopIterating("Invalid sourceLine found");
76075                         if (isSourceMappingSegmentEnd())
76076                             return setErrorAndStopIterating("Unsupported Format: No entries after sourceLine");
76077                         sourceCharacter += base64VLQFormatDecode();
76078                         if (hasReportedError())
76079                             return stopIterating();
76080                         if (sourceCharacter < 0)
76081                             return setErrorAndStopIterating("Invalid sourceCharacter found");
76082                         if (!isSourceMappingSegmentEnd()) {
76083                             hasName = true;
76084                             nameIndex += base64VLQFormatDecode();
76085                             if (hasReportedError())
76086                                 return stopIterating();
76087                             if (nameIndex < 0)
76088                                 return setErrorAndStopIterating("Invalid nameIndex found");
76089                             if (!isSourceMappingSegmentEnd())
76090                                 return setErrorAndStopIterating("Unsupported Error Format: Entries after nameIndex");
76091                         }
76092                     }
76093                     return { value: captureMapping(hasSource, hasName), done: done };
76094                 }
76095                 return stopIterating();
76096             }
76097         };
76098         function captureMapping(hasSource, hasName) {
76099             return {
76100                 generatedLine: generatedLine,
76101                 generatedCharacter: generatedCharacter,
76102                 sourceIndex: hasSource ? sourceIndex : undefined,
76103                 sourceLine: hasSource ? sourceLine : undefined,
76104                 sourceCharacter: hasSource ? sourceCharacter : undefined,
76105                 nameIndex: hasName ? nameIndex : undefined
76106             };
76107         }
76108         function stopIterating() {
76109             done = true;
76110             return { value: undefined, done: true };
76111         }
76112         function setError(message) {
76113             if (error === undefined) {
76114                 error = message;
76115             }
76116         }
76117         function setErrorAndStopIterating(message) {
76118             setError(message);
76119             return stopIterating();
76120         }
76121         function hasReportedError() {
76122             return error !== undefined;
76123         }
76124         function isSourceMappingSegmentEnd() {
76125             return (pos === mappings.length ||
76126                 mappings.charCodeAt(pos) === 44 /* comma */ ||
76127                 mappings.charCodeAt(pos) === 59 /* semicolon */);
76128         }
76129         function base64VLQFormatDecode() {
76130             var moreDigits = true;
76131             var shiftCount = 0;
76132             var value = 0;
76133             for (; moreDigits; pos++) {
76134                 if (pos >= mappings.length)
76135                     return setError("Error in decoding base64VLQFormatDecode, past the mapping string"), -1;
76136                 // 6 digit number
76137                 var currentByte = base64FormatDecode(mappings.charCodeAt(pos));
76138                 if (currentByte === -1)
76139                     return setError("Invalid character in VLQ"), -1;
76140                 // If msb is set, we still have more bits to continue
76141                 moreDigits = (currentByte & 32) !== 0;
76142                 // least significant 5 bits are the next msbs in the final value.
76143                 value = value | ((currentByte & 31) << shiftCount);
76144                 shiftCount += 5;
76145             }
76146             // Least significant bit if 1 represents negative and rest of the msb is actual absolute value
76147             if ((value & 1) === 0) {
76148                 // + number
76149                 value = value >> 1;
76150             }
76151             else {
76152                 // - number
76153                 value = value >> 1;
76154                 value = -value;
76155             }
76156             return value;
76157         }
76158     }
76159     ts.decodeMappings = decodeMappings;
76160     function sameMapping(left, right) {
76161         return left === right
76162             || left.generatedLine === right.generatedLine
76163                 && left.generatedCharacter === right.generatedCharacter
76164                 && left.sourceIndex === right.sourceIndex
76165                 && left.sourceLine === right.sourceLine
76166                 && left.sourceCharacter === right.sourceCharacter
76167                 && left.nameIndex === right.nameIndex;
76168     }
76169     ts.sameMapping = sameMapping;
76170     function isSourceMapping(mapping) {
76171         return mapping.sourceIndex !== undefined
76172             && mapping.sourceLine !== undefined
76173             && mapping.sourceCharacter !== undefined;
76174     }
76175     ts.isSourceMapping = isSourceMapping;
76176     function base64FormatEncode(value) {
76177         return value >= 0 && value < 26 ? 65 /* A */ + value :
76178             value >= 26 && value < 52 ? 97 /* a */ + value - 26 :
76179                 value >= 52 && value < 62 ? 48 /* _0 */ + value - 52 :
76180                     value === 62 ? 43 /* plus */ :
76181                         value === 63 ? 47 /* slash */ :
76182                             ts.Debug.fail(value + ": not a base64 value");
76183     }
76184     function base64FormatDecode(ch) {
76185         return ch >= 65 /* A */ && ch <= 90 /* Z */ ? ch - 65 /* A */ :
76186             ch >= 97 /* a */ && ch <= 122 /* z */ ? ch - 97 /* a */ + 26 :
76187                 ch >= 48 /* _0 */ && ch <= 57 /* _9 */ ? ch - 48 /* _0 */ + 52 :
76188                     ch === 43 /* plus */ ? 62 :
76189                         ch === 47 /* slash */ ? 63 :
76190                             -1;
76191     }
76192     function base64VLQFormatEncode(inValue) {
76193         // Add a new least significant bit that has the sign of the value.
76194         // if negative number the least significant bit that gets added to the number has value 1
76195         // else least significant bit value that gets added is 0
76196         // eg. -1 changes to binary : 01 [1] => 3
76197         //     +1 changes to binary : 01 [0] => 2
76198         if (inValue < 0) {
76199             inValue = ((-inValue) << 1) + 1;
76200         }
76201         else {
76202             inValue = inValue << 1;
76203         }
76204         // Encode 5 bits at a time starting from least significant bits
76205         var encodedStr = "";
76206         do {
76207             var currentDigit = inValue & 31; // 11111
76208             inValue = inValue >> 5;
76209             if (inValue > 0) {
76210                 // There are still more digits to decode, set the msb (6th bit)
76211                 currentDigit = currentDigit | 32;
76212             }
76213             encodedStr = encodedStr + String.fromCharCode(base64FormatEncode(currentDigit));
76214         } while (inValue > 0);
76215         return encodedStr;
76216     }
76217     function isSourceMappedPosition(value) {
76218         return value.sourceIndex !== undefined
76219             && value.sourcePosition !== undefined;
76220     }
76221     function sameMappedPosition(left, right) {
76222         return left.generatedPosition === right.generatedPosition
76223             && left.sourceIndex === right.sourceIndex
76224             && left.sourcePosition === right.sourcePosition;
76225     }
76226     function compareSourcePositions(left, right) {
76227         // Compares sourcePosition without comparing sourceIndex
76228         // since the mappings are grouped by sourceIndex
76229         ts.Debug.assert(left.sourceIndex === right.sourceIndex);
76230         return ts.compareValues(left.sourcePosition, right.sourcePosition);
76231     }
76232     function compareGeneratedPositions(left, right) {
76233         return ts.compareValues(left.generatedPosition, right.generatedPosition);
76234     }
76235     function getSourcePositionOfMapping(value) {
76236         return value.sourcePosition;
76237     }
76238     function getGeneratedPositionOfMapping(value) {
76239         return value.generatedPosition;
76240     }
76241     function createDocumentPositionMapper(host, map, mapPath) {
76242         var mapDirectory = ts.getDirectoryPath(mapPath);
76243         var sourceRoot = map.sourceRoot ? ts.getNormalizedAbsolutePath(map.sourceRoot, mapDirectory) : mapDirectory;
76244         var generatedAbsoluteFilePath = ts.getNormalizedAbsolutePath(map.file, mapDirectory);
76245         var generatedFile = host.getSourceFileLike(generatedAbsoluteFilePath);
76246         var sourceFileAbsolutePaths = map.sources.map(function (source) { return ts.getNormalizedAbsolutePath(source, sourceRoot); });
76247         var sourceToSourceIndexMap = ts.createMapFromEntries(sourceFileAbsolutePaths.map(function (source, i) { return [host.getCanonicalFileName(source), i]; }));
76248         var decodedMappings;
76249         var generatedMappings;
76250         var sourceMappings;
76251         return {
76252             getSourcePosition: getSourcePosition,
76253             getGeneratedPosition: getGeneratedPosition
76254         };
76255         function processMapping(mapping) {
76256             var generatedPosition = generatedFile !== undefined
76257                 ? ts.getPositionOfLineAndCharacter(generatedFile, mapping.generatedLine, mapping.generatedCharacter, /*allowEdits*/ true)
76258                 : -1;
76259             var source;
76260             var sourcePosition;
76261             if (isSourceMapping(mapping)) {
76262                 var sourceFile = host.getSourceFileLike(sourceFileAbsolutePaths[mapping.sourceIndex]);
76263                 source = map.sources[mapping.sourceIndex];
76264                 sourcePosition = sourceFile !== undefined
76265                     ? ts.getPositionOfLineAndCharacter(sourceFile, mapping.sourceLine, mapping.sourceCharacter, /*allowEdits*/ true)
76266                     : -1;
76267             }
76268             return {
76269                 generatedPosition: generatedPosition,
76270                 source: source,
76271                 sourceIndex: mapping.sourceIndex,
76272                 sourcePosition: sourcePosition,
76273                 nameIndex: mapping.nameIndex
76274             };
76275         }
76276         function getDecodedMappings() {
76277             if (decodedMappings === undefined) {
76278                 var decoder = decodeMappings(map.mappings);
76279                 var mappings = ts.arrayFrom(decoder, processMapping);
76280                 if (decoder.error !== undefined) {
76281                     if (host.log) {
76282                         host.log("Encountered error while decoding sourcemap: " + decoder.error);
76283                     }
76284                     decodedMappings = ts.emptyArray;
76285                 }
76286                 else {
76287                     decodedMappings = mappings;
76288                 }
76289             }
76290             return decodedMappings;
76291         }
76292         function getSourceMappings(sourceIndex) {
76293             if (sourceMappings === undefined) {
76294                 var lists = [];
76295                 for (var _i = 0, _a = getDecodedMappings(); _i < _a.length; _i++) {
76296                     var mapping = _a[_i];
76297                     if (!isSourceMappedPosition(mapping))
76298                         continue;
76299                     var list = lists[mapping.sourceIndex];
76300                     if (!list)
76301                         lists[mapping.sourceIndex] = list = [];
76302                     list.push(mapping);
76303                 }
76304                 sourceMappings = lists.map(function (list) { return ts.sortAndDeduplicate(list, compareSourcePositions, sameMappedPosition); });
76305             }
76306             return sourceMappings[sourceIndex];
76307         }
76308         function getGeneratedMappings() {
76309             if (generatedMappings === undefined) {
76310                 var list = [];
76311                 for (var _i = 0, _a = getDecodedMappings(); _i < _a.length; _i++) {
76312                     var mapping = _a[_i];
76313                     list.push(mapping);
76314                 }
76315                 generatedMappings = ts.sortAndDeduplicate(list, compareGeneratedPositions, sameMappedPosition);
76316             }
76317             return generatedMappings;
76318         }
76319         function getGeneratedPosition(loc) {
76320             var sourceIndex = sourceToSourceIndexMap.get(host.getCanonicalFileName(loc.fileName));
76321             if (sourceIndex === undefined)
76322                 return loc;
76323             var sourceMappings = getSourceMappings(sourceIndex);
76324             if (!ts.some(sourceMappings))
76325                 return loc;
76326             var targetIndex = ts.binarySearchKey(sourceMappings, loc.pos, getSourcePositionOfMapping, ts.compareValues);
76327             if (targetIndex < 0) {
76328                 // if no exact match, closest is 2's complement of result
76329                 targetIndex = ~targetIndex;
76330             }
76331             var mapping = sourceMappings[targetIndex];
76332             if (mapping === undefined || mapping.sourceIndex !== sourceIndex) {
76333                 return loc;
76334             }
76335             return { fileName: generatedAbsoluteFilePath, pos: mapping.generatedPosition }; // Closest pos
76336         }
76337         function getSourcePosition(loc) {
76338             var generatedMappings = getGeneratedMappings();
76339             if (!ts.some(generatedMappings))
76340                 return loc;
76341             var targetIndex = ts.binarySearchKey(generatedMappings, loc.pos, getGeneratedPositionOfMapping, ts.compareValues);
76342             if (targetIndex < 0) {
76343                 // if no exact match, closest is 2's complement of result
76344                 targetIndex = ~targetIndex;
76345             }
76346             var mapping = generatedMappings[targetIndex];
76347             if (mapping === undefined || !isSourceMappedPosition(mapping)) {
76348                 return loc;
76349             }
76350             return { fileName: sourceFileAbsolutePaths[mapping.sourceIndex], pos: mapping.sourcePosition }; // Closest pos
76351         }
76352     }
76353     ts.createDocumentPositionMapper = createDocumentPositionMapper;
76354     ts.identitySourceMapConsumer = {
76355         getSourcePosition: ts.identity,
76356         getGeneratedPosition: ts.identity
76357     };
76358 })(ts || (ts = {}));
76359 /* @internal */
76360 var ts;
76361 (function (ts) {
76362     function getOriginalNodeId(node) {
76363         node = ts.getOriginalNode(node);
76364         return node ? ts.getNodeId(node) : 0;
76365     }
76366     ts.getOriginalNodeId = getOriginalNodeId;
76367     function containsDefaultReference(node) {
76368         if (!node)
76369             return false;
76370         if (!ts.isNamedImports(node))
76371             return false;
76372         return ts.some(node.elements, isNamedDefaultReference);
76373     }
76374     function isNamedDefaultReference(e) {
76375         return e.propertyName !== undefined && e.propertyName.escapedText === "default" /* Default */;
76376     }
76377     function chainBundle(transformSourceFile) {
76378         return transformSourceFileOrBundle;
76379         function transformSourceFileOrBundle(node) {
76380             return node.kind === 290 /* SourceFile */ ? transformSourceFile(node) : transformBundle(node);
76381         }
76382         function transformBundle(node) {
76383             return ts.createBundle(ts.map(node.sourceFiles, transformSourceFile), node.prepends);
76384         }
76385     }
76386     ts.chainBundle = chainBundle;
76387     function getExportNeedsImportStarHelper(node) {
76388         return !!ts.getNamespaceDeclarationNode(node);
76389     }
76390     ts.getExportNeedsImportStarHelper = getExportNeedsImportStarHelper;
76391     function getImportNeedsImportStarHelper(node) {
76392         if (!!ts.getNamespaceDeclarationNode(node)) {
76393             return true;
76394         }
76395         var bindings = node.importClause && node.importClause.namedBindings;
76396         if (!bindings) {
76397             return false;
76398         }
76399         if (!ts.isNamedImports(bindings))
76400             return false;
76401         var defaultRefCount = 0;
76402         for (var _i = 0, _a = bindings.elements; _i < _a.length; _i++) {
76403             var binding = _a[_i];
76404             if (isNamedDefaultReference(binding)) {
76405                 defaultRefCount++;
76406             }
76407         }
76408         // 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
76409         return (defaultRefCount > 0 && defaultRefCount !== bindings.elements.length) || (!!(bindings.elements.length - defaultRefCount) && ts.isDefaultImport(node));
76410     }
76411     ts.getImportNeedsImportStarHelper = getImportNeedsImportStarHelper;
76412     function getImportNeedsImportDefaultHelper(node) {
76413         // 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)
76414         return !getImportNeedsImportStarHelper(node) && (ts.isDefaultImport(node) || (!!node.importClause && ts.isNamedImports(node.importClause.namedBindings) && containsDefaultReference(node.importClause.namedBindings))); // TODO: GH#18217
76415     }
76416     ts.getImportNeedsImportDefaultHelper = getImportNeedsImportDefaultHelper;
76417     function collectExternalModuleInfo(sourceFile, resolver, compilerOptions) {
76418         var externalImports = [];
76419         var exportSpecifiers = ts.createMultiMap();
76420         var exportedBindings = [];
76421         var uniqueExports = ts.createMap();
76422         var exportedNames;
76423         var hasExportDefault = false;
76424         var exportEquals;
76425         var hasExportStarsToExportValues = false;
76426         var hasImportStar = false;
76427         var hasImportDefault = false;
76428         for (var _i = 0, _a = sourceFile.statements; _i < _a.length; _i++) {
76429             var node = _a[_i];
76430             switch (node.kind) {
76431                 case 254 /* ImportDeclaration */:
76432                     // import "mod"
76433                     // import x from "mod"
76434                     // import * as x from "mod"
76435                     // import { x, y } from "mod"
76436                     externalImports.push(node);
76437                     if (!hasImportStar && getImportNeedsImportStarHelper(node)) {
76438                         hasImportStar = true;
76439                     }
76440                     if (!hasImportDefault && getImportNeedsImportDefaultHelper(node)) {
76441                         hasImportDefault = true;
76442                     }
76443                     break;
76444                 case 253 /* ImportEqualsDeclaration */:
76445                     if (node.moduleReference.kind === 265 /* ExternalModuleReference */) {
76446                         // import x = require("mod")
76447                         externalImports.push(node);
76448                     }
76449                     break;
76450                 case 260 /* ExportDeclaration */:
76451                     if (node.moduleSpecifier) {
76452                         if (!node.exportClause) {
76453                             // export * from "mod"
76454                             externalImports.push(node);
76455                             hasExportStarsToExportValues = true;
76456                         }
76457                         else {
76458                             // export * as ns from "mod"
76459                             // export { x, y } from "mod"
76460                             externalImports.push(node);
76461                         }
76462                     }
76463                     else {
76464                         // export { x, y }
76465                         for (var _b = 0, _c = ts.cast(node.exportClause, ts.isNamedExports).elements; _b < _c.length; _b++) {
76466                             var specifier = _c[_b];
76467                             if (!uniqueExports.get(ts.idText(specifier.name))) {
76468                                 var name = specifier.propertyName || specifier.name;
76469                                 exportSpecifiers.add(ts.idText(name), specifier);
76470                                 var decl = resolver.getReferencedImportDeclaration(name)
76471                                     || resolver.getReferencedValueDeclaration(name);
76472                                 if (decl) {
76473                                     multiMapSparseArrayAdd(exportedBindings, getOriginalNodeId(decl), specifier.name);
76474                                 }
76475                                 uniqueExports.set(ts.idText(specifier.name), true);
76476                                 exportedNames = ts.append(exportedNames, specifier.name);
76477                             }
76478                         }
76479                     }
76480                     break;
76481                 case 259 /* ExportAssignment */:
76482                     if (node.isExportEquals && !exportEquals) {
76483                         // export = x
76484                         exportEquals = node;
76485                     }
76486                     break;
76487                 case 225 /* VariableStatement */:
76488                     if (ts.hasModifier(node, 1 /* Export */)) {
76489                         for (var _d = 0, _e = node.declarationList.declarations; _d < _e.length; _d++) {
76490                             var decl = _e[_d];
76491                             exportedNames = collectExportedVariableInfo(decl, uniqueExports, exportedNames);
76492                         }
76493                     }
76494                     break;
76495                 case 244 /* FunctionDeclaration */:
76496                     if (ts.hasModifier(node, 1 /* Export */)) {
76497                         if (ts.hasModifier(node, 512 /* Default */)) {
76498                             // export default function() { }
76499                             if (!hasExportDefault) {
76500                                 multiMapSparseArrayAdd(exportedBindings, getOriginalNodeId(node), ts.getDeclarationName(node));
76501                                 hasExportDefault = true;
76502                             }
76503                         }
76504                         else {
76505                             // export function x() { }
76506                             var name = node.name;
76507                             if (!uniqueExports.get(ts.idText(name))) {
76508                                 multiMapSparseArrayAdd(exportedBindings, getOriginalNodeId(node), name);
76509                                 uniqueExports.set(ts.idText(name), true);
76510                                 exportedNames = ts.append(exportedNames, name);
76511                             }
76512                         }
76513                     }
76514                     break;
76515                 case 245 /* ClassDeclaration */:
76516                     if (ts.hasModifier(node, 1 /* Export */)) {
76517                         if (ts.hasModifier(node, 512 /* Default */)) {
76518                             // export default class { }
76519                             if (!hasExportDefault) {
76520                                 multiMapSparseArrayAdd(exportedBindings, getOriginalNodeId(node), ts.getDeclarationName(node));
76521                                 hasExportDefault = true;
76522                             }
76523                         }
76524                         else {
76525                             // export class x { }
76526                             var name = node.name;
76527                             if (name && !uniqueExports.get(ts.idText(name))) {
76528                                 multiMapSparseArrayAdd(exportedBindings, getOriginalNodeId(node), name);
76529                                 uniqueExports.set(ts.idText(name), true);
76530                                 exportedNames = ts.append(exportedNames, name);
76531                             }
76532                         }
76533                     }
76534                     break;
76535             }
76536         }
76537         var externalHelpersImportDeclaration = ts.createExternalHelpersImportDeclarationIfNeeded(sourceFile, compilerOptions, hasExportStarsToExportValues, hasImportStar, hasImportDefault);
76538         if (externalHelpersImportDeclaration) {
76539             externalImports.unshift(externalHelpersImportDeclaration);
76540         }
76541         return { externalImports: externalImports, exportSpecifiers: exportSpecifiers, exportEquals: exportEquals, hasExportStarsToExportValues: hasExportStarsToExportValues, exportedBindings: exportedBindings, exportedNames: exportedNames, externalHelpersImportDeclaration: externalHelpersImportDeclaration };
76542     }
76543     ts.collectExternalModuleInfo = collectExternalModuleInfo;
76544     function collectExportedVariableInfo(decl, uniqueExports, exportedNames) {
76545         if (ts.isBindingPattern(decl.name)) {
76546             for (var _i = 0, _a = decl.name.elements; _i < _a.length; _i++) {
76547                 var element = _a[_i];
76548                 if (!ts.isOmittedExpression(element)) {
76549                     exportedNames = collectExportedVariableInfo(element, uniqueExports, exportedNames);
76550                 }
76551             }
76552         }
76553         else if (!ts.isGeneratedIdentifier(decl.name)) {
76554             var text = ts.idText(decl.name);
76555             if (!uniqueExports.get(text)) {
76556                 uniqueExports.set(text, true);
76557                 exportedNames = ts.append(exportedNames, decl.name);
76558             }
76559         }
76560         return exportedNames;
76561     }
76562     /** Use a sparse array as a multi-map. */
76563     function multiMapSparseArrayAdd(map, key, value) {
76564         var values = map[key];
76565         if (values) {
76566             values.push(value);
76567         }
76568         else {
76569             map[key] = values = [value];
76570         }
76571         return values;
76572     }
76573     /**
76574      * Used in the module transformer to check if an expression is reasonably without sideeffect,
76575      *  and thus better to copy into multiple places rather than to cache in a temporary variable
76576      *  - this is mostly subjective beyond the requirement that the expression not be sideeffecting
76577      */
76578     function isSimpleCopiableExpression(expression) {
76579         return ts.isStringLiteralLike(expression) ||
76580             expression.kind === 8 /* NumericLiteral */ ||
76581             ts.isKeyword(expression.kind) ||
76582             ts.isIdentifier(expression);
76583     }
76584     ts.isSimpleCopiableExpression = isSimpleCopiableExpression;
76585     /**
76586      * A simple inlinable expression is an expression which can be copied into multiple locations
76587      * without risk of repeating any sideeffects and whose value could not possibly change between
76588      * any such locations
76589      */
76590     function isSimpleInlineableExpression(expression) {
76591         return !ts.isIdentifier(expression) && isSimpleCopiableExpression(expression) ||
76592             ts.isWellKnownSymbolSyntactically(expression);
76593     }
76594     ts.isSimpleInlineableExpression = isSimpleInlineableExpression;
76595     function isCompoundAssignment(kind) {
76596         return kind >= 63 /* FirstCompoundAssignment */
76597             && kind <= 74 /* LastCompoundAssignment */;
76598     }
76599     ts.isCompoundAssignment = isCompoundAssignment;
76600     function getNonAssignmentOperatorForCompoundAssignment(kind) {
76601         switch (kind) {
76602             case 63 /* PlusEqualsToken */: return 39 /* PlusToken */;
76603             case 64 /* MinusEqualsToken */: return 40 /* MinusToken */;
76604             case 65 /* AsteriskEqualsToken */: return 41 /* AsteriskToken */;
76605             case 66 /* AsteriskAsteriskEqualsToken */: return 42 /* AsteriskAsteriskToken */;
76606             case 67 /* SlashEqualsToken */: return 43 /* SlashToken */;
76607             case 68 /* PercentEqualsToken */: return 44 /* PercentToken */;
76608             case 69 /* LessThanLessThanEqualsToken */: return 47 /* LessThanLessThanToken */;
76609             case 70 /* GreaterThanGreaterThanEqualsToken */: return 48 /* GreaterThanGreaterThanToken */;
76610             case 71 /* GreaterThanGreaterThanGreaterThanEqualsToken */: return 49 /* GreaterThanGreaterThanGreaterThanToken */;
76611             case 72 /* AmpersandEqualsToken */: return 50 /* AmpersandToken */;
76612             case 73 /* BarEqualsToken */: return 51 /* BarToken */;
76613             case 74 /* CaretEqualsToken */: return 52 /* CaretToken */;
76614         }
76615     }
76616     ts.getNonAssignmentOperatorForCompoundAssignment = getNonAssignmentOperatorForCompoundAssignment;
76617     /**
76618      * Adds super call and preceding prologue directives into the list of statements.
76619      *
76620      * @param ctor The constructor node.
76621      * @param result The list of statements.
76622      * @param visitor The visitor to apply to each node added to the result array.
76623      * @returns index of the statement that follows super call
76624      */
76625     function addPrologueDirectivesAndInitialSuperCall(ctor, result, visitor) {
76626         if (ctor.body) {
76627             var statements = ctor.body.statements;
76628             // add prologue directives to the list (if any)
76629             var index = ts.addPrologue(result, statements, /*ensureUseStrict*/ false, visitor);
76630             if (index === statements.length) {
76631                 // list contains nothing but prologue directives (or empty) - exit
76632                 return index;
76633             }
76634             var superIndex = ts.findIndex(statements, function (s) { return ts.isExpressionStatement(s) && ts.isSuperCall(s.expression); }, index);
76635             if (superIndex > -1) {
76636                 for (var i = index; i <= superIndex; i++) {
76637                     result.push(ts.visitNode(statements[i], visitor, ts.isStatement));
76638                 }
76639                 return superIndex + 1;
76640             }
76641             return index;
76642         }
76643         return 0;
76644     }
76645     ts.addPrologueDirectivesAndInitialSuperCall = addPrologueDirectivesAndInitialSuperCall;
76646     /**
76647      * @param input Template string input strings
76648      * @param args Names which need to be made file-level unique
76649      */
76650     function helperString(input) {
76651         var args = [];
76652         for (var _i = 1; _i < arguments.length; _i++) {
76653             args[_i - 1] = arguments[_i];
76654         }
76655         return function (uniqueName) {
76656             var result = "";
76657             for (var i = 0; i < args.length; i++) {
76658                 result += input[i];
76659                 result += uniqueName(args[i]);
76660             }
76661             result += input[input.length - 1];
76662             return result;
76663         };
76664     }
76665     ts.helperString = helperString;
76666     /**
76667      * Gets all the static or all the instance property declarations of a class
76668      *
76669      * @param node The class node.
76670      * @param isStatic A value indicating whether to get properties from the static or instance side of the class.
76671      */
76672     function getProperties(node, requireInitializer, isStatic) {
76673         return ts.filter(node.members, function (m) { return isInitializedOrStaticProperty(m, requireInitializer, isStatic); });
76674     }
76675     ts.getProperties = getProperties;
76676     /**
76677      * Is a class element either a static or an instance property declaration with an initializer?
76678      *
76679      * @param member The class element node.
76680      * @param isStatic A value indicating whether the member should be a static or instance member.
76681      */
76682     function isInitializedOrStaticProperty(member, requireInitializer, isStatic) {
76683         return ts.isPropertyDeclaration(member)
76684             && (!!member.initializer || !requireInitializer)
76685             && ts.hasStaticModifier(member) === isStatic;
76686     }
76687     /**
76688      * Gets a value indicating whether a class element is either a static or an instance property declaration with an initializer.
76689      *
76690      * @param member The class element node.
76691      * @param isStatic A value indicating whether the member should be a static or instance member.
76692      */
76693     function isInitializedProperty(member) {
76694         return member.kind === 159 /* PropertyDeclaration */
76695             && member.initializer !== undefined;
76696     }
76697     ts.isInitializedProperty = isInitializedProperty;
76698 })(ts || (ts = {}));
76699 /*@internal*/
76700 var ts;
76701 (function (ts) {
76702     var FlattenLevel;
76703     (function (FlattenLevel) {
76704         FlattenLevel[FlattenLevel["All"] = 0] = "All";
76705         FlattenLevel[FlattenLevel["ObjectRest"] = 1] = "ObjectRest";
76706     })(FlattenLevel = ts.FlattenLevel || (ts.FlattenLevel = {}));
76707     /**
76708      * Flattens a DestructuringAssignment or a VariableDeclaration to an expression.
76709      *
76710      * @param node The node to flatten.
76711      * @param visitor An optional visitor used to visit initializers.
76712      * @param context The transformation context.
76713      * @param level Indicates the extent to which flattening should occur.
76714      * @param needsValue An optional value indicating whether the value from the right-hand-side of
76715      * the destructuring assignment is needed as part of a larger expression.
76716      * @param createAssignmentCallback An optional callback used to create the assignment expression.
76717      */
76718     function flattenDestructuringAssignment(node, visitor, context, level, needsValue, createAssignmentCallback) {
76719         var location = node;
76720         var value;
76721         if (ts.isDestructuringAssignment(node)) {
76722             value = node.right;
76723             while (ts.isEmptyArrayLiteral(node.left) || ts.isEmptyObjectLiteral(node.left)) {
76724                 if (ts.isDestructuringAssignment(value)) {
76725                     location = node = value;
76726                     value = node.right;
76727                 }
76728                 else {
76729                     return ts.visitNode(value, visitor, ts.isExpression);
76730                 }
76731             }
76732         }
76733         var expressions;
76734         var flattenContext = {
76735             context: context,
76736             level: level,
76737             downlevelIteration: !!context.getCompilerOptions().downlevelIteration,
76738             hoistTempVariables: true,
76739             emitExpression: emitExpression,
76740             emitBindingOrAssignment: emitBindingOrAssignment,
76741             createArrayBindingOrAssignmentPattern: makeArrayAssignmentPattern,
76742             createObjectBindingOrAssignmentPattern: makeObjectAssignmentPattern,
76743             createArrayBindingOrAssignmentElement: makeAssignmentElement,
76744             visitor: visitor
76745         };
76746         if (value) {
76747             value = ts.visitNode(value, visitor, ts.isExpression);
76748             if (ts.isIdentifier(value) && bindingOrAssignmentElementAssignsToName(node, value.escapedText) ||
76749                 bindingOrAssignmentElementContainsNonLiteralComputedName(node)) {
76750                 // If the right-hand value of the assignment is also an assignment target then
76751                 // we need to cache the right-hand value.
76752                 value = ensureIdentifier(flattenContext, value, /*reuseIdentifierExpressions*/ false, location);
76753             }
76754             else if (needsValue) {
76755                 // If the right-hand value of the destructuring assignment needs to be preserved (as
76756                 // is the case when the destructuring assignment is part of a larger expression),
76757                 // then we need to cache the right-hand value.
76758                 //
76759                 // The source map location for the assignment should point to the entire binary
76760                 // expression.
76761                 value = ensureIdentifier(flattenContext, value, /*reuseIdentifierExpressions*/ true, location);
76762             }
76763             else if (ts.nodeIsSynthesized(node)) {
76764                 // Generally, the source map location for a destructuring assignment is the root
76765                 // expression.
76766                 //
76767                 // However, if the root expression is synthesized (as in the case
76768                 // of the initializer when transforming a ForOfStatement), then the source map
76769                 // location should point to the right-hand value of the expression.
76770                 location = value;
76771             }
76772         }
76773         flattenBindingOrAssignmentElement(flattenContext, node, value, location, /*skipInitializer*/ ts.isDestructuringAssignment(node));
76774         if (value && needsValue) {
76775             if (!ts.some(expressions)) {
76776                 return value;
76777             }
76778             expressions.push(value);
76779         }
76780         return ts.aggregateTransformFlags(ts.inlineExpressions(expressions)) || ts.createOmittedExpression();
76781         function emitExpression(expression) {
76782             ts.aggregateTransformFlags(expression);
76783             expressions = ts.append(expressions, expression);
76784         }
76785         function emitBindingOrAssignment(target, value, location, original) {
76786             ts.Debug.assertNode(target, createAssignmentCallback ? ts.isIdentifier : ts.isExpression);
76787             var expression = createAssignmentCallback
76788                 ? createAssignmentCallback(target, value, location)
76789                 : ts.setTextRange(ts.createAssignment(ts.visitNode(target, visitor, ts.isExpression), value), location);
76790             expression.original = original;
76791             emitExpression(expression);
76792         }
76793     }
76794     ts.flattenDestructuringAssignment = flattenDestructuringAssignment;
76795     function bindingOrAssignmentElementAssignsToName(element, escapedName) {
76796         var target = ts.getTargetOfBindingOrAssignmentElement(element); // TODO: GH#18217
76797         if (ts.isBindingOrAssignmentPattern(target)) {
76798             return bindingOrAssignmentPatternAssignsToName(target, escapedName);
76799         }
76800         else if (ts.isIdentifier(target)) {
76801             return target.escapedText === escapedName;
76802         }
76803         return false;
76804     }
76805     function bindingOrAssignmentPatternAssignsToName(pattern, escapedName) {
76806         var elements = ts.getElementsOfBindingOrAssignmentPattern(pattern);
76807         for (var _i = 0, elements_3 = elements; _i < elements_3.length; _i++) {
76808             var element = elements_3[_i];
76809             if (bindingOrAssignmentElementAssignsToName(element, escapedName)) {
76810                 return true;
76811             }
76812         }
76813         return false;
76814     }
76815     function bindingOrAssignmentElementContainsNonLiteralComputedName(element) {
76816         var propertyName = ts.tryGetPropertyNameOfBindingOrAssignmentElement(element);
76817         if (propertyName && ts.isComputedPropertyName(propertyName) && !ts.isLiteralExpression(propertyName.expression)) {
76818             return true;
76819         }
76820         var target = ts.getTargetOfBindingOrAssignmentElement(element);
76821         return !!target && ts.isBindingOrAssignmentPattern(target) && bindingOrAssignmentPatternContainsNonLiteralComputedName(target);
76822     }
76823     function bindingOrAssignmentPatternContainsNonLiteralComputedName(pattern) {
76824         return !!ts.forEach(ts.getElementsOfBindingOrAssignmentPattern(pattern), bindingOrAssignmentElementContainsNonLiteralComputedName);
76825     }
76826     /**
76827      * Flattens a VariableDeclaration or ParameterDeclaration to one or more variable declarations.
76828      *
76829      * @param node The node to flatten.
76830      * @param visitor An optional visitor used to visit initializers.
76831      * @param context The transformation context.
76832      * @param boundValue The value bound to the declaration.
76833      * @param skipInitializer A value indicating whether to ignore the initializer of `node`.
76834      * @param hoistTempVariables Indicates whether temporary variables should not be recorded in-line.
76835      * @param level Indicates the extent to which flattening should occur.
76836      */
76837     function flattenDestructuringBinding(node, visitor, context, level, rval, hoistTempVariables, skipInitializer) {
76838         if (hoistTempVariables === void 0) { hoistTempVariables = false; }
76839         var pendingExpressions;
76840         var pendingDeclarations = [];
76841         var declarations = [];
76842         var flattenContext = {
76843             context: context,
76844             level: level,
76845             downlevelIteration: !!context.getCompilerOptions().downlevelIteration,
76846             hoistTempVariables: hoistTempVariables,
76847             emitExpression: emitExpression,
76848             emitBindingOrAssignment: emitBindingOrAssignment,
76849             createArrayBindingOrAssignmentPattern: makeArrayBindingPattern,
76850             createObjectBindingOrAssignmentPattern: makeObjectBindingPattern,
76851             createArrayBindingOrAssignmentElement: makeBindingElement,
76852             visitor: visitor
76853         };
76854         if (ts.isVariableDeclaration(node)) {
76855             var initializer = ts.getInitializerOfBindingOrAssignmentElement(node);
76856             if (initializer && (ts.isIdentifier(initializer) && bindingOrAssignmentElementAssignsToName(node, initializer.escapedText) ||
76857                 bindingOrAssignmentElementContainsNonLiteralComputedName(node))) {
76858                 // If the right-hand value of the assignment is also an assignment target then
76859                 // we need to cache the right-hand value.
76860                 initializer = ensureIdentifier(flattenContext, initializer, /*reuseIdentifierExpressions*/ false, initializer);
76861                 node = ts.updateVariableDeclaration(node, node.name, node.type, initializer);
76862             }
76863         }
76864         flattenBindingOrAssignmentElement(flattenContext, node, rval, node, skipInitializer);
76865         if (pendingExpressions) {
76866             var temp = ts.createTempVariable(/*recordTempVariable*/ undefined);
76867             if (hoistTempVariables) {
76868                 var value = ts.inlineExpressions(pendingExpressions);
76869                 pendingExpressions = undefined;
76870                 emitBindingOrAssignment(temp, value, /*location*/ undefined, /*original*/ undefined);
76871             }
76872             else {
76873                 context.hoistVariableDeclaration(temp);
76874                 var pendingDeclaration = ts.last(pendingDeclarations);
76875                 pendingDeclaration.pendingExpressions = ts.append(pendingDeclaration.pendingExpressions, ts.createAssignment(temp, pendingDeclaration.value));
76876                 ts.addRange(pendingDeclaration.pendingExpressions, pendingExpressions);
76877                 pendingDeclaration.value = temp;
76878             }
76879         }
76880         for (var _i = 0, pendingDeclarations_1 = pendingDeclarations; _i < pendingDeclarations_1.length; _i++) {
76881             var _a = pendingDeclarations_1[_i], pendingExpressions_1 = _a.pendingExpressions, name = _a.name, value = _a.value, location = _a.location, original = _a.original;
76882             var variable = ts.createVariableDeclaration(name, 
76883             /*type*/ undefined, pendingExpressions_1 ? ts.inlineExpressions(ts.append(pendingExpressions_1, value)) : value);
76884             variable.original = original;
76885             ts.setTextRange(variable, location);
76886             ts.aggregateTransformFlags(variable);
76887             declarations.push(variable);
76888         }
76889         return declarations;
76890         function emitExpression(value) {
76891             pendingExpressions = ts.append(pendingExpressions, value);
76892         }
76893         function emitBindingOrAssignment(target, value, location, original) {
76894             ts.Debug.assertNode(target, ts.isBindingName);
76895             if (pendingExpressions) {
76896                 value = ts.inlineExpressions(ts.append(pendingExpressions, value));
76897                 pendingExpressions = undefined;
76898             }
76899             pendingDeclarations.push({ pendingExpressions: pendingExpressions, name: target, value: value, location: location, original: original });
76900         }
76901     }
76902     ts.flattenDestructuringBinding = flattenDestructuringBinding;
76903     /**
76904      * Flattens a BindingOrAssignmentElement into zero or more bindings or assignments.
76905      *
76906      * @param flattenContext Options used to control flattening.
76907      * @param element The element to flatten.
76908      * @param value The current RHS value to assign to the element.
76909      * @param location The location to use for source maps and comments.
76910      * @param skipInitializer An optional value indicating whether to include the initializer
76911      * for the element.
76912      */
76913     function flattenBindingOrAssignmentElement(flattenContext, element, value, location, skipInitializer) {
76914         if (!skipInitializer) {
76915             var initializer = ts.visitNode(ts.getInitializerOfBindingOrAssignmentElement(element), flattenContext.visitor, ts.isExpression);
76916             if (initializer) {
76917                 // Combine value and initializer
76918                 value = value ? createDefaultValueCheck(flattenContext, value, initializer, location) : initializer;
76919             }
76920             else if (!value) {
76921                 // Use 'void 0' in absence of value and initializer
76922                 value = ts.createVoidZero();
76923             }
76924         }
76925         var bindingTarget = ts.getTargetOfBindingOrAssignmentElement(element); // TODO: GH#18217
76926         if (ts.isObjectBindingOrAssignmentPattern(bindingTarget)) {
76927             flattenObjectBindingOrAssignmentPattern(flattenContext, element, bindingTarget, value, location);
76928         }
76929         else if (ts.isArrayBindingOrAssignmentPattern(bindingTarget)) {
76930             flattenArrayBindingOrAssignmentPattern(flattenContext, element, bindingTarget, value, location);
76931         }
76932         else {
76933             flattenContext.emitBindingOrAssignment(bindingTarget, value, location, /*original*/ element); // TODO: GH#18217
76934         }
76935     }
76936     /**
76937      * Flattens an ObjectBindingOrAssignmentPattern into zero or more bindings or assignments.
76938      *
76939      * @param flattenContext Options used to control flattening.
76940      * @param parent The parent element of the pattern.
76941      * @param pattern The ObjectBindingOrAssignmentPattern to flatten.
76942      * @param value The current RHS value to assign to the element.
76943      * @param location The location to use for source maps and comments.
76944      */
76945     function flattenObjectBindingOrAssignmentPattern(flattenContext, parent, pattern, value, location) {
76946         var elements = ts.getElementsOfBindingOrAssignmentPattern(pattern);
76947         var numElements = elements.length;
76948         if (numElements !== 1) {
76949             // For anything other than a single-element destructuring we need to generate a temporary
76950             // to ensure value is evaluated exactly once. Additionally, if we have zero elements
76951             // we need to emit *something* to ensure that in case a 'var' keyword was already emitted,
76952             // so in that case, we'll intentionally create that temporary.
76953             var reuseIdentifierExpressions = !ts.isDeclarationBindingElement(parent) || numElements !== 0;
76954             value = ensureIdentifier(flattenContext, value, reuseIdentifierExpressions, location);
76955         }
76956         var bindingElements;
76957         var computedTempVariables;
76958         for (var i = 0; i < numElements; i++) {
76959             var element = elements[i];
76960             if (!ts.getRestIndicatorOfBindingOrAssignmentElement(element)) {
76961                 var propertyName = ts.getPropertyNameOfBindingOrAssignmentElement(element);
76962                 if (flattenContext.level >= 1 /* ObjectRest */
76963                     && !(element.transformFlags & (8192 /* ContainsRestOrSpread */ | 16384 /* ContainsObjectRestOrSpread */))
76964                     && !(ts.getTargetOfBindingOrAssignmentElement(element).transformFlags & (8192 /* ContainsRestOrSpread */ | 16384 /* ContainsObjectRestOrSpread */))
76965                     && !ts.isComputedPropertyName(propertyName)) {
76966                     bindingElements = ts.append(bindingElements, ts.visitNode(element, flattenContext.visitor));
76967                 }
76968                 else {
76969                     if (bindingElements) {
76970                         flattenContext.emitBindingOrAssignment(flattenContext.createObjectBindingOrAssignmentPattern(bindingElements), value, location, pattern);
76971                         bindingElements = undefined;
76972                     }
76973                     var rhsValue = createDestructuringPropertyAccess(flattenContext, value, propertyName);
76974                     if (ts.isComputedPropertyName(propertyName)) {
76975                         computedTempVariables = ts.append(computedTempVariables, rhsValue.argumentExpression);
76976                     }
76977                     flattenBindingOrAssignmentElement(flattenContext, element, rhsValue, /*location*/ element);
76978                 }
76979             }
76980             else if (i === numElements - 1) {
76981                 if (bindingElements) {
76982                     flattenContext.emitBindingOrAssignment(flattenContext.createObjectBindingOrAssignmentPattern(bindingElements), value, location, pattern);
76983                     bindingElements = undefined;
76984                 }
76985                 var rhsValue = createRestCall(flattenContext.context, value, elements, computedTempVariables, pattern); // TODO: GH#18217
76986                 flattenBindingOrAssignmentElement(flattenContext, element, rhsValue, element);
76987             }
76988         }
76989         if (bindingElements) {
76990             flattenContext.emitBindingOrAssignment(flattenContext.createObjectBindingOrAssignmentPattern(bindingElements), value, location, pattern);
76991         }
76992     }
76993     /**
76994      * Flattens an ArrayBindingOrAssignmentPattern into zero or more bindings or assignments.
76995      *
76996      * @param flattenContext Options used to control flattening.
76997      * @param parent The parent element of the pattern.
76998      * @param pattern The ArrayBindingOrAssignmentPattern to flatten.
76999      * @param value The current RHS value to assign to the element.
77000      * @param location The location to use for source maps and comments.
77001      */
77002     function flattenArrayBindingOrAssignmentPattern(flattenContext, parent, pattern, value, location) {
77003         var elements = ts.getElementsOfBindingOrAssignmentPattern(pattern);
77004         var numElements = elements.length;
77005         if (flattenContext.level < 1 /* ObjectRest */ && flattenContext.downlevelIteration) {
77006             // Read the elements of the iterable into an array
77007             value = ensureIdentifier(flattenContext, ts.createReadHelper(flattenContext.context, value, numElements > 0 && ts.getRestIndicatorOfBindingOrAssignmentElement(elements[numElements - 1])
77008                 ? undefined
77009                 : numElements, location), 
77010             /*reuseIdentifierExpressions*/ false, location);
77011         }
77012         else if (numElements !== 1 && (flattenContext.level < 1 /* ObjectRest */ || numElements === 0)
77013             || ts.every(elements, ts.isOmittedExpression)) {
77014             // For anything other than a single-element destructuring we need to generate a temporary
77015             // to ensure value is evaluated exactly once. Additionally, if we have zero elements
77016             // we need to emit *something* to ensure that in case a 'var' keyword was already emitted,
77017             // so in that case, we'll intentionally create that temporary.
77018             // Or all the elements of the binding pattern are omitted expression such as "var [,] = [1,2]",
77019             // then we will create temporary variable.
77020             var reuseIdentifierExpressions = !ts.isDeclarationBindingElement(parent) || numElements !== 0;
77021             value = ensureIdentifier(flattenContext, value, reuseIdentifierExpressions, location);
77022         }
77023         var bindingElements;
77024         var restContainingElements;
77025         for (var i = 0; i < numElements; i++) {
77026             var element = elements[i];
77027             if (flattenContext.level >= 1 /* ObjectRest */) {
77028                 // If an array pattern contains an ObjectRest, we must cache the result so that we
77029                 // can perform the ObjectRest destructuring in a different declaration
77030                 if (element.transformFlags & 16384 /* ContainsObjectRestOrSpread */) {
77031                     var temp = ts.createTempVariable(/*recordTempVariable*/ undefined);
77032                     if (flattenContext.hoistTempVariables) {
77033                         flattenContext.context.hoistVariableDeclaration(temp);
77034                     }
77035                     restContainingElements = ts.append(restContainingElements, [temp, element]);
77036                     bindingElements = ts.append(bindingElements, flattenContext.createArrayBindingOrAssignmentElement(temp));
77037                 }
77038                 else {
77039                     bindingElements = ts.append(bindingElements, element);
77040                 }
77041             }
77042             else if (ts.isOmittedExpression(element)) {
77043                 continue;
77044             }
77045             else if (!ts.getRestIndicatorOfBindingOrAssignmentElement(element)) {
77046                 var rhsValue = ts.createElementAccess(value, i);
77047                 flattenBindingOrAssignmentElement(flattenContext, element, rhsValue, /*location*/ element);
77048             }
77049             else if (i === numElements - 1) {
77050                 var rhsValue = ts.createArraySlice(value, i);
77051                 flattenBindingOrAssignmentElement(flattenContext, element, rhsValue, /*location*/ element);
77052             }
77053         }
77054         if (bindingElements) {
77055             flattenContext.emitBindingOrAssignment(flattenContext.createArrayBindingOrAssignmentPattern(bindingElements), value, location, pattern);
77056         }
77057         if (restContainingElements) {
77058             for (var _i = 0, restContainingElements_1 = restContainingElements; _i < restContainingElements_1.length; _i++) {
77059                 var _a = restContainingElements_1[_i], id = _a[0], element = _a[1];
77060                 flattenBindingOrAssignmentElement(flattenContext, element, id, element);
77061             }
77062         }
77063     }
77064     /**
77065      * Creates an expression used to provide a default value if a value is `undefined` at runtime.
77066      *
77067      * @param flattenContext Options used to control flattening.
77068      * @param value The RHS value to test.
77069      * @param defaultValue The default value to use if `value` is `undefined` at runtime.
77070      * @param location The location to use for source maps and comments.
77071      */
77072     function createDefaultValueCheck(flattenContext, value, defaultValue, location) {
77073         value = ensureIdentifier(flattenContext, value, /*reuseIdentifierExpressions*/ true, location);
77074         return ts.createConditional(ts.createTypeCheck(value, "undefined"), defaultValue, value);
77075     }
77076     /**
77077      * Creates either a PropertyAccessExpression or an ElementAccessExpression for the
77078      * right-hand side of a transformed destructuring assignment.
77079      *
77080      * @link https://tc39.github.io/ecma262/#sec-runtime-semantics-keyeddestructuringassignmentevaluation
77081      *
77082      * @param flattenContext Options used to control flattening.
77083      * @param value The RHS value that is the source of the property.
77084      * @param propertyName The destructuring property name.
77085      */
77086     function createDestructuringPropertyAccess(flattenContext, value, propertyName) {
77087         if (ts.isComputedPropertyName(propertyName)) {
77088             var argumentExpression = ensureIdentifier(flattenContext, ts.visitNode(propertyName.expression, flattenContext.visitor), /*reuseIdentifierExpressions*/ false, /*location*/ propertyName);
77089             return ts.createElementAccess(value, argumentExpression);
77090         }
77091         else if (ts.isStringOrNumericLiteralLike(propertyName)) {
77092             var argumentExpression = ts.getSynthesizedClone(propertyName);
77093             argumentExpression.text = argumentExpression.text;
77094             return ts.createElementAccess(value, argumentExpression);
77095         }
77096         else {
77097             var name = ts.createIdentifier(ts.idText(propertyName));
77098             return ts.createPropertyAccess(value, name);
77099         }
77100     }
77101     /**
77102      * Ensures that there exists a declared identifier whose value holds the given expression.
77103      * This function is useful to ensure that the expression's value can be read from in subsequent expressions.
77104      * Unless 'reuseIdentifierExpressions' is false, 'value' will be returned if it is just an identifier.
77105      *
77106      * @param flattenContext Options used to control flattening.
77107      * @param value the expression whose value needs to be bound.
77108      * @param reuseIdentifierExpressions true if identifier expressions can simply be returned;
77109      * false if it is necessary to always emit an identifier.
77110      * @param location The location to use for source maps and comments.
77111      */
77112     function ensureIdentifier(flattenContext, value, reuseIdentifierExpressions, location) {
77113         if (ts.isIdentifier(value) && reuseIdentifierExpressions) {
77114             return value;
77115         }
77116         else {
77117             var temp = ts.createTempVariable(/*recordTempVariable*/ undefined);
77118             if (flattenContext.hoistTempVariables) {
77119                 flattenContext.context.hoistVariableDeclaration(temp);
77120                 flattenContext.emitExpression(ts.setTextRange(ts.createAssignment(temp, value), location));
77121             }
77122             else {
77123                 flattenContext.emitBindingOrAssignment(temp, value, location, /*original*/ undefined);
77124             }
77125             return temp;
77126         }
77127     }
77128     function makeArrayBindingPattern(elements) {
77129         ts.Debug.assertEachNode(elements, ts.isArrayBindingElement);
77130         return ts.createArrayBindingPattern(elements);
77131     }
77132     function makeArrayAssignmentPattern(elements) {
77133         return ts.createArrayLiteral(ts.map(elements, ts.convertToArrayAssignmentElement));
77134     }
77135     function makeObjectBindingPattern(elements) {
77136         ts.Debug.assertEachNode(elements, ts.isBindingElement);
77137         return ts.createObjectBindingPattern(elements);
77138     }
77139     function makeObjectAssignmentPattern(elements) {
77140         return ts.createObjectLiteral(ts.map(elements, ts.convertToObjectAssignmentElement));
77141     }
77142     function makeBindingElement(name) {
77143         return ts.createBindingElement(/*dotDotDotToken*/ undefined, /*propertyName*/ undefined, name);
77144     }
77145     function makeAssignmentElement(name) {
77146         return name;
77147     }
77148     ts.restHelper = {
77149         name: "typescript:rest",
77150         importName: "__rest",
77151         scoped: false,
77152         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            };"
77153     };
77154     /** Given value: o, propName: p, pattern: { a, b, ...p } from the original statement
77155      * `{ a, b, ...p } = o`, create `p = __rest(o, ["a", "b"]);`
77156      */
77157     function createRestCall(context, value, elements, computedTempVariables, location) {
77158         context.requestEmitHelper(ts.restHelper);
77159         var propertyNames = [];
77160         var computedTempVariableOffset = 0;
77161         for (var i = 0; i < elements.length - 1; i++) {
77162             var propertyName = ts.getPropertyNameOfBindingOrAssignmentElement(elements[i]);
77163             if (propertyName) {
77164                 if (ts.isComputedPropertyName(propertyName)) {
77165                     var temp = computedTempVariables[computedTempVariableOffset];
77166                     computedTempVariableOffset++;
77167                     // typeof _tmp === "symbol" ? _tmp : _tmp + ""
77168                     propertyNames.push(ts.createConditional(ts.createTypeCheck(temp, "symbol"), temp, ts.createAdd(temp, ts.createLiteral(""))));
77169                 }
77170                 else {
77171                     propertyNames.push(ts.createLiteral(propertyName));
77172                 }
77173             }
77174         }
77175         return ts.createCall(ts.getUnscopedHelperName("__rest"), 
77176         /*typeArguments*/ undefined, [
77177             value,
77178             ts.setTextRange(ts.createArrayLiteral(propertyNames), location)
77179         ]);
77180     }
77181 })(ts || (ts = {}));
77182 /*@internal*/
77183 var ts;
77184 (function (ts) {
77185     var ProcessLevel;
77186     (function (ProcessLevel) {
77187         ProcessLevel[ProcessLevel["LiftRestriction"] = 0] = "LiftRestriction";
77188         ProcessLevel[ProcessLevel["All"] = 1] = "All";
77189     })(ProcessLevel = ts.ProcessLevel || (ts.ProcessLevel = {}));
77190     function processTaggedTemplateExpression(context, node, visitor, currentSourceFile, recordTaggedTemplateString, level) {
77191         // Visit the tag expression
77192         var tag = ts.visitNode(node.tag, visitor, ts.isExpression);
77193         // Build up the template arguments and the raw and cooked strings for the template.
77194         // We start out with 'undefined' for the first argument and revisit later
77195         // to avoid walking over the template string twice and shifting all our arguments over after the fact.
77196         var templateArguments = [undefined];
77197         var cookedStrings = [];
77198         var rawStrings = [];
77199         var template = node.template;
77200         if (level === ProcessLevel.LiftRestriction && !ts.hasInvalidEscape(template))
77201             return node;
77202         if (ts.isNoSubstitutionTemplateLiteral(template)) {
77203             cookedStrings.push(createTemplateCooked(template));
77204             rawStrings.push(getRawLiteral(template, currentSourceFile));
77205         }
77206         else {
77207             cookedStrings.push(createTemplateCooked(template.head));
77208             rawStrings.push(getRawLiteral(template.head, currentSourceFile));
77209             for (var _i = 0, _a = template.templateSpans; _i < _a.length; _i++) {
77210                 var templateSpan = _a[_i];
77211                 cookedStrings.push(createTemplateCooked(templateSpan.literal));
77212                 rawStrings.push(getRawLiteral(templateSpan.literal, currentSourceFile));
77213                 templateArguments.push(ts.visitNode(templateSpan.expression, visitor, ts.isExpression));
77214             }
77215         }
77216         var helperCall = createTemplateObjectHelper(context, ts.createArrayLiteral(cookedStrings), ts.createArrayLiteral(rawStrings));
77217         // Create a variable to cache the template object if we're in a module.
77218         // Do not do this in the global scope, as any variable we currently generate could conflict with
77219         // variables from outside of the current compilation. In the future, we can revisit this behavior.
77220         if (ts.isExternalModule(currentSourceFile)) {
77221             var tempVar = ts.createUniqueName("templateObject");
77222             recordTaggedTemplateString(tempVar);
77223             templateArguments[0] = ts.createLogicalOr(tempVar, ts.createAssignment(tempVar, helperCall));
77224         }
77225         else {
77226             templateArguments[0] = helperCall;
77227         }
77228         return ts.createCall(tag, /*typeArguments*/ undefined, templateArguments);
77229     }
77230     ts.processTaggedTemplateExpression = processTaggedTemplateExpression;
77231     function createTemplateCooked(template) {
77232         return template.templateFlags ? ts.createIdentifier("undefined") : ts.createLiteral(template.text);
77233     }
77234     /**
77235      * Creates an ES5 compatible literal from an ES6 template literal.
77236      *
77237      * @param node The ES6 template literal.
77238      */
77239     function getRawLiteral(node, currentSourceFile) {
77240         // Find original source text, since we need to emit the raw strings of the tagged template.
77241         // The raw strings contain the (escaped) strings of what the user wrote.
77242         // Examples: `\n` is converted to "\\n", a template string with a newline to "\n".
77243         var text = node.rawText;
77244         if (text === undefined) {
77245             text = ts.getSourceTextOfNodeFromSourceFile(currentSourceFile, node);
77246             // text contains the original source, it will also contain quotes ("`"), dolar signs and braces ("${" and "}"),
77247             // thus we need to remove those characters.
77248             // First template piece starts with "`", others with "}"
77249             // Last template piece ends with "`", others with "${"
77250             var isLast = node.kind === 14 /* NoSubstitutionTemplateLiteral */ || node.kind === 17 /* TemplateTail */;
77251             text = text.substring(1, text.length - (isLast ? 1 : 2));
77252         }
77253         // Newline normalization:
77254         // ES6 Spec 11.8.6.1 - Static Semantics of TV's and TRV's
77255         // <CR><LF> and <CR> LineTerminatorSequences are normalized to <LF> for both TV and TRV.
77256         text = text.replace(/\r\n?/g, "\n");
77257         return ts.setTextRange(ts.createLiteral(text), node);
77258     }
77259     function createTemplateObjectHelper(context, cooked, raw) {
77260         context.requestEmitHelper(ts.templateObjectHelper);
77261         return ts.createCall(ts.getUnscopedHelperName("__makeTemplateObject"), 
77262         /*typeArguments*/ undefined, [
77263             cooked,
77264             raw
77265         ]);
77266     }
77267     ts.templateObjectHelper = {
77268         name: "typescript:makeTemplateObject",
77269         importName: "__makeTemplateObject",
77270         scoped: false,
77271         priority: 0,
77272         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            };"
77273     };
77274 })(ts || (ts = {}));
77275 /*@internal*/
77276 var ts;
77277 (function (ts) {
77278     /**
77279      * Indicates whether to emit type metadata in the new format.
77280      */
77281     var USE_NEW_TYPE_METADATA_FORMAT = false;
77282     var TypeScriptSubstitutionFlags;
77283     (function (TypeScriptSubstitutionFlags) {
77284         /** Enables substitutions for decorated classes. */
77285         TypeScriptSubstitutionFlags[TypeScriptSubstitutionFlags["ClassAliases"] = 1] = "ClassAliases";
77286         /** Enables substitutions for namespace exports. */
77287         TypeScriptSubstitutionFlags[TypeScriptSubstitutionFlags["NamespaceExports"] = 2] = "NamespaceExports";
77288         /* Enables substitutions for unqualified enum members */
77289         TypeScriptSubstitutionFlags[TypeScriptSubstitutionFlags["NonQualifiedEnumMembers"] = 8] = "NonQualifiedEnumMembers";
77290     })(TypeScriptSubstitutionFlags || (TypeScriptSubstitutionFlags = {}));
77291     var ClassFacts;
77292     (function (ClassFacts) {
77293         ClassFacts[ClassFacts["None"] = 0] = "None";
77294         ClassFacts[ClassFacts["HasStaticInitializedProperties"] = 1] = "HasStaticInitializedProperties";
77295         ClassFacts[ClassFacts["HasConstructorDecorators"] = 2] = "HasConstructorDecorators";
77296         ClassFacts[ClassFacts["HasMemberDecorators"] = 4] = "HasMemberDecorators";
77297         ClassFacts[ClassFacts["IsExportOfNamespace"] = 8] = "IsExportOfNamespace";
77298         ClassFacts[ClassFacts["IsNamedExternalExport"] = 16] = "IsNamedExternalExport";
77299         ClassFacts[ClassFacts["IsDefaultExternalExport"] = 32] = "IsDefaultExternalExport";
77300         ClassFacts[ClassFacts["IsDerivedClass"] = 64] = "IsDerivedClass";
77301         ClassFacts[ClassFacts["UseImmediatelyInvokedFunctionExpression"] = 128] = "UseImmediatelyInvokedFunctionExpression";
77302         ClassFacts[ClassFacts["HasAnyDecorators"] = 6] = "HasAnyDecorators";
77303         ClassFacts[ClassFacts["NeedsName"] = 5] = "NeedsName";
77304         ClassFacts[ClassFacts["MayNeedImmediatelyInvokedFunctionExpression"] = 7] = "MayNeedImmediatelyInvokedFunctionExpression";
77305         ClassFacts[ClassFacts["IsExported"] = 56] = "IsExported";
77306     })(ClassFacts || (ClassFacts = {}));
77307     function transformTypeScript(context) {
77308         var startLexicalEnvironment = context.startLexicalEnvironment, resumeLexicalEnvironment = context.resumeLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistVariableDeclaration = context.hoistVariableDeclaration;
77309         var resolver = context.getEmitResolver();
77310         var compilerOptions = context.getCompilerOptions();
77311         var strictNullChecks = ts.getStrictOptionValue(compilerOptions, "strictNullChecks");
77312         var languageVersion = ts.getEmitScriptTarget(compilerOptions);
77313         var moduleKind = ts.getEmitModuleKind(compilerOptions);
77314         // Save the previous transformation hooks.
77315         var previousOnEmitNode = context.onEmitNode;
77316         var previousOnSubstituteNode = context.onSubstituteNode;
77317         // Set new transformation hooks.
77318         context.onEmitNode = onEmitNode;
77319         context.onSubstituteNode = onSubstituteNode;
77320         // Enable substitution for property/element access to emit const enum values.
77321         context.enableSubstitution(194 /* PropertyAccessExpression */);
77322         context.enableSubstitution(195 /* ElementAccessExpression */);
77323         // These variables contain state that changes as we descend into the tree.
77324         var currentSourceFile;
77325         var currentNamespace;
77326         var currentNamespaceContainerName;
77327         var currentLexicalScope;
77328         var currentNameScope;
77329         var currentScopeFirstDeclarationsOfName;
77330         var currentClassHasParameterProperties;
77331         /**
77332          * Keeps track of whether expression substitution has been enabled for specific edge cases.
77333          * They are persisted between each SourceFile transformation and should not be reset.
77334          */
77335         var enabledSubstitutions;
77336         /**
77337          * A map that keeps track of aliases created for classes with decorators to avoid issues
77338          * with the double-binding behavior of classes.
77339          */
77340         var classAliases;
77341         /**
77342          * Keeps track of whether we are within any containing namespaces when performing
77343          * just-in-time substitution while printing an expression identifier.
77344          */
77345         var applicableSubstitutions;
77346         return transformSourceFileOrBundle;
77347         function transformSourceFileOrBundle(node) {
77348             if (node.kind === 291 /* Bundle */) {
77349                 return transformBundle(node);
77350             }
77351             return transformSourceFile(node);
77352         }
77353         function transformBundle(node) {
77354             return ts.createBundle(node.sourceFiles.map(transformSourceFile), ts.mapDefined(node.prepends, function (prepend) {
77355                 if (prepend.kind === 293 /* InputFiles */) {
77356                     return ts.createUnparsedSourceFile(prepend, "js");
77357                 }
77358                 return prepend;
77359             }));
77360         }
77361         /**
77362          * Transform TypeScript-specific syntax in a SourceFile.
77363          *
77364          * @param node A SourceFile node.
77365          */
77366         function transformSourceFile(node) {
77367             if (node.isDeclarationFile) {
77368                 return node;
77369             }
77370             currentSourceFile = node;
77371             var visited = saveStateAndInvoke(node, visitSourceFile);
77372             ts.addEmitHelpers(visited, context.readEmitHelpers());
77373             currentSourceFile = undefined;
77374             return visited;
77375         }
77376         /**
77377          * Visits a node, saving and restoring state variables on the stack.
77378          *
77379          * @param node The node to visit.
77380          */
77381         function saveStateAndInvoke(node, f) {
77382             // Save state
77383             var savedCurrentScope = currentLexicalScope;
77384             var savedCurrentNameScope = currentNameScope;
77385             var savedCurrentScopeFirstDeclarationsOfName = currentScopeFirstDeclarationsOfName;
77386             var savedCurrentClassHasParameterProperties = currentClassHasParameterProperties;
77387             // Handle state changes before visiting a node.
77388             onBeforeVisitNode(node);
77389             var visited = f(node);
77390             // Restore state
77391             if (currentLexicalScope !== savedCurrentScope) {
77392                 currentScopeFirstDeclarationsOfName = savedCurrentScopeFirstDeclarationsOfName;
77393             }
77394             currentLexicalScope = savedCurrentScope;
77395             currentNameScope = savedCurrentNameScope;
77396             currentClassHasParameterProperties = savedCurrentClassHasParameterProperties;
77397             return visited;
77398         }
77399         /**
77400          * Performs actions that should always occur immediately before visiting a node.
77401          *
77402          * @param node The node to visit.
77403          */
77404         function onBeforeVisitNode(node) {
77405             switch (node.kind) {
77406                 case 290 /* SourceFile */:
77407                 case 251 /* CaseBlock */:
77408                 case 250 /* ModuleBlock */:
77409                 case 223 /* Block */:
77410                     currentLexicalScope = node;
77411                     currentNameScope = undefined;
77412                     currentScopeFirstDeclarationsOfName = undefined;
77413                     break;
77414                 case 245 /* ClassDeclaration */:
77415                 case 244 /* FunctionDeclaration */:
77416                     if (ts.hasModifier(node, 2 /* Ambient */)) {
77417                         break;
77418                     }
77419                     // Record these declarations provided that they have a name.
77420                     if (node.name) {
77421                         recordEmittedDeclarationInScope(node);
77422                     }
77423                     else {
77424                         // These nodes should always have names unless they are default-exports;
77425                         // however, class declaration parsing allows for undefined names, so syntactically invalid
77426                         // programs may also have an undefined name.
77427                         ts.Debug.assert(node.kind === 245 /* ClassDeclaration */ || ts.hasModifier(node, 512 /* Default */));
77428                     }
77429                     if (ts.isClassDeclaration(node)) {
77430                         // XXX: should probably also cover interfaces and type aliases that can have type variables?
77431                         currentNameScope = node;
77432                     }
77433                     break;
77434             }
77435         }
77436         /**
77437          * General-purpose node visitor.
77438          *
77439          * @param node The node to visit.
77440          */
77441         function visitor(node) {
77442             return saveStateAndInvoke(node, visitorWorker);
77443         }
77444         /**
77445          * Visits and possibly transforms any node.
77446          *
77447          * @param node The node to visit.
77448          */
77449         function visitorWorker(node) {
77450             if (node.transformFlags & 1 /* ContainsTypeScript */) {
77451                 return visitTypeScript(node);
77452             }
77453             return node;
77454         }
77455         /**
77456          * Specialized visitor that visits the immediate children of a SourceFile.
77457          *
77458          * @param node The node to visit.
77459          */
77460         function sourceElementVisitor(node) {
77461             return saveStateAndInvoke(node, sourceElementVisitorWorker);
77462         }
77463         /**
77464          * Specialized visitor that visits the immediate children of a SourceFile.
77465          *
77466          * @param node The node to visit.
77467          */
77468         function sourceElementVisitorWorker(node) {
77469             switch (node.kind) {
77470                 case 254 /* ImportDeclaration */:
77471                 case 253 /* ImportEqualsDeclaration */:
77472                 case 259 /* ExportAssignment */:
77473                 case 260 /* ExportDeclaration */:
77474                     return visitEllidableStatement(node);
77475                 default:
77476                     return visitorWorker(node);
77477             }
77478         }
77479         function visitEllidableStatement(node) {
77480             var parsed = ts.getParseTreeNode(node);
77481             if (parsed !== node) {
77482                 // If the node has been transformed by a `before` transformer, perform no ellision on it
77483                 // As the type information we would attempt to lookup to perform ellision is potentially unavailable for the synthesized nodes
77484                 // We do not reuse `visitorWorker`, as the ellidable statement syntax kinds are technically unrecognized by the switch-case in `visitTypeScript`,
77485                 // and will trigger debug failures when debug verbosity is turned up
77486                 if (node.transformFlags & 1 /* ContainsTypeScript */) {
77487                     // This node contains TypeScript, so we should visit its children.
77488                     return ts.visitEachChild(node, visitor, context);
77489                 }
77490                 // Otherwise, we can just return the node
77491                 return node;
77492             }
77493             switch (node.kind) {
77494                 case 254 /* ImportDeclaration */:
77495                     return visitImportDeclaration(node);
77496                 case 253 /* ImportEqualsDeclaration */:
77497                     return visitImportEqualsDeclaration(node);
77498                 case 259 /* ExportAssignment */:
77499                     return visitExportAssignment(node);
77500                 case 260 /* ExportDeclaration */:
77501                     return visitExportDeclaration(node);
77502                 default:
77503                     ts.Debug.fail("Unhandled ellided statement");
77504             }
77505         }
77506         /**
77507          * Specialized visitor that visits the immediate children of a namespace.
77508          *
77509          * @param node The node to visit.
77510          */
77511         function namespaceElementVisitor(node) {
77512             return saveStateAndInvoke(node, namespaceElementVisitorWorker);
77513         }
77514         /**
77515          * Specialized visitor that visits the immediate children of a namespace.
77516          *
77517          * @param node The node to visit.
77518          */
77519         function namespaceElementVisitorWorker(node) {
77520             if (node.kind === 260 /* ExportDeclaration */ ||
77521                 node.kind === 254 /* ImportDeclaration */ ||
77522                 node.kind === 255 /* ImportClause */ ||
77523                 (node.kind === 253 /* ImportEqualsDeclaration */ &&
77524                     node.moduleReference.kind === 265 /* ExternalModuleReference */)) {
77525                 // do not emit ES6 imports and exports since they are illegal inside a namespace
77526                 return undefined;
77527             }
77528             else if (node.transformFlags & 1 /* ContainsTypeScript */ || ts.hasModifier(node, 1 /* Export */)) {
77529                 return visitTypeScript(node);
77530             }
77531             return node;
77532         }
77533         /**
77534          * Specialized visitor that visits the immediate children of a class with TypeScript syntax.
77535          *
77536          * @param node The node to visit.
77537          */
77538         function classElementVisitor(node) {
77539             return saveStateAndInvoke(node, classElementVisitorWorker);
77540         }
77541         /**
77542          * Specialized visitor that visits the immediate children of a class with TypeScript syntax.
77543          *
77544          * @param node The node to visit.
77545          */
77546         function classElementVisitorWorker(node) {
77547             switch (node.kind) {
77548                 case 162 /* Constructor */:
77549                     return visitConstructor(node);
77550                 case 159 /* PropertyDeclaration */:
77551                     // Property declarations are not TypeScript syntax, but they must be visited
77552                     // for the decorator transformation.
77553                     return visitPropertyDeclaration(node);
77554                 case 167 /* IndexSignature */:
77555                 case 163 /* GetAccessor */:
77556                 case 164 /* SetAccessor */:
77557                 case 161 /* MethodDeclaration */:
77558                     // Fallback to the default visit behavior.
77559                     return visitorWorker(node);
77560                 case 222 /* SemicolonClassElement */:
77561                     return node;
77562                 default:
77563                     return ts.Debug.failBadSyntaxKind(node);
77564             }
77565         }
77566         function modifierVisitor(node) {
77567             if (ts.modifierToFlag(node.kind) & 2270 /* TypeScriptModifier */) {
77568                 return undefined;
77569             }
77570             else if (currentNamespace && node.kind === 89 /* ExportKeyword */) {
77571                 return undefined;
77572             }
77573             return node;
77574         }
77575         /**
77576          * Branching visitor, visits a TypeScript syntax node.
77577          *
77578          * @param node The node to visit.
77579          */
77580         function visitTypeScript(node) {
77581             if (ts.isStatement(node) && ts.hasModifier(node, 2 /* Ambient */)) {
77582                 // TypeScript ambient declarations are elided, but some comments may be preserved.
77583                 // See the implementation of `getLeadingComments` in comments.ts for more details.
77584                 return ts.createNotEmittedStatement(node);
77585             }
77586             switch (node.kind) {
77587                 case 89 /* ExportKeyword */:
77588                 case 84 /* DefaultKeyword */:
77589                     // ES6 export and default modifiers are elided when inside a namespace.
77590                     return currentNamespace ? undefined : node;
77591                 case 119 /* PublicKeyword */:
77592                 case 117 /* PrivateKeyword */:
77593                 case 118 /* ProtectedKeyword */:
77594                 case 122 /* AbstractKeyword */:
77595                 case 81 /* ConstKeyword */:
77596                 case 130 /* DeclareKeyword */:
77597                 case 138 /* ReadonlyKeyword */:
77598                 // TypeScript accessibility and readonly modifiers are elided
77599                 // falls through
77600                 case 174 /* ArrayType */:
77601                 case 175 /* TupleType */:
77602                 case 176 /* OptionalType */:
77603                 case 177 /* RestType */:
77604                 case 173 /* TypeLiteral */:
77605                 case 168 /* TypePredicate */:
77606                 case 155 /* TypeParameter */:
77607                 case 125 /* AnyKeyword */:
77608                 case 148 /* UnknownKeyword */:
77609                 case 128 /* BooleanKeyword */:
77610                 case 143 /* StringKeyword */:
77611                 case 140 /* NumberKeyword */:
77612                 case 137 /* NeverKeyword */:
77613                 case 110 /* VoidKeyword */:
77614                 case 144 /* SymbolKeyword */:
77615                 case 171 /* ConstructorType */:
77616                 case 170 /* FunctionType */:
77617                 case 172 /* TypeQuery */:
77618                 case 169 /* TypeReference */:
77619                 case 178 /* UnionType */:
77620                 case 179 /* IntersectionType */:
77621                 case 180 /* ConditionalType */:
77622                 case 182 /* ParenthesizedType */:
77623                 case 183 /* ThisType */:
77624                 case 184 /* TypeOperator */:
77625                 case 185 /* IndexedAccessType */:
77626                 case 186 /* MappedType */:
77627                 case 187 /* LiteralType */:
77628                 // TypeScript type nodes are elided.
77629                 // falls through
77630                 case 167 /* IndexSignature */:
77631                 // TypeScript index signatures are elided.
77632                 // falls through
77633                 case 157 /* Decorator */:
77634                 // TypeScript decorators are elided. They will be emitted as part of visitClassDeclaration.
77635                 // falls through
77636                 case 247 /* TypeAliasDeclaration */:
77637                     // TypeScript type-only declarations are elided.
77638                     return undefined;
77639                 case 159 /* PropertyDeclaration */:
77640                     // TypeScript property declarations are elided. However their names are still visited, and can potentially be retained if they could have sideeffects
77641                     return visitPropertyDeclaration(node);
77642                 case 252 /* NamespaceExportDeclaration */:
77643                     // TypeScript namespace export declarations are elided.
77644                     return undefined;
77645                 case 162 /* Constructor */:
77646                     return visitConstructor(node);
77647                 case 246 /* InterfaceDeclaration */:
77648                     // TypeScript interfaces are elided, but some comments may be preserved.
77649                     // See the implementation of `getLeadingComments` in comments.ts for more details.
77650                     return ts.createNotEmittedStatement(node);
77651                 case 245 /* ClassDeclaration */:
77652                     // This may be a class declaration with TypeScript syntax extensions.
77653                     //
77654                     // TypeScript class syntax extensions include:
77655                     // - decorators
77656                     // - optional `implements` heritage clause
77657                     // - parameter property assignments in the constructor
77658                     // - index signatures
77659                     // - method overload signatures
77660                     return visitClassDeclaration(node);
77661                 case 214 /* ClassExpression */:
77662                     // This may be a class expression with TypeScript syntax extensions.
77663                     //
77664                     // TypeScript class syntax extensions include:
77665                     // - decorators
77666                     // - optional `implements` heritage clause
77667                     // - parameter property assignments in the constructor
77668                     // - index signatures
77669                     // - method overload signatures
77670                     return visitClassExpression(node);
77671                 case 279 /* HeritageClause */:
77672                     // This may be a heritage clause with TypeScript syntax extensions.
77673                     //
77674                     // TypeScript heritage clause extensions include:
77675                     // - `implements` clause
77676                     return visitHeritageClause(node);
77677                 case 216 /* ExpressionWithTypeArguments */:
77678                     // TypeScript supports type arguments on an expression in an `extends` heritage clause.
77679                     return visitExpressionWithTypeArguments(node);
77680                 case 161 /* MethodDeclaration */:
77681                     // TypeScript method declarations may have decorators, modifiers
77682                     // or type annotations.
77683                     return visitMethodDeclaration(node);
77684                 case 163 /* GetAccessor */:
77685                     // Get Accessors can have TypeScript modifiers, decorators, and type annotations.
77686                     return visitGetAccessor(node);
77687                 case 164 /* SetAccessor */:
77688                     // Set Accessors can have TypeScript modifiers and type annotations.
77689                     return visitSetAccessor(node);
77690                 case 244 /* FunctionDeclaration */:
77691                     // Typescript function declarations can have modifiers, decorators, and type annotations.
77692                     return visitFunctionDeclaration(node);
77693                 case 201 /* FunctionExpression */:
77694                     // TypeScript function expressions can have modifiers and type annotations.
77695                     return visitFunctionExpression(node);
77696                 case 202 /* ArrowFunction */:
77697                     // TypeScript arrow functions can have modifiers and type annotations.
77698                     return visitArrowFunction(node);
77699                 case 156 /* Parameter */:
77700                     // This may be a parameter declaration with TypeScript syntax extensions.
77701                     //
77702                     // TypeScript parameter declaration syntax extensions include:
77703                     // - decorators
77704                     // - accessibility modifiers
77705                     // - the question mark (?) token for optional parameters
77706                     // - type annotations
77707                     // - this parameters
77708                     return visitParameter(node);
77709                 case 200 /* ParenthesizedExpression */:
77710                     // ParenthesizedExpressions are TypeScript if their expression is a
77711                     // TypeAssertion or AsExpression
77712                     return visitParenthesizedExpression(node);
77713                 case 199 /* TypeAssertionExpression */:
77714                 case 217 /* AsExpression */:
77715                     // TypeScript type assertions are removed, but their subtrees are preserved.
77716                     return visitAssertionExpression(node);
77717                 case 196 /* CallExpression */:
77718                     return visitCallExpression(node);
77719                 case 197 /* NewExpression */:
77720                     return visitNewExpression(node);
77721                 case 198 /* TaggedTemplateExpression */:
77722                     return visitTaggedTemplateExpression(node);
77723                 case 218 /* NonNullExpression */:
77724                     // TypeScript non-null expressions are removed, but their subtrees are preserved.
77725                     return visitNonNullExpression(node);
77726                 case 248 /* EnumDeclaration */:
77727                     // TypeScript enum declarations do not exist in ES6 and must be rewritten.
77728                     return visitEnumDeclaration(node);
77729                 case 225 /* VariableStatement */:
77730                     // TypeScript namespace exports for variable statements must be transformed.
77731                     return visitVariableStatement(node);
77732                 case 242 /* VariableDeclaration */:
77733                     return visitVariableDeclaration(node);
77734                 case 249 /* ModuleDeclaration */:
77735                     // TypeScript namespace declarations must be transformed.
77736                     return visitModuleDeclaration(node);
77737                 case 253 /* ImportEqualsDeclaration */:
77738                     // TypeScript namespace or external module import.
77739                     return visitImportEqualsDeclaration(node);
77740                 case 267 /* JsxSelfClosingElement */:
77741                     return visitJsxSelfClosingElement(node);
77742                 case 268 /* JsxOpeningElement */:
77743                     return visitJsxJsxOpeningElement(node);
77744                 default:
77745                     // node contains some other TypeScript syntax
77746                     return ts.visitEachChild(node, visitor, context);
77747             }
77748         }
77749         function visitSourceFile(node) {
77750             var alwaysStrict = ts.getStrictOptionValue(compilerOptions, "alwaysStrict") &&
77751                 !(ts.isExternalModule(node) && moduleKind >= ts.ModuleKind.ES2015) &&
77752                 !ts.isJsonSourceFile(node);
77753             return ts.updateSourceFileNode(node, ts.visitLexicalEnvironment(node.statements, sourceElementVisitor, context, /*start*/ 0, alwaysStrict));
77754         }
77755         /**
77756          * Tests whether we should emit a __decorate call for a class declaration.
77757          */
77758         function shouldEmitDecorateCallForClass(node) {
77759             if (node.decorators && node.decorators.length > 0) {
77760                 return true;
77761             }
77762             var constructor = ts.getFirstConstructorWithBody(node);
77763             if (constructor) {
77764                 return ts.forEach(constructor.parameters, shouldEmitDecorateCallForParameter);
77765             }
77766             return false;
77767         }
77768         /**
77769          * Tests whether we should emit a __decorate call for a parameter declaration.
77770          */
77771         function shouldEmitDecorateCallForParameter(parameter) {
77772             return parameter.decorators !== undefined && parameter.decorators.length > 0;
77773         }
77774         function getClassFacts(node, staticProperties) {
77775             var facts = 0 /* None */;
77776             if (ts.some(staticProperties))
77777                 facts |= 1 /* HasStaticInitializedProperties */;
77778             var extendsClauseElement = ts.getEffectiveBaseTypeNode(node);
77779             if (extendsClauseElement && ts.skipOuterExpressions(extendsClauseElement.expression).kind !== 100 /* NullKeyword */)
77780                 facts |= 64 /* IsDerivedClass */;
77781             if (shouldEmitDecorateCallForClass(node))
77782                 facts |= 2 /* HasConstructorDecorators */;
77783             if (ts.childIsDecorated(node))
77784                 facts |= 4 /* HasMemberDecorators */;
77785             if (isExportOfNamespace(node))
77786                 facts |= 8 /* IsExportOfNamespace */;
77787             else if (isDefaultExternalModuleExport(node))
77788                 facts |= 32 /* IsDefaultExternalExport */;
77789             else if (isNamedExternalModuleExport(node))
77790                 facts |= 16 /* IsNamedExternalExport */;
77791             if (languageVersion <= 1 /* ES5 */ && (facts & 7 /* MayNeedImmediatelyInvokedFunctionExpression */))
77792                 facts |= 128 /* UseImmediatelyInvokedFunctionExpression */;
77793             return facts;
77794         }
77795         function hasTypeScriptClassSyntax(node) {
77796             return !!(node.transformFlags & 2048 /* ContainsTypeScriptClassSyntax */);
77797         }
77798         function isClassLikeDeclarationWithTypeScriptSyntax(node) {
77799             return ts.some(node.decorators)
77800                 || ts.some(node.typeParameters)
77801                 || ts.some(node.heritageClauses, hasTypeScriptClassSyntax)
77802                 || ts.some(node.members, hasTypeScriptClassSyntax);
77803         }
77804         function visitClassDeclaration(node) {
77805             if (!isClassLikeDeclarationWithTypeScriptSyntax(node) && !(currentNamespace && ts.hasModifier(node, 1 /* Export */))) {
77806                 return ts.visitEachChild(node, visitor, context);
77807             }
77808             var staticProperties = ts.getProperties(node, /*requireInitializer*/ true, /*isStatic*/ true);
77809             var facts = getClassFacts(node, staticProperties);
77810             if (facts & 128 /* UseImmediatelyInvokedFunctionExpression */) {
77811                 context.startLexicalEnvironment();
77812             }
77813             var name = node.name || (facts & 5 /* NeedsName */ ? ts.getGeneratedNameForNode(node) : undefined);
77814             var classStatement = facts & 2 /* HasConstructorDecorators */
77815                 ? createClassDeclarationHeadWithDecorators(node, name)
77816                 : createClassDeclarationHeadWithoutDecorators(node, name, facts);
77817             var statements = [classStatement];
77818             // Write any decorators of the node.
77819             addClassElementDecorationStatements(statements, node, /*isStatic*/ false);
77820             addClassElementDecorationStatements(statements, node, /*isStatic*/ true);
77821             addConstructorDecorationStatement(statements, node);
77822             if (facts & 128 /* UseImmediatelyInvokedFunctionExpression */) {
77823                 // When we emit a TypeScript class down to ES5, we must wrap it in an IIFE so that the
77824                 // 'es2015' transformer can properly nest static initializers and decorators. The result
77825                 // looks something like:
77826                 //
77827                 //  var C = function () {
77828                 //      class C {
77829                 //      }
77830                 //      C.static_prop = 1;
77831                 //      return C;
77832                 //  }();
77833                 //
77834                 var closingBraceLocation = ts.createTokenRange(ts.skipTrivia(currentSourceFile.text, node.members.end), 19 /* CloseBraceToken */);
77835                 var localName = ts.getInternalName(node);
77836                 // The following partially-emitted expression exists purely to align our sourcemap
77837                 // emit with the original emitter.
77838                 var outer = ts.createPartiallyEmittedExpression(localName);
77839                 outer.end = closingBraceLocation.end;
77840                 ts.setEmitFlags(outer, 1536 /* NoComments */);
77841                 var statement = ts.createReturn(outer);
77842                 statement.pos = closingBraceLocation.pos;
77843                 ts.setEmitFlags(statement, 1536 /* NoComments */ | 384 /* NoTokenSourceMaps */);
77844                 statements.push(statement);
77845                 ts.insertStatementsAfterStandardPrologue(statements, context.endLexicalEnvironment());
77846                 var iife = ts.createImmediatelyInvokedArrowFunction(statements);
77847                 ts.setEmitFlags(iife, 33554432 /* TypeScriptClassWrapper */);
77848                 var varStatement = ts.createVariableStatement(
77849                 /*modifiers*/ undefined, ts.createVariableDeclarationList([
77850                     ts.createVariableDeclaration(ts.getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ false), 
77851                     /*type*/ undefined, iife)
77852                 ]));
77853                 ts.setOriginalNode(varStatement, node);
77854                 ts.setCommentRange(varStatement, node);
77855                 ts.setSourceMapRange(varStatement, ts.moveRangePastDecorators(node));
77856                 ts.startOnNewLine(varStatement);
77857                 statements = [varStatement];
77858             }
77859             // If the class is exported as part of a TypeScript namespace, emit the namespace export.
77860             // Otherwise, if the class was exported at the top level and was decorated, emit an export
77861             // declaration or export default for the class.
77862             if (facts & 8 /* IsExportOfNamespace */) {
77863                 addExportMemberAssignment(statements, node);
77864             }
77865             else if (facts & 128 /* UseImmediatelyInvokedFunctionExpression */ || facts & 2 /* HasConstructorDecorators */) {
77866                 if (facts & 32 /* IsDefaultExternalExport */) {
77867                     statements.push(ts.createExportDefault(ts.getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ true)));
77868                 }
77869                 else if (facts & 16 /* IsNamedExternalExport */) {
77870                     statements.push(ts.createExternalModuleExport(ts.getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ true)));
77871                 }
77872             }
77873             if (statements.length > 1) {
77874                 // Add a DeclarationMarker as a marker for the end of the declaration
77875                 statements.push(ts.createEndOfDeclarationMarker(node));
77876                 ts.setEmitFlags(classStatement, ts.getEmitFlags(classStatement) | 4194304 /* HasEndOfDeclarationMarker */);
77877             }
77878             return ts.singleOrMany(statements);
77879         }
77880         /**
77881          * Transforms a non-decorated class declaration and appends the resulting statements.
77882          *
77883          * @param node A ClassDeclaration node.
77884          * @param name The name of the class.
77885          * @param facts Precomputed facts about the class.
77886          */
77887         function createClassDeclarationHeadWithoutDecorators(node, name, facts) {
77888             //  ${modifiers} class ${name} ${heritageClauses} {
77889             //      ${members}
77890             //  }
77891             // we do not emit modifiers on the declaration if we are emitting an IIFE
77892             var modifiers = !(facts & 128 /* UseImmediatelyInvokedFunctionExpression */)
77893                 ? ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier)
77894                 : undefined;
77895             var classDeclaration = ts.createClassDeclaration(
77896             /*decorators*/ undefined, modifiers, name, 
77897             /*typeParameters*/ undefined, ts.visitNodes(node.heritageClauses, visitor, ts.isHeritageClause), transformClassMembers(node));
77898             // To better align with the old emitter, we should not emit a trailing source map
77899             // entry if the class has static properties.
77900             var emitFlags = ts.getEmitFlags(node);
77901             if (facts & 1 /* HasStaticInitializedProperties */) {
77902                 emitFlags |= 32 /* NoTrailingSourceMap */;
77903             }
77904             ts.aggregateTransformFlags(classDeclaration);
77905             ts.setTextRange(classDeclaration, node);
77906             ts.setOriginalNode(classDeclaration, node);
77907             ts.setEmitFlags(classDeclaration, emitFlags);
77908             return classDeclaration;
77909         }
77910         /**
77911          * Transforms a decorated class declaration and appends the resulting statements. If
77912          * the class requires an alias to avoid issues with double-binding, the alias is returned.
77913          */
77914         function createClassDeclarationHeadWithDecorators(node, name) {
77915             // When we emit an ES6 class that has a class decorator, we must tailor the
77916             // emit to certain specific cases.
77917             //
77918             // In the simplest case, we emit the class declaration as a let declaration, and
77919             // evaluate decorators after the close of the class body:
77920             //
77921             //  [Example 1]
77922             //  ---------------------------------------------------------------------
77923             //  TypeScript                      | Javascript
77924             //  ---------------------------------------------------------------------
77925             //  @dec                            | let C = class C {
77926             //  class C {                       | }
77927             //  }                               | C = __decorate([dec], C);
77928             //  ---------------------------------------------------------------------
77929             //  @dec                            | let C = class C {
77930             //  export class C {                | }
77931             //  }                               | C = __decorate([dec], C);
77932             //                                  | export { C };
77933             //  ---------------------------------------------------------------------
77934             //
77935             // If a class declaration contains a reference to itself *inside* of the class body,
77936             // this introduces two bindings to the class: One outside of the class body, and one
77937             // inside of the class body. If we apply decorators as in [Example 1] above, there
77938             // is the possibility that the decorator `dec` will return a new value for the
77939             // constructor, which would result in the binding inside of the class no longer
77940             // pointing to the same reference as the binding outside of the class.
77941             //
77942             // As a result, we must instead rewrite all references to the class *inside* of the
77943             // class body to instead point to a local temporary alias for the class:
77944             //
77945             //  [Example 2]
77946             //  ---------------------------------------------------------------------
77947             //  TypeScript                      | Javascript
77948             //  ---------------------------------------------------------------------
77949             //  @dec                            | let C = C_1 = class C {
77950             //  class C {                       |   static x() { return C_1.y; }
77951             //    static x() { return C.y; }    | }
77952             //    static y = 1;                 | C.y = 1;
77953             //  }                               | C = C_1 = __decorate([dec], C);
77954             //                                  | var C_1;
77955             //  ---------------------------------------------------------------------
77956             //  @dec                            | let C = class C {
77957             //  export class C {                |   static x() { return C_1.y; }
77958             //    static x() { return C.y; }    | }
77959             //    static y = 1;                 | C.y = 1;
77960             //  }                               | C = C_1 = __decorate([dec], C);
77961             //                                  | export { C };
77962             //                                  | var C_1;
77963             //  ---------------------------------------------------------------------
77964             //
77965             // If a class declaration is the default export of a module, we instead emit
77966             // the export after the decorated declaration:
77967             //
77968             //  [Example 3]
77969             //  ---------------------------------------------------------------------
77970             //  TypeScript                      | Javascript
77971             //  ---------------------------------------------------------------------
77972             //  @dec                            | let default_1 = class {
77973             //  export default class {          | }
77974             //  }                               | default_1 = __decorate([dec], default_1);
77975             //                                  | export default default_1;
77976             //  ---------------------------------------------------------------------
77977             //  @dec                            | let C = class C {
77978             //  export default class C {        | }
77979             //  }                               | C = __decorate([dec], C);
77980             //                                  | export default C;
77981             //  ---------------------------------------------------------------------
77982             //
77983             // If the class declaration is the default export and a reference to itself
77984             // inside of the class body, we must emit both an alias for the class *and*
77985             // move the export after the declaration:
77986             //
77987             //  [Example 4]
77988             //  ---------------------------------------------------------------------
77989             //  TypeScript                      | Javascript
77990             //  ---------------------------------------------------------------------
77991             //  @dec                            | let C = class C {
77992             //  export default class C {        |   static x() { return C_1.y; }
77993             //    static x() { return C.y; }    | }
77994             //    static y = 1;                 | C.y = 1;
77995             //  }                               | C = C_1 = __decorate([dec], C);
77996             //                                  | export default C;
77997             //                                  | var C_1;
77998             //  ---------------------------------------------------------------------
77999             //
78000             var location = ts.moveRangePastDecorators(node);
78001             var classAlias = getClassAliasIfNeeded(node);
78002             var declName = ts.getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ true);
78003             //  ... = class ${name} ${heritageClauses} {
78004             //      ${members}
78005             //  }
78006             var heritageClauses = ts.visitNodes(node.heritageClauses, visitor, ts.isHeritageClause);
78007             var members = transformClassMembers(node);
78008             var classExpression = ts.createClassExpression(/*modifiers*/ undefined, name, /*typeParameters*/ undefined, heritageClauses, members);
78009             ts.aggregateTransformFlags(classExpression);
78010             ts.setOriginalNode(classExpression, node);
78011             ts.setTextRange(classExpression, location);
78012             //  let ${name} = ${classExpression} where name is either declaredName if the class doesn't contain self-reference
78013             //                                         or decoratedClassAlias if the class contain self-reference.
78014             var statement = ts.createVariableStatement(
78015             /*modifiers*/ undefined, ts.createVariableDeclarationList([
78016                 ts.createVariableDeclaration(declName, 
78017                 /*type*/ undefined, classAlias ? ts.createAssignment(classAlias, classExpression) : classExpression)
78018             ], 1 /* Let */));
78019             ts.setOriginalNode(statement, node);
78020             ts.setTextRange(statement, location);
78021             ts.setCommentRange(statement, node);
78022             return statement;
78023         }
78024         function visitClassExpression(node) {
78025             if (!isClassLikeDeclarationWithTypeScriptSyntax(node)) {
78026                 return ts.visitEachChild(node, visitor, context);
78027             }
78028             var classExpression = ts.createClassExpression(
78029             /*modifiers*/ undefined, node.name, 
78030             /*typeParameters*/ undefined, ts.visitNodes(node.heritageClauses, visitor, ts.isHeritageClause), transformClassMembers(node));
78031             ts.aggregateTransformFlags(classExpression);
78032             ts.setOriginalNode(classExpression, node);
78033             ts.setTextRange(classExpression, node);
78034             return classExpression;
78035         }
78036         /**
78037          * Transforms the members of a class.
78038          *
78039          * @param node The current class.
78040          */
78041         function transformClassMembers(node) {
78042             var members = [];
78043             var constructor = ts.getFirstConstructorWithBody(node);
78044             var parametersWithPropertyAssignments = constructor &&
78045                 ts.filter(constructor.parameters, function (p) { return ts.isParameterPropertyDeclaration(p, constructor); });
78046             if (parametersWithPropertyAssignments) {
78047                 for (var _i = 0, parametersWithPropertyAssignments_1 = parametersWithPropertyAssignments; _i < parametersWithPropertyAssignments_1.length; _i++) {
78048                     var parameter = parametersWithPropertyAssignments_1[_i];
78049                     if (ts.isIdentifier(parameter.name)) {
78050                         members.push(ts.setOriginalNode(ts.aggregateTransformFlags(ts.createProperty(
78051                         /*decorators*/ undefined, 
78052                         /*modifiers*/ undefined, parameter.name, 
78053                         /*questionOrExclamationToken*/ undefined, 
78054                         /*type*/ undefined, 
78055                         /*initializer*/ undefined)), parameter));
78056                     }
78057                 }
78058             }
78059             ts.addRange(members, ts.visitNodes(node.members, classElementVisitor, ts.isClassElement));
78060             return ts.setTextRange(ts.createNodeArray(members), /*location*/ node.members);
78061         }
78062         /**
78063          * Gets either the static or instance members of a class that are decorated, or have
78064          * parameters that are decorated.
78065          *
78066          * @param node The class containing the member.
78067          * @param isStatic A value indicating whether to retrieve static or instance members of
78068          *                 the class.
78069          */
78070         function getDecoratedClassElements(node, isStatic) {
78071             return ts.filter(node.members, isStatic ? function (m) { return isStaticDecoratedClassElement(m, node); } : function (m) { return isInstanceDecoratedClassElement(m, node); });
78072         }
78073         /**
78074          * Determines whether a class member is a static member of a class that is decorated, or
78075          * has parameters that are decorated.
78076          *
78077          * @param member The class member.
78078          */
78079         function isStaticDecoratedClassElement(member, parent) {
78080             return isDecoratedClassElement(member, /*isStatic*/ true, parent);
78081         }
78082         /**
78083          * Determines whether a class member is an instance member of a class that is decorated,
78084          * or has parameters that are decorated.
78085          *
78086          * @param member The class member.
78087          */
78088         function isInstanceDecoratedClassElement(member, parent) {
78089             return isDecoratedClassElement(member, /*isStatic*/ false, parent);
78090         }
78091         /**
78092          * Determines whether a class member is either a static or an instance member of a class
78093          * that is decorated, or has parameters that are decorated.
78094          *
78095          * @param member The class member.
78096          */
78097         function isDecoratedClassElement(member, isStatic, parent) {
78098             return ts.nodeOrChildIsDecorated(member, parent)
78099                 && isStatic === ts.hasModifier(member, 32 /* Static */);
78100         }
78101         /**
78102          * Gets an array of arrays of decorators for the parameters of a function-like node.
78103          * The offset into the result array should correspond to the offset of the parameter.
78104          *
78105          * @param node The function-like node.
78106          */
78107         function getDecoratorsOfParameters(node) {
78108             var decorators;
78109             if (node) {
78110                 var parameters = node.parameters;
78111                 var firstParameterIsThis = parameters.length > 0 && ts.parameterIsThisKeyword(parameters[0]);
78112                 var firstParameterOffset = firstParameterIsThis ? 1 : 0;
78113                 var numParameters = firstParameterIsThis ? parameters.length - 1 : parameters.length;
78114                 for (var i = 0; i < numParameters; i++) {
78115                     var parameter = parameters[i + firstParameterOffset];
78116                     if (decorators || parameter.decorators) {
78117                         if (!decorators) {
78118                             decorators = new Array(numParameters);
78119                         }
78120                         decorators[i] = parameter.decorators;
78121                     }
78122                 }
78123             }
78124             return decorators;
78125         }
78126         /**
78127          * Gets an AllDecorators object containing the decorators for the class and the decorators for the
78128          * parameters of the constructor of the class.
78129          *
78130          * @param node The class node.
78131          */
78132         function getAllDecoratorsOfConstructor(node) {
78133             var decorators = node.decorators;
78134             var parameters = getDecoratorsOfParameters(ts.getFirstConstructorWithBody(node));
78135             if (!decorators && !parameters) {
78136                 return undefined;
78137             }
78138             return {
78139                 decorators: decorators,
78140                 parameters: parameters
78141             };
78142         }
78143         /**
78144          * Gets an AllDecorators object containing the decorators for the member and its parameters.
78145          *
78146          * @param node The class node that contains the member.
78147          * @param member The class member.
78148          */
78149         function getAllDecoratorsOfClassElement(node, member) {
78150             switch (member.kind) {
78151                 case 163 /* GetAccessor */:
78152                 case 164 /* SetAccessor */:
78153                     return getAllDecoratorsOfAccessors(node, member);
78154                 case 161 /* MethodDeclaration */:
78155                     return getAllDecoratorsOfMethod(member);
78156                 case 159 /* PropertyDeclaration */:
78157                     return getAllDecoratorsOfProperty(member);
78158                 default:
78159                     return undefined;
78160             }
78161         }
78162         /**
78163          * Gets an AllDecorators object containing the decorators for the accessor and its parameters.
78164          *
78165          * @param node The class node that contains the accessor.
78166          * @param accessor The class accessor member.
78167          */
78168         function getAllDecoratorsOfAccessors(node, accessor) {
78169             if (!accessor.body) {
78170                 return undefined;
78171             }
78172             var _a = ts.getAllAccessorDeclarations(node.members, accessor), firstAccessor = _a.firstAccessor, secondAccessor = _a.secondAccessor, setAccessor = _a.setAccessor;
78173             var firstAccessorWithDecorators = firstAccessor.decorators ? firstAccessor : secondAccessor && secondAccessor.decorators ? secondAccessor : undefined;
78174             if (!firstAccessorWithDecorators || accessor !== firstAccessorWithDecorators) {
78175                 return undefined;
78176             }
78177             var decorators = firstAccessorWithDecorators.decorators;
78178             var parameters = getDecoratorsOfParameters(setAccessor);
78179             if (!decorators && !parameters) {
78180                 return undefined;
78181             }
78182             return { decorators: decorators, parameters: parameters };
78183         }
78184         /**
78185          * Gets an AllDecorators object containing the decorators for the method and its parameters.
78186          *
78187          * @param method The class method member.
78188          */
78189         function getAllDecoratorsOfMethod(method) {
78190             if (!method.body) {
78191                 return undefined;
78192             }
78193             var decorators = method.decorators;
78194             var parameters = getDecoratorsOfParameters(method);
78195             if (!decorators && !parameters) {
78196                 return undefined;
78197             }
78198             return { decorators: decorators, parameters: parameters };
78199         }
78200         /**
78201          * Gets an AllDecorators object containing the decorators for the property.
78202          *
78203          * @param property The class property member.
78204          */
78205         function getAllDecoratorsOfProperty(property) {
78206             var decorators = property.decorators;
78207             if (!decorators) {
78208                 return undefined;
78209             }
78210             return { decorators: decorators };
78211         }
78212         /**
78213          * Transforms all of the decorators for a declaration into an array of expressions.
78214          *
78215          * @param node The declaration node.
78216          * @param allDecorators An object containing all of the decorators for the declaration.
78217          */
78218         function transformAllDecoratorsOfDeclaration(node, container, allDecorators) {
78219             if (!allDecorators) {
78220                 return undefined;
78221             }
78222             var decoratorExpressions = [];
78223             ts.addRange(decoratorExpressions, ts.map(allDecorators.decorators, transformDecorator));
78224             ts.addRange(decoratorExpressions, ts.flatMap(allDecorators.parameters, transformDecoratorsOfParameter));
78225             addTypeMetadata(node, container, decoratorExpressions);
78226             return decoratorExpressions;
78227         }
78228         /**
78229          * Generates statements used to apply decorators to either the static or instance members
78230          * of a class.
78231          *
78232          * @param node The class node.
78233          * @param isStatic A value indicating whether to generate statements for static or
78234          *                 instance members.
78235          */
78236         function addClassElementDecorationStatements(statements, node, isStatic) {
78237             ts.addRange(statements, ts.map(generateClassElementDecorationExpressions(node, isStatic), expressionToStatement));
78238         }
78239         /**
78240          * Generates expressions used to apply decorators to either the static or instance members
78241          * of a class.
78242          *
78243          * @param node The class node.
78244          * @param isStatic A value indicating whether to generate expressions for static or
78245          *                 instance members.
78246          */
78247         function generateClassElementDecorationExpressions(node, isStatic) {
78248             var members = getDecoratedClassElements(node, isStatic);
78249             var expressions;
78250             for (var _i = 0, members_6 = members; _i < members_6.length; _i++) {
78251                 var member = members_6[_i];
78252                 var expression = generateClassElementDecorationExpression(node, member);
78253                 if (expression) {
78254                     if (!expressions) {
78255                         expressions = [expression];
78256                     }
78257                     else {
78258                         expressions.push(expression);
78259                     }
78260                 }
78261             }
78262             return expressions;
78263         }
78264         /**
78265          * Generates an expression used to evaluate class element decorators at runtime.
78266          *
78267          * @param node The class node that contains the member.
78268          * @param member The class member.
78269          */
78270         function generateClassElementDecorationExpression(node, member) {
78271             var allDecorators = getAllDecoratorsOfClassElement(node, member);
78272             var decoratorExpressions = transformAllDecoratorsOfDeclaration(member, node, allDecorators);
78273             if (!decoratorExpressions) {
78274                 return undefined;
78275             }
78276             // Emit the call to __decorate. Given the following:
78277             //
78278             //   class C {
78279             //     @dec method(@dec2 x) {}
78280             //     @dec get accessor() {}
78281             //     @dec prop;
78282             //   }
78283             //
78284             // The emit for a method is:
78285             //
78286             //   __decorate([
78287             //       dec,
78288             //       __param(0, dec2),
78289             //       __metadata("design:type", Function),
78290             //       __metadata("design:paramtypes", [Object]),
78291             //       __metadata("design:returntype", void 0)
78292             //   ], C.prototype, "method", null);
78293             //
78294             // The emit for an accessor is:
78295             //
78296             //   __decorate([
78297             //       dec
78298             //   ], C.prototype, "accessor", null);
78299             //
78300             // The emit for a property is:
78301             //
78302             //   __decorate([
78303             //       dec
78304             //   ], C.prototype, "prop");
78305             //
78306             var prefix = getClassMemberPrefix(node, member);
78307             var memberName = getExpressionForPropertyName(member, /*generateNameForComputedPropertyName*/ true);
78308             var descriptor = languageVersion > 0 /* ES3 */
78309                 ? member.kind === 159 /* PropertyDeclaration */
78310                     // We emit `void 0` here to indicate to `__decorate` that it can invoke `Object.defineProperty` directly, but that it
78311                     // should not invoke `Object.getOwnPropertyDescriptor`.
78312                     ? ts.createVoidZero()
78313                     // We emit `null` here to indicate to `__decorate` that it can invoke `Object.getOwnPropertyDescriptor` directly.
78314                     // We have this extra argument here so that we can inject an explicit property descriptor at a later date.
78315                     : ts.createNull()
78316                 : undefined;
78317             var helper = createDecorateHelper(context, decoratorExpressions, prefix, memberName, descriptor, ts.moveRangePastDecorators(member));
78318             ts.setEmitFlags(helper, 1536 /* NoComments */);
78319             return helper;
78320         }
78321         /**
78322          * Generates a __decorate helper call for a class constructor.
78323          *
78324          * @param node The class node.
78325          */
78326         function addConstructorDecorationStatement(statements, node) {
78327             var expression = generateConstructorDecorationExpression(node);
78328             if (expression) {
78329                 statements.push(ts.setOriginalNode(ts.createExpressionStatement(expression), node));
78330             }
78331         }
78332         /**
78333          * Generates a __decorate helper call for a class constructor.
78334          *
78335          * @param node The class node.
78336          */
78337         function generateConstructorDecorationExpression(node) {
78338             var allDecorators = getAllDecoratorsOfConstructor(node);
78339             var decoratorExpressions = transformAllDecoratorsOfDeclaration(node, node, allDecorators);
78340             if (!decoratorExpressions) {
78341                 return undefined;
78342             }
78343             var classAlias = classAliases && classAliases[ts.getOriginalNodeId(node)];
78344             var localName = ts.getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ true);
78345             var decorate = createDecorateHelper(context, decoratorExpressions, localName);
78346             var expression = ts.createAssignment(localName, classAlias ? ts.createAssignment(classAlias, decorate) : decorate);
78347             ts.setEmitFlags(expression, 1536 /* NoComments */);
78348             ts.setSourceMapRange(expression, ts.moveRangePastDecorators(node));
78349             return expression;
78350         }
78351         /**
78352          * Transforms a decorator into an expression.
78353          *
78354          * @param decorator The decorator node.
78355          */
78356         function transformDecorator(decorator) {
78357             return ts.visitNode(decorator.expression, visitor, ts.isExpression);
78358         }
78359         /**
78360          * Transforms the decorators of a parameter.
78361          *
78362          * @param decorators The decorators for the parameter at the provided offset.
78363          * @param parameterOffset The offset of the parameter.
78364          */
78365         function transformDecoratorsOfParameter(decorators, parameterOffset) {
78366             var expressions;
78367             if (decorators) {
78368                 expressions = [];
78369                 for (var _i = 0, decorators_1 = decorators; _i < decorators_1.length; _i++) {
78370                     var decorator = decorators_1[_i];
78371                     var helper = createParamHelper(context, transformDecorator(decorator), parameterOffset, 
78372                     /*location*/ decorator.expression);
78373                     ts.setEmitFlags(helper, 1536 /* NoComments */);
78374                     expressions.push(helper);
78375                 }
78376             }
78377             return expressions;
78378         }
78379         /**
78380          * Adds optional type metadata for a declaration.
78381          *
78382          * @param node The declaration node.
78383          * @param decoratorExpressions The destination array to which to add new decorator expressions.
78384          */
78385         function addTypeMetadata(node, container, decoratorExpressions) {
78386             if (USE_NEW_TYPE_METADATA_FORMAT) {
78387                 addNewTypeMetadata(node, container, decoratorExpressions);
78388             }
78389             else {
78390                 addOldTypeMetadata(node, container, decoratorExpressions);
78391             }
78392         }
78393         function addOldTypeMetadata(node, container, decoratorExpressions) {
78394             if (compilerOptions.emitDecoratorMetadata) {
78395                 if (shouldAddTypeMetadata(node)) {
78396                     decoratorExpressions.push(createMetadataHelper(context, "design:type", serializeTypeOfNode(node)));
78397                 }
78398                 if (shouldAddParamTypesMetadata(node)) {
78399                     decoratorExpressions.push(createMetadataHelper(context, "design:paramtypes", serializeParameterTypesOfNode(node, container)));
78400                 }
78401                 if (shouldAddReturnTypeMetadata(node)) {
78402                     decoratorExpressions.push(createMetadataHelper(context, "design:returntype", serializeReturnTypeOfNode(node)));
78403                 }
78404             }
78405         }
78406         function addNewTypeMetadata(node, container, decoratorExpressions) {
78407             if (compilerOptions.emitDecoratorMetadata) {
78408                 var properties = void 0;
78409                 if (shouldAddTypeMetadata(node)) {
78410                     (properties || (properties = [])).push(ts.createPropertyAssignment("type", ts.createArrowFunction(/*modifiers*/ undefined, /*typeParameters*/ undefined, [], /*type*/ undefined, ts.createToken(38 /* EqualsGreaterThanToken */), serializeTypeOfNode(node))));
78411                 }
78412                 if (shouldAddParamTypesMetadata(node)) {
78413                     (properties || (properties = [])).push(ts.createPropertyAssignment("paramTypes", ts.createArrowFunction(/*modifiers*/ undefined, /*typeParameters*/ undefined, [], /*type*/ undefined, ts.createToken(38 /* EqualsGreaterThanToken */), serializeParameterTypesOfNode(node, container))));
78414                 }
78415                 if (shouldAddReturnTypeMetadata(node)) {
78416                     (properties || (properties = [])).push(ts.createPropertyAssignment("returnType", ts.createArrowFunction(/*modifiers*/ undefined, /*typeParameters*/ undefined, [], /*type*/ undefined, ts.createToken(38 /* EqualsGreaterThanToken */), serializeReturnTypeOfNode(node))));
78417                 }
78418                 if (properties) {
78419                     decoratorExpressions.push(createMetadataHelper(context, "design:typeinfo", ts.createObjectLiteral(properties, /*multiLine*/ true)));
78420                 }
78421             }
78422         }
78423         /**
78424          * Determines whether to emit the "design:type" metadata based on the node's kind.
78425          * The caller should have already tested whether the node has decorators and whether the
78426          * emitDecoratorMetadata compiler option is set.
78427          *
78428          * @param node The node to test.
78429          */
78430         function shouldAddTypeMetadata(node) {
78431             var kind = node.kind;
78432             return kind === 161 /* MethodDeclaration */
78433                 || kind === 163 /* GetAccessor */
78434                 || kind === 164 /* SetAccessor */
78435                 || kind === 159 /* PropertyDeclaration */;
78436         }
78437         /**
78438          * Determines whether to emit the "design:returntype" metadata based on the node's kind.
78439          * The caller should have already tested whether the node has decorators and whether the
78440          * emitDecoratorMetadata compiler option is set.
78441          *
78442          * @param node The node to test.
78443          */
78444         function shouldAddReturnTypeMetadata(node) {
78445             return node.kind === 161 /* MethodDeclaration */;
78446         }
78447         /**
78448          * Determines whether to emit the "design:paramtypes" metadata based on the node's kind.
78449          * The caller should have already tested whether the node has decorators and whether the
78450          * emitDecoratorMetadata compiler option is set.
78451          *
78452          * @param node The node to test.
78453          */
78454         function shouldAddParamTypesMetadata(node) {
78455             switch (node.kind) {
78456                 case 245 /* ClassDeclaration */:
78457                 case 214 /* ClassExpression */:
78458                     return ts.getFirstConstructorWithBody(node) !== undefined;
78459                 case 161 /* MethodDeclaration */:
78460                 case 163 /* GetAccessor */:
78461                 case 164 /* SetAccessor */:
78462                     return true;
78463             }
78464             return false;
78465         }
78466         function getAccessorTypeNode(node) {
78467             var accessors = resolver.getAllAccessorDeclarations(node);
78468             return accessors.setAccessor && ts.getSetAccessorTypeAnnotationNode(accessors.setAccessor)
78469                 || accessors.getAccessor && ts.getEffectiveReturnTypeNode(accessors.getAccessor);
78470         }
78471         /**
78472          * Serializes the type of a node for use with decorator type metadata.
78473          *
78474          * @param node The node that should have its type serialized.
78475          */
78476         function serializeTypeOfNode(node) {
78477             switch (node.kind) {
78478                 case 159 /* PropertyDeclaration */:
78479                 case 156 /* Parameter */:
78480                     return serializeTypeNode(node.type);
78481                 case 164 /* SetAccessor */:
78482                 case 163 /* GetAccessor */:
78483                     return serializeTypeNode(getAccessorTypeNode(node));
78484                 case 245 /* ClassDeclaration */:
78485                 case 214 /* ClassExpression */:
78486                 case 161 /* MethodDeclaration */:
78487                     return ts.createIdentifier("Function");
78488                 default:
78489                     return ts.createVoidZero();
78490             }
78491         }
78492         /**
78493          * Serializes the types of the parameters of a node for use with decorator type metadata.
78494          *
78495          * @param node The node that should have its parameter types serialized.
78496          */
78497         function serializeParameterTypesOfNode(node, container) {
78498             var valueDeclaration = ts.isClassLike(node)
78499                 ? ts.getFirstConstructorWithBody(node)
78500                 : ts.isFunctionLike(node) && ts.nodeIsPresent(node.body)
78501                     ? node
78502                     : undefined;
78503             var expressions = [];
78504             if (valueDeclaration) {
78505                 var parameters = getParametersOfDecoratedDeclaration(valueDeclaration, container);
78506                 var numParameters = parameters.length;
78507                 for (var i = 0; i < numParameters; i++) {
78508                     var parameter = parameters[i];
78509                     if (i === 0 && ts.isIdentifier(parameter.name) && parameter.name.escapedText === "this") {
78510                         continue;
78511                     }
78512                     if (parameter.dotDotDotToken) {
78513                         expressions.push(serializeTypeNode(ts.getRestParameterElementType(parameter.type)));
78514                     }
78515                     else {
78516                         expressions.push(serializeTypeOfNode(parameter));
78517                     }
78518                 }
78519             }
78520             return ts.createArrayLiteral(expressions);
78521         }
78522         function getParametersOfDecoratedDeclaration(node, container) {
78523             if (container && node.kind === 163 /* GetAccessor */) {
78524                 var setAccessor = ts.getAllAccessorDeclarations(container.members, node).setAccessor;
78525                 if (setAccessor) {
78526                     return setAccessor.parameters;
78527                 }
78528             }
78529             return node.parameters;
78530         }
78531         /**
78532          * Serializes the return type of a node for use with decorator type metadata.
78533          *
78534          * @param node The node that should have its return type serialized.
78535          */
78536         function serializeReturnTypeOfNode(node) {
78537             if (ts.isFunctionLike(node) && node.type) {
78538                 return serializeTypeNode(node.type);
78539             }
78540             else if (ts.isAsyncFunction(node)) {
78541                 return ts.createIdentifier("Promise");
78542             }
78543             return ts.createVoidZero();
78544         }
78545         /**
78546          * Serializes a type node for use with decorator type metadata.
78547          *
78548          * Types are serialized in the following fashion:
78549          * - Void types point to "undefined" (e.g. "void 0")
78550          * - Function and Constructor types point to the global "Function" constructor.
78551          * - Interface types with a call or construct signature types point to the global
78552          *   "Function" constructor.
78553          * - Array and Tuple types point to the global "Array" constructor.
78554          * - Type predicates and booleans point to the global "Boolean" constructor.
78555          * - String literal types and strings point to the global "String" constructor.
78556          * - Enum and number types point to the global "Number" constructor.
78557          * - Symbol types point to the global "Symbol" constructor.
78558          * - Type references to classes (or class-like variables) point to the constructor for the class.
78559          * - Anything else points to the global "Object" constructor.
78560          *
78561          * @param node The type node to serialize.
78562          */
78563         function serializeTypeNode(node) {
78564             if (node === undefined) {
78565                 return ts.createIdentifier("Object");
78566             }
78567             switch (node.kind) {
78568                 case 110 /* VoidKeyword */:
78569                 case 146 /* UndefinedKeyword */:
78570                 case 100 /* NullKeyword */:
78571                 case 137 /* NeverKeyword */:
78572                     return ts.createVoidZero();
78573                 case 182 /* ParenthesizedType */:
78574                     return serializeTypeNode(node.type);
78575                 case 170 /* FunctionType */:
78576                 case 171 /* ConstructorType */:
78577                     return ts.createIdentifier("Function");
78578                 case 174 /* ArrayType */:
78579                 case 175 /* TupleType */:
78580                     return ts.createIdentifier("Array");
78581                 case 168 /* TypePredicate */:
78582                 case 128 /* BooleanKeyword */:
78583                     return ts.createIdentifier("Boolean");
78584                 case 143 /* StringKeyword */:
78585                     return ts.createIdentifier("String");
78586                 case 141 /* ObjectKeyword */:
78587                     return ts.createIdentifier("Object");
78588                 case 187 /* LiteralType */:
78589                     switch (node.literal.kind) {
78590                         case 10 /* StringLiteral */:
78591                             return ts.createIdentifier("String");
78592                         case 207 /* PrefixUnaryExpression */:
78593                         case 8 /* NumericLiteral */:
78594                             return ts.createIdentifier("Number");
78595                         case 9 /* BigIntLiteral */:
78596                             return getGlobalBigIntNameWithFallback();
78597                         case 106 /* TrueKeyword */:
78598                         case 91 /* FalseKeyword */:
78599                             return ts.createIdentifier("Boolean");
78600                         default:
78601                             return ts.Debug.failBadSyntaxKind(node.literal);
78602                     }
78603                 case 140 /* NumberKeyword */:
78604                     return ts.createIdentifier("Number");
78605                 case 151 /* BigIntKeyword */:
78606                     return getGlobalBigIntNameWithFallback();
78607                 case 144 /* SymbolKeyword */:
78608                     return languageVersion < 2 /* ES2015 */
78609                         ? getGlobalSymbolNameWithFallback()
78610                         : ts.createIdentifier("Symbol");
78611                 case 169 /* TypeReference */:
78612                     return serializeTypeReferenceNode(node);
78613                 case 179 /* IntersectionType */:
78614                 case 178 /* UnionType */:
78615                     return serializeTypeList(node.types);
78616                 case 180 /* ConditionalType */:
78617                     return serializeTypeList([node.trueType, node.falseType]);
78618                 case 184 /* TypeOperator */:
78619                     if (node.operator === 138 /* ReadonlyKeyword */) {
78620                         return serializeTypeNode(node.type);
78621                     }
78622                     break;
78623                 case 172 /* TypeQuery */:
78624                 case 185 /* IndexedAccessType */:
78625                 case 186 /* MappedType */:
78626                 case 173 /* TypeLiteral */:
78627                 case 125 /* AnyKeyword */:
78628                 case 148 /* UnknownKeyword */:
78629                 case 183 /* ThisType */:
78630                 case 188 /* ImportType */:
78631                     break;
78632                 // handle JSDoc types from an invalid parse
78633                 case 295 /* JSDocAllType */:
78634                 case 296 /* JSDocUnknownType */:
78635                 case 300 /* JSDocFunctionType */:
78636                 case 301 /* JSDocVariadicType */:
78637                 case 302 /* JSDocNamepathType */:
78638                     break;
78639                 case 297 /* JSDocNullableType */:
78640                 case 298 /* JSDocNonNullableType */:
78641                 case 299 /* JSDocOptionalType */:
78642                     return serializeTypeNode(node.type);
78643                 default:
78644                     return ts.Debug.failBadSyntaxKind(node);
78645             }
78646             return ts.createIdentifier("Object");
78647         }
78648         function serializeTypeList(types) {
78649             // Note when updating logic here also update getEntityNameForDecoratorMetadata
78650             // so that aliases can be marked as referenced
78651             var serializedUnion;
78652             for (var _i = 0, types_21 = types; _i < types_21.length; _i++) {
78653                 var typeNode = types_21[_i];
78654                 while (typeNode.kind === 182 /* ParenthesizedType */) {
78655                     typeNode = typeNode.type; // Skip parens if need be
78656                 }
78657                 if (typeNode.kind === 137 /* NeverKeyword */) {
78658                     continue; // Always elide `never` from the union/intersection if possible
78659                 }
78660                 if (!strictNullChecks && (typeNode.kind === 100 /* NullKeyword */ || typeNode.kind === 146 /* UndefinedKeyword */)) {
78661                     continue; // Elide null and undefined from unions for metadata, just like what we did prior to the implementation of strict null checks
78662                 }
78663                 var serializedIndividual = serializeTypeNode(typeNode);
78664                 if (ts.isIdentifier(serializedIndividual) && serializedIndividual.escapedText === "Object") {
78665                     // One of the individual is global object, return immediately
78666                     return serializedIndividual;
78667                 }
78668                 // If there exists union that is not void 0 expression, check if the the common type is identifier.
78669                 // anything more complex and we will just default to Object
78670                 else if (serializedUnion) {
78671                     // Different types
78672                     if (!ts.isIdentifier(serializedUnion) ||
78673                         !ts.isIdentifier(serializedIndividual) ||
78674                         serializedUnion.escapedText !== serializedIndividual.escapedText) {
78675                         return ts.createIdentifier("Object");
78676                     }
78677                 }
78678                 else {
78679                     // Initialize the union type
78680                     serializedUnion = serializedIndividual;
78681                 }
78682             }
78683             // If we were able to find common type, use it
78684             return serializedUnion || ts.createVoidZero(); // Fallback is only hit if all union constituients are null/undefined/never
78685         }
78686         /**
78687          * Serializes a TypeReferenceNode to an appropriate JS constructor value for use with
78688          * decorator type metadata.
78689          *
78690          * @param node The type reference node.
78691          */
78692         function serializeTypeReferenceNode(node) {
78693             var kind = resolver.getTypeReferenceSerializationKind(node.typeName, currentNameScope || currentLexicalScope);
78694             switch (kind) {
78695                 case ts.TypeReferenceSerializationKind.Unknown:
78696                     // From conditional type type reference that cannot be resolved is Similar to any or unknown
78697                     if (ts.findAncestor(node, function (n) { return n.parent && ts.isConditionalTypeNode(n.parent) && (n.parent.trueType === n || n.parent.falseType === n); })) {
78698                         return ts.createIdentifier("Object");
78699                     }
78700                     var serialized = serializeEntityNameAsExpressionFallback(node.typeName);
78701                     var temp = ts.createTempVariable(hoistVariableDeclaration);
78702                     return ts.createConditional(ts.createTypeCheck(ts.createAssignment(temp, serialized), "function"), temp, ts.createIdentifier("Object"));
78703                 case ts.TypeReferenceSerializationKind.TypeWithConstructSignatureAndValue:
78704                     return serializeEntityNameAsExpression(node.typeName);
78705                 case ts.TypeReferenceSerializationKind.VoidNullableOrNeverType:
78706                     return ts.createVoidZero();
78707                 case ts.TypeReferenceSerializationKind.BigIntLikeType:
78708                     return getGlobalBigIntNameWithFallback();
78709                 case ts.TypeReferenceSerializationKind.BooleanType:
78710                     return ts.createIdentifier("Boolean");
78711                 case ts.TypeReferenceSerializationKind.NumberLikeType:
78712                     return ts.createIdentifier("Number");
78713                 case ts.TypeReferenceSerializationKind.StringLikeType:
78714                     return ts.createIdentifier("String");
78715                 case ts.TypeReferenceSerializationKind.ArrayLikeType:
78716                     return ts.createIdentifier("Array");
78717                 case ts.TypeReferenceSerializationKind.ESSymbolType:
78718                     return languageVersion < 2 /* ES2015 */
78719                         ? getGlobalSymbolNameWithFallback()
78720                         : ts.createIdentifier("Symbol");
78721                 case ts.TypeReferenceSerializationKind.TypeWithCallSignature:
78722                     return ts.createIdentifier("Function");
78723                 case ts.TypeReferenceSerializationKind.Promise:
78724                     return ts.createIdentifier("Promise");
78725                 case ts.TypeReferenceSerializationKind.ObjectType:
78726                     return ts.createIdentifier("Object");
78727                 default:
78728                     return ts.Debug.assertNever(kind);
78729             }
78730         }
78731         function createCheckedValue(left, right) {
78732             return ts.createLogicalAnd(ts.createStrictInequality(ts.createTypeOf(left), ts.createLiteral("undefined")), right);
78733         }
78734         /**
78735          * Serializes an entity name which may not exist at runtime, but whose access shouldn't throw
78736          *
78737          * @param node The entity name to serialize.
78738          */
78739         function serializeEntityNameAsExpressionFallback(node) {
78740             if (node.kind === 75 /* Identifier */) {
78741                 // A -> typeof A !== undefined && A
78742                 var copied = serializeEntityNameAsExpression(node);
78743                 return createCheckedValue(copied, copied);
78744             }
78745             if (node.left.kind === 75 /* Identifier */) {
78746                 // A.B -> typeof A !== undefined && A.B
78747                 return createCheckedValue(serializeEntityNameAsExpression(node.left), serializeEntityNameAsExpression(node));
78748             }
78749             // A.B.C -> typeof A !== undefined && (_a = A.B) !== void 0 && _a.C
78750             var left = serializeEntityNameAsExpressionFallback(node.left);
78751             var temp = ts.createTempVariable(hoistVariableDeclaration);
78752             return ts.createLogicalAnd(ts.createLogicalAnd(left.left, ts.createStrictInequality(ts.createAssignment(temp, left.right), ts.createVoidZero())), ts.createPropertyAccess(temp, node.right));
78753         }
78754         /**
78755          * Serializes an entity name as an expression for decorator type metadata.
78756          *
78757          * @param node The entity name to serialize.
78758          */
78759         function serializeEntityNameAsExpression(node) {
78760             switch (node.kind) {
78761                 case 75 /* Identifier */:
78762                     // Create a clone of the name with a new parent, and treat it as if it were
78763                     // a source tree node for the purposes of the checker.
78764                     var name = ts.getMutableClone(node);
78765                     name.flags &= ~8 /* Synthesized */;
78766                     name.original = undefined;
78767                     name.parent = ts.getParseTreeNode(currentLexicalScope); // ensure the parent is set to a parse tree node.
78768                     return name;
78769                 case 153 /* QualifiedName */:
78770                     return serializeQualifiedNameAsExpression(node);
78771             }
78772         }
78773         /**
78774          * Serializes an qualified name as an expression for decorator type metadata.
78775          *
78776          * @param node The qualified name to serialize.
78777          * @param useFallback A value indicating whether to use logical operators to test for the
78778          *                    qualified name at runtime.
78779          */
78780         function serializeQualifiedNameAsExpression(node) {
78781             return ts.createPropertyAccess(serializeEntityNameAsExpression(node.left), node.right);
78782         }
78783         /**
78784          * Gets an expression that points to the global "Symbol" constructor at runtime if it is
78785          * available.
78786          */
78787         function getGlobalSymbolNameWithFallback() {
78788             return ts.createConditional(ts.createTypeCheck(ts.createIdentifier("Symbol"), "function"), ts.createIdentifier("Symbol"), ts.createIdentifier("Object"));
78789         }
78790         /**
78791          * Gets an expression that points to the global "BigInt" constructor at runtime if it is
78792          * available.
78793          */
78794         function getGlobalBigIntNameWithFallback() {
78795             return languageVersion < 99 /* ESNext */
78796                 ? ts.createConditional(ts.createTypeCheck(ts.createIdentifier("BigInt"), "function"), ts.createIdentifier("BigInt"), ts.createIdentifier("Object"))
78797                 : ts.createIdentifier("BigInt");
78798         }
78799         /**
78800          * Gets an expression that represents a property name (for decorated properties or enums).
78801          * For a computed property, a name is generated for the node.
78802          *
78803          * @param member The member whose name should be converted into an expression.
78804          */
78805         function getExpressionForPropertyName(member, generateNameForComputedPropertyName) {
78806             var name = member.name;
78807             if (ts.isPrivateIdentifier(name)) {
78808                 return ts.createIdentifier("");
78809             }
78810             else if (ts.isComputedPropertyName(name)) {
78811                 return generateNameForComputedPropertyName && !ts.isSimpleInlineableExpression(name.expression)
78812                     ? ts.getGeneratedNameForNode(name)
78813                     : name.expression;
78814             }
78815             else if (ts.isIdentifier(name)) {
78816                 return ts.createLiteral(ts.idText(name));
78817             }
78818             else {
78819                 return ts.getSynthesizedClone(name);
78820             }
78821         }
78822         /**
78823          * Visits the property name of a class element, for use when emitting property
78824          * initializers. For a computed property on a node with decorators, a temporary
78825          * value is stored for later use.
78826          *
78827          * @param member The member whose name should be visited.
78828          */
78829         function visitPropertyNameOfClassElement(member) {
78830             var name = member.name;
78831             // Computed property names need to be transformed into a hoisted variable when they are used more than once.
78832             // The names are used more than once when:
78833             //   - the property is non-static and its initializer is moved to the constructor (when there are parameter property assignments).
78834             //   - the property has a decorator.
78835             if (ts.isComputedPropertyName(name) && ((!ts.hasStaticModifier(member) && currentClassHasParameterProperties) || ts.some(member.decorators))) {
78836                 var expression = ts.visitNode(name.expression, visitor, ts.isExpression);
78837                 var innerExpression = ts.skipPartiallyEmittedExpressions(expression);
78838                 if (!ts.isSimpleInlineableExpression(innerExpression)) {
78839                     var generatedName = ts.getGeneratedNameForNode(name);
78840                     hoistVariableDeclaration(generatedName);
78841                     return ts.updateComputedPropertyName(name, ts.createAssignment(generatedName, expression));
78842                 }
78843             }
78844             return ts.visitNode(name, visitor, ts.isPropertyName);
78845         }
78846         /**
78847          * Transforms a HeritageClause with TypeScript syntax.
78848          *
78849          * This function will only be called when one of the following conditions are met:
78850          * - The node is a non-`extends` heritage clause that should be elided.
78851          * - The node is an `extends` heritage clause that should be visited, but only allow a single type.
78852          *
78853          * @param node The HeritageClause to transform.
78854          */
78855         function visitHeritageClause(node) {
78856             if (node.token === 113 /* ImplementsKeyword */) {
78857                 // implements clauses are elided
78858                 return undefined;
78859             }
78860             return ts.visitEachChild(node, visitor, context);
78861         }
78862         /**
78863          * Transforms an ExpressionWithTypeArguments with TypeScript syntax.
78864          *
78865          * This function will only be called when one of the following conditions are met:
78866          * - The node contains type arguments that should be elided.
78867          *
78868          * @param node The ExpressionWithTypeArguments to transform.
78869          */
78870         function visitExpressionWithTypeArguments(node) {
78871             return ts.updateExpressionWithTypeArguments(node, 
78872             /*typeArguments*/ undefined, ts.visitNode(node.expression, visitor, ts.isLeftHandSideExpression));
78873         }
78874         /**
78875          * Determines whether to emit a function-like declaration. We should not emit the
78876          * declaration if it does not have a body.
78877          *
78878          * @param node The declaration node.
78879          */
78880         function shouldEmitFunctionLikeDeclaration(node) {
78881             return !ts.nodeIsMissing(node.body);
78882         }
78883         function visitPropertyDeclaration(node) {
78884             if (node.flags & 8388608 /* Ambient */) {
78885                 return undefined;
78886             }
78887             var updated = ts.updateProperty(node, 
78888             /*decorators*/ undefined, ts.visitNodes(node.modifiers, visitor, ts.isModifier), visitPropertyNameOfClassElement(node), 
78889             /*questionOrExclamationToken*/ undefined, 
78890             /*type*/ undefined, ts.visitNode(node.initializer, visitor));
78891             if (updated !== node) {
78892                 // While we emit the source map for the node after skipping decorators and modifiers,
78893                 // we need to emit the comments for the original range.
78894                 ts.setCommentRange(updated, node);
78895                 ts.setSourceMapRange(updated, ts.moveRangePastDecorators(node));
78896             }
78897             return updated;
78898         }
78899         function visitConstructor(node) {
78900             if (!shouldEmitFunctionLikeDeclaration(node)) {
78901                 return undefined;
78902             }
78903             return ts.updateConstructor(node, 
78904             /*decorators*/ undefined, 
78905             /*modifiers*/ undefined, ts.visitParameterList(node.parameters, visitor, context), transformConstructorBody(node.body, node));
78906         }
78907         function transformConstructorBody(body, constructor) {
78908             var parametersWithPropertyAssignments = constructor &&
78909                 ts.filter(constructor.parameters, function (p) { return ts.isParameterPropertyDeclaration(p, constructor); });
78910             if (!ts.some(parametersWithPropertyAssignments)) {
78911                 return ts.visitFunctionBody(body, visitor, context);
78912             }
78913             var statements = [];
78914             var indexOfFirstStatement = 0;
78915             resumeLexicalEnvironment();
78916             indexOfFirstStatement = ts.addPrologueDirectivesAndInitialSuperCall(constructor, statements, visitor);
78917             // Add parameters with property assignments. Transforms this:
78918             //
78919             //  constructor (public x, public y) {
78920             //  }
78921             //
78922             // Into this:
78923             //
78924             //  constructor (x, y) {
78925             //      this.x = x;
78926             //      this.y = y;
78927             //  }
78928             //
78929             ts.addRange(statements, ts.map(parametersWithPropertyAssignments, transformParameterWithPropertyAssignment));
78930             // Add the existing statements, skipping the initial super call.
78931             ts.addRange(statements, ts.visitNodes(body.statements, visitor, ts.isStatement, indexOfFirstStatement));
78932             // End the lexical environment.
78933             statements = ts.mergeLexicalEnvironment(statements, endLexicalEnvironment());
78934             var block = ts.createBlock(ts.setTextRange(ts.createNodeArray(statements), body.statements), /*multiLine*/ true);
78935             ts.setTextRange(block, /*location*/ body);
78936             ts.setOriginalNode(block, body);
78937             return block;
78938         }
78939         /**
78940          * Transforms a parameter into a property assignment statement.
78941          *
78942          * @param node The parameter declaration.
78943          */
78944         function transformParameterWithPropertyAssignment(node) {
78945             var name = node.name;
78946             if (!ts.isIdentifier(name)) {
78947                 return undefined;
78948             }
78949             var propertyName = ts.getMutableClone(name);
78950             ts.setEmitFlags(propertyName, 1536 /* NoComments */ | 48 /* NoSourceMap */);
78951             var localName = ts.getMutableClone(name);
78952             ts.setEmitFlags(localName, 1536 /* NoComments */);
78953             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))));
78954         }
78955         function visitMethodDeclaration(node) {
78956             if (!shouldEmitFunctionLikeDeclaration(node)) {
78957                 return undefined;
78958             }
78959             var updated = ts.updateMethod(node, 
78960             /*decorators*/ undefined, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), node.asteriskToken, visitPropertyNameOfClassElement(node), 
78961             /*questionToken*/ undefined, 
78962             /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), 
78963             /*type*/ undefined, ts.visitFunctionBody(node.body, visitor, context));
78964             if (updated !== node) {
78965                 // While we emit the source map for the node after skipping decorators and modifiers,
78966                 // we need to emit the comments for the original range.
78967                 ts.setCommentRange(updated, node);
78968                 ts.setSourceMapRange(updated, ts.moveRangePastDecorators(node));
78969             }
78970             return updated;
78971         }
78972         /**
78973          * Determines whether to emit an accessor declaration. We should not emit the
78974          * declaration if it does not have a body and is abstract.
78975          *
78976          * @param node The declaration node.
78977          */
78978         function shouldEmitAccessorDeclaration(node) {
78979             return !(ts.nodeIsMissing(node.body) && ts.hasModifier(node, 128 /* Abstract */));
78980         }
78981         function visitGetAccessor(node) {
78982             if (!shouldEmitAccessorDeclaration(node)) {
78983                 return undefined;
78984             }
78985             var updated = ts.updateGetAccessor(node, 
78986             /*decorators*/ undefined, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), visitPropertyNameOfClassElement(node), ts.visitParameterList(node.parameters, visitor, context), 
78987             /*type*/ undefined, ts.visitFunctionBody(node.body, visitor, context) || ts.createBlock([]));
78988             if (updated !== node) {
78989                 // While we emit the source map for the node after skipping decorators and modifiers,
78990                 // we need to emit the comments for the original range.
78991                 ts.setCommentRange(updated, node);
78992                 ts.setSourceMapRange(updated, ts.moveRangePastDecorators(node));
78993             }
78994             return updated;
78995         }
78996         function visitSetAccessor(node) {
78997             if (!shouldEmitAccessorDeclaration(node)) {
78998                 return undefined;
78999             }
79000             var updated = ts.updateSetAccessor(node, 
79001             /*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([]));
79002             if (updated !== node) {
79003                 // While we emit the source map for the node after skipping decorators and modifiers,
79004                 // we need to emit the comments for the original range.
79005                 ts.setCommentRange(updated, node);
79006                 ts.setSourceMapRange(updated, ts.moveRangePastDecorators(node));
79007             }
79008             return updated;
79009         }
79010         function visitFunctionDeclaration(node) {
79011             if (!shouldEmitFunctionLikeDeclaration(node)) {
79012                 return ts.createNotEmittedStatement(node);
79013             }
79014             var updated = ts.updateFunctionDeclaration(node, 
79015             /*decorators*/ undefined, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), node.asteriskToken, node.name, 
79016             /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), 
79017             /*type*/ undefined, ts.visitFunctionBody(node.body, visitor, context) || ts.createBlock([]));
79018             if (isExportOfNamespace(node)) {
79019                 var statements = [updated];
79020                 addExportMemberAssignment(statements, node);
79021                 return statements;
79022             }
79023             return updated;
79024         }
79025         function visitFunctionExpression(node) {
79026             if (!shouldEmitFunctionLikeDeclaration(node)) {
79027                 return ts.createOmittedExpression();
79028             }
79029             var updated = ts.updateFunctionExpression(node, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), node.asteriskToken, node.name, 
79030             /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), 
79031             /*type*/ undefined, ts.visitFunctionBody(node.body, visitor, context) || ts.createBlock([]));
79032             return updated;
79033         }
79034         function visitArrowFunction(node) {
79035             var updated = ts.updateArrowFunction(node, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), 
79036             /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), 
79037             /*type*/ undefined, node.equalsGreaterThanToken, ts.visitFunctionBody(node.body, visitor, context));
79038             return updated;
79039         }
79040         function visitParameter(node) {
79041             if (ts.parameterIsThisKeyword(node)) {
79042                 return undefined;
79043             }
79044             var updated = ts.updateParameter(node, 
79045             /*decorators*/ undefined, 
79046             /*modifiers*/ undefined, node.dotDotDotToken, ts.visitNode(node.name, visitor, ts.isBindingName), 
79047             /*questionToken*/ undefined, 
79048             /*type*/ undefined, ts.visitNode(node.initializer, visitor, ts.isExpression));
79049             if (updated !== node) {
79050                 // While we emit the source map for the node after skipping decorators and modifiers,
79051                 // we need to emit the comments for the original range.
79052                 ts.setCommentRange(updated, node);
79053                 ts.setTextRange(updated, ts.moveRangePastModifiers(node));
79054                 ts.setSourceMapRange(updated, ts.moveRangePastModifiers(node));
79055                 ts.setEmitFlags(updated.name, 32 /* NoTrailingSourceMap */);
79056             }
79057             return updated;
79058         }
79059         function visitVariableStatement(node) {
79060             if (isExportOfNamespace(node)) {
79061                 var variables = ts.getInitializedVariables(node.declarationList);
79062                 if (variables.length === 0) {
79063                     // elide statement if there are no initialized variables.
79064                     return undefined;
79065                 }
79066                 return ts.setTextRange(ts.createExpressionStatement(ts.inlineExpressions(ts.map(variables, transformInitializedVariable))), node);
79067             }
79068             else {
79069                 return ts.visitEachChild(node, visitor, context);
79070             }
79071         }
79072         function transformInitializedVariable(node) {
79073             var name = node.name;
79074             if (ts.isBindingPattern(name)) {
79075                 return ts.flattenDestructuringAssignment(node, visitor, context, 0 /* All */, 
79076                 /*needsValue*/ false, createNamespaceExportExpression);
79077             }
79078             else {
79079                 return ts.setTextRange(ts.createAssignment(getNamespaceMemberNameWithSourceMapsAndWithoutComments(name), ts.visitNode(node.initializer, visitor, ts.isExpression)), 
79080                 /*location*/ node);
79081             }
79082         }
79083         function visitVariableDeclaration(node) {
79084             return ts.updateTypeScriptVariableDeclaration(node, ts.visitNode(node.name, visitor, ts.isBindingName), 
79085             /*exclaimationToken*/ undefined, 
79086             /*type*/ undefined, ts.visitNode(node.initializer, visitor, ts.isExpression));
79087         }
79088         function visitParenthesizedExpression(node) {
79089             var innerExpression = ts.skipOuterExpressions(node.expression, ~6 /* Assertions */);
79090             if (ts.isAssertionExpression(innerExpression)) {
79091                 // Make sure we consider all nested cast expressions, e.g.:
79092                 // (<any><number><any>-A).x;
79093                 var expression = ts.visitNode(node.expression, visitor, ts.isExpression);
79094                 // We have an expression of the form: (<Type>SubExpr). Emitting this as (SubExpr)
79095                 // is really not desirable. We would like to emit the subexpression as-is. Omitting
79096                 // the parentheses, however, could cause change in the semantics of the generated
79097                 // code if the casted expression has a lower precedence than the rest of the
79098                 // expression.
79099                 //
79100                 // To preserve comments, we return a "PartiallyEmittedExpression" here which will
79101                 // preserve the position information of the original expression.
79102                 //
79103                 // Due to the auto-parenthesization rules used by the visitor and factory functions
79104                 // we can safely elide the parentheses here, as a new synthetic
79105                 // ParenthesizedExpression will be inserted if we remove parentheses too
79106                 // aggressively.
79107                 // HOWEVER - if there are leading comments on the expression itself, to handle ASI
79108                 // correctly for return and throw, we must keep the parenthesis
79109                 if (ts.length(ts.getLeadingCommentRangesOfNode(expression, currentSourceFile))) {
79110                     return ts.updateParen(node, expression);
79111                 }
79112                 return ts.createPartiallyEmittedExpression(expression, node);
79113             }
79114             return ts.visitEachChild(node, visitor, context);
79115         }
79116         function visitAssertionExpression(node) {
79117             var expression = ts.visitNode(node.expression, visitor, ts.isExpression);
79118             return ts.createPartiallyEmittedExpression(expression, node);
79119         }
79120         function visitNonNullExpression(node) {
79121             var expression = ts.visitNode(node.expression, visitor, ts.isLeftHandSideExpression);
79122             return ts.createPartiallyEmittedExpression(expression, node);
79123         }
79124         function visitCallExpression(node) {
79125             return ts.updateCall(node, ts.visitNode(node.expression, visitor, ts.isExpression), 
79126             /*typeArguments*/ undefined, ts.visitNodes(node.arguments, visitor, ts.isExpression));
79127         }
79128         function visitNewExpression(node) {
79129             return ts.updateNew(node, ts.visitNode(node.expression, visitor, ts.isExpression), 
79130             /*typeArguments*/ undefined, ts.visitNodes(node.arguments, visitor, ts.isExpression));
79131         }
79132         function visitTaggedTemplateExpression(node) {
79133             return ts.updateTaggedTemplate(node, ts.visitNode(node.tag, visitor, ts.isExpression), 
79134             /*typeArguments*/ undefined, ts.visitNode(node.template, visitor, ts.isExpression));
79135         }
79136         function visitJsxSelfClosingElement(node) {
79137             return ts.updateJsxSelfClosingElement(node, ts.visitNode(node.tagName, visitor, ts.isJsxTagNameExpression), 
79138             /*typeArguments*/ undefined, ts.visitNode(node.attributes, visitor, ts.isJsxAttributes));
79139         }
79140         function visitJsxJsxOpeningElement(node) {
79141             return ts.updateJsxOpeningElement(node, ts.visitNode(node.tagName, visitor, ts.isJsxTagNameExpression), 
79142             /*typeArguments*/ undefined, ts.visitNode(node.attributes, visitor, ts.isJsxAttributes));
79143         }
79144         /**
79145          * Determines whether to emit an enum declaration.
79146          *
79147          * @param node The enum declaration node.
79148          */
79149         function shouldEmitEnumDeclaration(node) {
79150             return !ts.isEnumConst(node)
79151                 || compilerOptions.preserveConstEnums
79152                 || compilerOptions.isolatedModules;
79153         }
79154         /**
79155          * Visits an enum declaration.
79156          *
79157          * This function will be called any time a TypeScript enum is encountered.
79158          *
79159          * @param node The enum declaration node.
79160          */
79161         function visitEnumDeclaration(node) {
79162             if (!shouldEmitEnumDeclaration(node)) {
79163                 return ts.createNotEmittedStatement(node);
79164             }
79165             var statements = [];
79166             // We request to be advised when the printer is about to print this node. This allows
79167             // us to set up the correct state for later substitutions.
79168             var emitFlags = 2 /* AdviseOnEmitNode */;
79169             // If needed, we should emit a variable declaration for the enum. If we emit
79170             // a leading variable declaration, we should not emit leading comments for the
79171             // enum body.
79172             var varAdded = addVarForEnumOrModuleDeclaration(statements, node);
79173             if (varAdded) {
79174                 // We should still emit the comments if we are emitting a system module.
79175                 if (moduleKind !== ts.ModuleKind.System || currentLexicalScope !== currentSourceFile) {
79176                     emitFlags |= 512 /* NoLeadingComments */;
79177                 }
79178             }
79179             // `parameterName` is the declaration name used inside of the enum.
79180             var parameterName = getNamespaceParameterName(node);
79181             // `containerName` is the expression used inside of the enum for assignments.
79182             var containerName = getNamespaceContainerName(node);
79183             // `exportName` is the expression used within this node's container for any exported references.
79184             var exportName = ts.hasModifier(node, 1 /* Export */)
79185                 ? ts.getExternalModuleOrNamespaceExportName(currentNamespaceContainerName, node, /*allowComments*/ false, /*allowSourceMaps*/ true)
79186                 : ts.getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ true);
79187             //  x || (x = {})
79188             //  exports.x || (exports.x = {})
79189             var moduleArg = ts.createLogicalOr(exportName, ts.createAssignment(exportName, ts.createObjectLiteral()));
79190             if (hasNamespaceQualifiedExportName(node)) {
79191                 // `localName` is the expression used within this node's containing scope for any local references.
79192                 var localName = ts.getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ true);
79193                 //  x = (exports.x || (exports.x = {}))
79194                 moduleArg = ts.createAssignment(localName, moduleArg);
79195             }
79196             //  (function (x) {
79197             //      x[x["y"] = 0] = "y";
79198             //      ...
79199             //  })(x || (x = {}));
79200             var enumStatement = ts.createExpressionStatement(ts.createCall(ts.createFunctionExpression(
79201             /*modifiers*/ undefined, 
79202             /*asteriskToken*/ undefined, 
79203             /*name*/ undefined, 
79204             /*typeParameters*/ undefined, [ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, parameterName)], 
79205             /*type*/ undefined, transformEnumBody(node, containerName)), 
79206             /*typeArguments*/ undefined, [moduleArg]));
79207             ts.setOriginalNode(enumStatement, node);
79208             if (varAdded) {
79209                 // If a variable was added, synthetic comments are emitted on it, not on the moduleStatement.
79210                 ts.setSyntheticLeadingComments(enumStatement, undefined);
79211                 ts.setSyntheticTrailingComments(enumStatement, undefined);
79212             }
79213             ts.setTextRange(enumStatement, node);
79214             ts.addEmitFlags(enumStatement, emitFlags);
79215             statements.push(enumStatement);
79216             // Add a DeclarationMarker for the enum to preserve trailing comments and mark
79217             // the end of the declaration.
79218             statements.push(ts.createEndOfDeclarationMarker(node));
79219             return statements;
79220         }
79221         /**
79222          * Transforms the body of an enum declaration.
79223          *
79224          * @param node The enum declaration node.
79225          */
79226         function transformEnumBody(node, localName) {
79227             var savedCurrentNamespaceLocalName = currentNamespaceContainerName;
79228             currentNamespaceContainerName = localName;
79229             var statements = [];
79230             startLexicalEnvironment();
79231             var members = ts.map(node.members, transformEnumMember);
79232             ts.insertStatementsAfterStandardPrologue(statements, endLexicalEnvironment());
79233             ts.addRange(statements, members);
79234             currentNamespaceContainerName = savedCurrentNamespaceLocalName;
79235             return ts.createBlock(ts.setTextRange(ts.createNodeArray(statements), /*location*/ node.members), 
79236             /*multiLine*/ true);
79237         }
79238         /**
79239          * Transforms an enum member into a statement.
79240          *
79241          * @param member The enum member node.
79242          */
79243         function transformEnumMember(member) {
79244             // enums don't support computed properties
79245             // we pass false as 'generateNameForComputedPropertyName' for a backward compatibility purposes
79246             // old emitter always generate 'expression' part of the name as-is.
79247             var name = getExpressionForPropertyName(member, /*generateNameForComputedPropertyName*/ false);
79248             var valueExpression = transformEnumMemberDeclarationValue(member);
79249             var innerAssignment = ts.createAssignment(ts.createElementAccess(currentNamespaceContainerName, name), valueExpression);
79250             var outerAssignment = valueExpression.kind === 10 /* StringLiteral */ ?
79251                 innerAssignment :
79252                 ts.createAssignment(ts.createElementAccess(currentNamespaceContainerName, innerAssignment), name);
79253             return ts.setTextRange(ts.createExpressionStatement(ts.setTextRange(outerAssignment, member)), member);
79254         }
79255         /**
79256          * Transforms the value of an enum member.
79257          *
79258          * @param member The enum member node.
79259          */
79260         function transformEnumMemberDeclarationValue(member) {
79261             var value = resolver.getConstantValue(member);
79262             if (value !== undefined) {
79263                 return ts.createLiteral(value);
79264             }
79265             else {
79266                 enableSubstitutionForNonQualifiedEnumMembers();
79267                 if (member.initializer) {
79268                     return ts.visitNode(member.initializer, visitor, ts.isExpression);
79269                 }
79270                 else {
79271                     return ts.createVoidZero();
79272                 }
79273             }
79274         }
79275         /**
79276          * Determines whether to elide a module declaration.
79277          *
79278          * @param node The module declaration node.
79279          */
79280         function shouldEmitModuleDeclaration(nodeIn) {
79281             var node = ts.getParseTreeNode(nodeIn, ts.isModuleDeclaration);
79282             if (!node) {
79283                 // If we can't find a parse tree node, assume the node is instantiated.
79284                 return true;
79285             }
79286             return ts.isInstantiatedModule(node, !!compilerOptions.preserveConstEnums || !!compilerOptions.isolatedModules);
79287         }
79288         /**
79289          * Determines whether an exported declaration will have a qualified export name (e.g. `f.x`
79290          * or `exports.x`).
79291          */
79292         function hasNamespaceQualifiedExportName(node) {
79293             return isExportOfNamespace(node)
79294                 || (isExternalModuleExport(node)
79295                     && moduleKind !== ts.ModuleKind.ES2015
79296                     && moduleKind !== ts.ModuleKind.ES2020
79297                     && moduleKind !== ts.ModuleKind.ESNext
79298                     && moduleKind !== ts.ModuleKind.System);
79299         }
79300         /**
79301          * Records that a declaration was emitted in the current scope, if it was the first
79302          * declaration for the provided symbol.
79303          */
79304         function recordEmittedDeclarationInScope(node) {
79305             if (!currentScopeFirstDeclarationsOfName) {
79306                 currentScopeFirstDeclarationsOfName = ts.createUnderscoreEscapedMap();
79307             }
79308             var name = declaredNameInScope(node);
79309             if (!currentScopeFirstDeclarationsOfName.has(name)) {
79310                 currentScopeFirstDeclarationsOfName.set(name, node);
79311             }
79312         }
79313         /**
79314          * Determines whether a declaration is the first declaration with
79315          * the same name emitted in the current scope.
79316          */
79317         function isFirstEmittedDeclarationInScope(node) {
79318             if (currentScopeFirstDeclarationsOfName) {
79319                 var name = declaredNameInScope(node);
79320                 return currentScopeFirstDeclarationsOfName.get(name) === node;
79321             }
79322             return true;
79323         }
79324         function declaredNameInScope(node) {
79325             ts.Debug.assertNode(node.name, ts.isIdentifier);
79326             return node.name.escapedText;
79327         }
79328         /**
79329          * Adds a leading VariableStatement for a enum or module declaration.
79330          */
79331         function addVarForEnumOrModuleDeclaration(statements, node) {
79332             // Emit a variable statement for the module. We emit top-level enums as a `var`
79333             // declaration to avoid static errors in global scripts scripts due to redeclaration.
79334             // enums in any other scope are emitted as a `let` declaration.
79335             var statement = ts.createVariableStatement(ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), ts.createVariableDeclarationList([
79336                 ts.createVariableDeclaration(ts.getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ true))
79337             ], currentLexicalScope.kind === 290 /* SourceFile */ ? 0 /* None */ : 1 /* Let */));
79338             ts.setOriginalNode(statement, node);
79339             recordEmittedDeclarationInScope(node);
79340             if (isFirstEmittedDeclarationInScope(node)) {
79341                 // Adjust the source map emit to match the old emitter.
79342                 if (node.kind === 248 /* EnumDeclaration */) {
79343                     ts.setSourceMapRange(statement.declarationList, node);
79344                 }
79345                 else {
79346                     ts.setSourceMapRange(statement, node);
79347                 }
79348                 // Trailing comments for module declaration should be emitted after the function closure
79349                 // instead of the variable statement:
79350                 //
79351                 //     /** Module comment*/
79352                 //     module m1 {
79353                 //         function foo4Export() {
79354                 //         }
79355                 //     } // trailing comment module
79356                 //
79357                 // Should emit:
79358                 //
79359                 //     /** Module comment*/
79360                 //     var m1;
79361                 //     (function (m1) {
79362                 //         function foo4Export() {
79363                 //         }
79364                 //     })(m1 || (m1 = {})); // trailing comment module
79365                 //
79366                 ts.setCommentRange(statement, node);
79367                 ts.addEmitFlags(statement, 1024 /* NoTrailingComments */ | 4194304 /* HasEndOfDeclarationMarker */);
79368                 statements.push(statement);
79369                 return true;
79370             }
79371             else {
79372                 // For an EnumDeclaration or ModuleDeclaration that merges with a preceeding
79373                 // declaration we do not emit a leading variable declaration. To preserve the
79374                 // begin/end semantics of the declararation and to properly handle exports
79375                 // we wrap the leading variable declaration in a `MergeDeclarationMarker`.
79376                 var mergeMarker = ts.createMergeDeclarationMarker(statement);
79377                 ts.setEmitFlags(mergeMarker, 1536 /* NoComments */ | 4194304 /* HasEndOfDeclarationMarker */);
79378                 statements.push(mergeMarker);
79379                 return false;
79380             }
79381         }
79382         /**
79383          * Visits a module declaration node.
79384          *
79385          * This function will be called any time a TypeScript namespace (ModuleDeclaration) is encountered.
79386          *
79387          * @param node The module declaration node.
79388          */
79389         function visitModuleDeclaration(node) {
79390             if (!shouldEmitModuleDeclaration(node)) {
79391                 return ts.createNotEmittedStatement(node);
79392             }
79393             ts.Debug.assertNode(node.name, ts.isIdentifier, "A TypeScript namespace should have an Identifier name.");
79394             enableSubstitutionForNamespaceExports();
79395             var statements = [];
79396             // We request to be advised when the printer is about to print this node. This allows
79397             // us to set up the correct state for later substitutions.
79398             var emitFlags = 2 /* AdviseOnEmitNode */;
79399             // If needed, we should emit a variable declaration for the module. If we emit
79400             // a leading variable declaration, we should not emit leading comments for the
79401             // module body.
79402             var varAdded = addVarForEnumOrModuleDeclaration(statements, node);
79403             if (varAdded) {
79404                 // We should still emit the comments if we are emitting a system module.
79405                 if (moduleKind !== ts.ModuleKind.System || currentLexicalScope !== currentSourceFile) {
79406                     emitFlags |= 512 /* NoLeadingComments */;
79407                 }
79408             }
79409             // `parameterName` is the declaration name used inside of the namespace.
79410             var parameterName = getNamespaceParameterName(node);
79411             // `containerName` is the expression used inside of the namespace for exports.
79412             var containerName = getNamespaceContainerName(node);
79413             // `exportName` is the expression used within this node's container for any exported references.
79414             var exportName = ts.hasModifier(node, 1 /* Export */)
79415                 ? ts.getExternalModuleOrNamespaceExportName(currentNamespaceContainerName, node, /*allowComments*/ false, /*allowSourceMaps*/ true)
79416                 : ts.getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ true);
79417             //  x || (x = {})
79418             //  exports.x || (exports.x = {})
79419             var moduleArg = ts.createLogicalOr(exportName, ts.createAssignment(exportName, ts.createObjectLiteral()));
79420             if (hasNamespaceQualifiedExportName(node)) {
79421                 // `localName` is the expression used within this node's containing scope for any local references.
79422                 var localName = ts.getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ true);
79423                 //  x = (exports.x || (exports.x = {}))
79424                 moduleArg = ts.createAssignment(localName, moduleArg);
79425             }
79426             //  (function (x_1) {
79427             //      x_1.y = ...;
79428             //  })(x || (x = {}));
79429             var moduleStatement = ts.createExpressionStatement(ts.createCall(ts.createFunctionExpression(
79430             /*modifiers*/ undefined, 
79431             /*asteriskToken*/ undefined, 
79432             /*name*/ undefined, 
79433             /*typeParameters*/ undefined, [ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, parameterName)], 
79434             /*type*/ undefined, transformModuleBody(node, containerName)), 
79435             /*typeArguments*/ undefined, [moduleArg]));
79436             ts.setOriginalNode(moduleStatement, node);
79437             if (varAdded) {
79438                 // If a variable was added, synthetic comments are emitted on it, not on the moduleStatement.
79439                 ts.setSyntheticLeadingComments(moduleStatement, undefined);
79440                 ts.setSyntheticTrailingComments(moduleStatement, undefined);
79441             }
79442             ts.setTextRange(moduleStatement, node);
79443             ts.addEmitFlags(moduleStatement, emitFlags);
79444             statements.push(moduleStatement);
79445             // Add a DeclarationMarker for the namespace to preserve trailing comments and mark
79446             // the end of the declaration.
79447             statements.push(ts.createEndOfDeclarationMarker(node));
79448             return statements;
79449         }
79450         /**
79451          * Transforms the body of a module declaration.
79452          *
79453          * @param node The module declaration node.
79454          */
79455         function transformModuleBody(node, namespaceLocalName) {
79456             var savedCurrentNamespaceContainerName = currentNamespaceContainerName;
79457             var savedCurrentNamespace = currentNamespace;
79458             var savedCurrentScopeFirstDeclarationsOfName = currentScopeFirstDeclarationsOfName;
79459             currentNamespaceContainerName = namespaceLocalName;
79460             currentNamespace = node;
79461             currentScopeFirstDeclarationsOfName = undefined;
79462             var statements = [];
79463             startLexicalEnvironment();
79464             var statementsLocation;
79465             var blockLocation;
79466             if (node.body) {
79467                 if (node.body.kind === 250 /* ModuleBlock */) {
79468                     saveStateAndInvoke(node.body, function (body) { return ts.addRange(statements, ts.visitNodes(body.statements, namespaceElementVisitor, ts.isStatement)); });
79469                     statementsLocation = node.body.statements;
79470                     blockLocation = node.body;
79471                 }
79472                 else {
79473                     var result = visitModuleDeclaration(node.body);
79474                     if (result) {
79475                         if (ts.isArray(result)) {
79476                             ts.addRange(statements, result);
79477                         }
79478                         else {
79479                             statements.push(result);
79480                         }
79481                     }
79482                     var moduleBlock = getInnerMostModuleDeclarationFromDottedModule(node).body;
79483                     statementsLocation = ts.moveRangePos(moduleBlock.statements, -1);
79484                 }
79485             }
79486             ts.insertStatementsAfterStandardPrologue(statements, endLexicalEnvironment());
79487             currentNamespaceContainerName = savedCurrentNamespaceContainerName;
79488             currentNamespace = savedCurrentNamespace;
79489             currentScopeFirstDeclarationsOfName = savedCurrentScopeFirstDeclarationsOfName;
79490             var block = ts.createBlock(ts.setTextRange(ts.createNodeArray(statements), 
79491             /*location*/ statementsLocation), 
79492             /*multiLine*/ true);
79493             ts.setTextRange(block, blockLocation);
79494             // namespace hello.hi.world {
79495             //      function foo() {}
79496             //
79497             //      // TODO, blah
79498             // }
79499             //
79500             // should be emitted as
79501             //
79502             // var hello;
79503             // (function (hello) {
79504             //     var hi;
79505             //     (function (hi) {
79506             //         var world;
79507             //         (function (world) {
79508             //             function foo() { }
79509             //             // TODO, blah
79510             //         })(world = hi.world || (hi.world = {}));
79511             //     })(hi = hello.hi || (hello.hi = {}));
79512             // })(hello || (hello = {}));
79513             // We only want to emit comment on the namespace which contains block body itself, not the containing namespaces.
79514             if (!node.body || node.body.kind !== 250 /* ModuleBlock */) {
79515                 ts.setEmitFlags(block, ts.getEmitFlags(block) | 1536 /* NoComments */);
79516             }
79517             return block;
79518         }
79519         function getInnerMostModuleDeclarationFromDottedModule(moduleDeclaration) {
79520             if (moduleDeclaration.body.kind === 249 /* ModuleDeclaration */) {
79521                 var recursiveInnerModule = getInnerMostModuleDeclarationFromDottedModule(moduleDeclaration.body);
79522                 return recursiveInnerModule || moduleDeclaration.body;
79523             }
79524         }
79525         /**
79526          * Visits an import declaration, eliding it if it is not referenced and `importsNotUsedAsValues` is not 'preserve'.
79527          *
79528          * @param node The import declaration node.
79529          */
79530         function visitImportDeclaration(node) {
79531             if (!node.importClause) {
79532                 // Do not elide a side-effect only import declaration.
79533                 //  import "foo";
79534                 return node;
79535             }
79536             if (node.importClause.isTypeOnly) {
79537                 // Always elide type-only imports
79538                 return undefined;
79539             }
79540             // Elide the declaration if the import clause was elided.
79541             var importClause = ts.visitNode(node.importClause, visitImportClause, ts.isImportClause);
79542             return importClause ||
79543                 compilerOptions.importsNotUsedAsValues === 1 /* Preserve */ ||
79544                 compilerOptions.importsNotUsedAsValues === 2 /* Error */
79545                 ? ts.updateImportDeclaration(node, 
79546                 /*decorators*/ undefined, 
79547                 /*modifiers*/ undefined, importClause, node.moduleSpecifier)
79548                 : undefined;
79549         }
79550         /**
79551          * Visits an import clause, eliding it if it is not referenced.
79552          *
79553          * @param node The import clause node.
79554          */
79555         function visitImportClause(node) {
79556             if (node.isTypeOnly) {
79557                 return undefined;
79558             }
79559             // Elide the import clause if we elide both its name and its named bindings.
79560             var name = resolver.isReferencedAliasDeclaration(node) ? node.name : undefined;
79561             var namedBindings = ts.visitNode(node.namedBindings, visitNamedImportBindings, ts.isNamedImportBindings);
79562             return (name || namedBindings) ? ts.updateImportClause(node, name, namedBindings, /*isTypeOnly*/ false) : undefined;
79563         }
79564         /**
79565          * Visits named import bindings, eliding it if it is not referenced.
79566          *
79567          * @param node The named import bindings node.
79568          */
79569         function visitNamedImportBindings(node) {
79570             if (node.kind === 256 /* NamespaceImport */) {
79571                 // Elide a namespace import if it is not referenced.
79572                 return resolver.isReferencedAliasDeclaration(node) ? node : undefined;
79573             }
79574             else {
79575                 // Elide named imports if all of its import specifiers are elided.
79576                 var elements = ts.visitNodes(node.elements, visitImportSpecifier, ts.isImportSpecifier);
79577                 return ts.some(elements) ? ts.updateNamedImports(node, elements) : undefined;
79578             }
79579         }
79580         /**
79581          * Visits an import specifier, eliding it if it is not referenced.
79582          *
79583          * @param node The import specifier node.
79584          */
79585         function visitImportSpecifier(node) {
79586             // Elide an import specifier if it is not referenced.
79587             return resolver.isReferencedAliasDeclaration(node) ? node : undefined;
79588         }
79589         /**
79590          * Visits an export assignment, eliding it if it does not contain a clause that resolves
79591          * to a value.
79592          *
79593          * @param node The export assignment node.
79594          */
79595         function visitExportAssignment(node) {
79596             // Elide the export assignment if it does not reference a value.
79597             return resolver.isValueAliasDeclaration(node)
79598                 ? ts.visitEachChild(node, visitor, context)
79599                 : undefined;
79600         }
79601         /**
79602          * Visits an export declaration, eliding it if it does not contain a clause that resolves
79603          * to a value.
79604          *
79605          * @param node The export declaration node.
79606          */
79607         function visitExportDeclaration(node) {
79608             if (node.isTypeOnly) {
79609                 return undefined;
79610             }
79611             if (!node.exportClause || ts.isNamespaceExport(node.exportClause)) {
79612                 // never elide `export <whatever> from <whereever>` declarations -
79613                 // they should be kept for sideffects/untyped exports, even when the
79614                 // type checker doesn't know about any exports
79615                 return node;
79616             }
79617             if (!resolver.isValueAliasDeclaration(node)) {
79618                 // Elide the export declaration if it does not export a value.
79619                 return undefined;
79620             }
79621             // Elide the export declaration if all of its named exports are elided.
79622             var exportClause = ts.visitNode(node.exportClause, visitNamedExportBindings, ts.isNamedExportBindings);
79623             return exportClause
79624                 ? ts.updateExportDeclaration(node, 
79625                 /*decorators*/ undefined, 
79626                 /*modifiers*/ undefined, exportClause, node.moduleSpecifier, node.isTypeOnly)
79627                 : undefined;
79628         }
79629         /**
79630          * Visits named exports, eliding it if it does not contain an export specifier that
79631          * resolves to a value.
79632          *
79633          * @param node The named exports node.
79634          */
79635         function visitNamedExports(node) {
79636             // Elide the named exports if all of its export specifiers were elided.
79637             var elements = ts.visitNodes(node.elements, visitExportSpecifier, ts.isExportSpecifier);
79638             return ts.some(elements) ? ts.updateNamedExports(node, elements) : undefined;
79639         }
79640         function visitNamespaceExports(node) {
79641             return ts.updateNamespaceExport(node, ts.visitNode(node.name, visitor, ts.isIdentifier));
79642         }
79643         function visitNamedExportBindings(node) {
79644             return ts.isNamespaceExport(node) ? visitNamespaceExports(node) : visitNamedExports(node);
79645         }
79646         /**
79647          * Visits an export specifier, eliding it if it does not resolve to a value.
79648          *
79649          * @param node The export specifier node.
79650          */
79651         function visitExportSpecifier(node) {
79652             // Elide an export specifier if it does not reference a value.
79653             return resolver.isValueAliasDeclaration(node) ? node : undefined;
79654         }
79655         /**
79656          * Determines whether to emit an import equals declaration.
79657          *
79658          * @param node The import equals declaration node.
79659          */
79660         function shouldEmitImportEqualsDeclaration(node) {
79661             // preserve old compiler's behavior: emit 'var' for import declaration (even if we do not consider them referenced) when
79662             // - current file is not external module
79663             // - import declaration is top level and target is value imported by entity name
79664             return resolver.isReferencedAliasDeclaration(node)
79665                 || (!ts.isExternalModule(currentSourceFile)
79666                     && resolver.isTopLevelValueImportEqualsWithEntityName(node));
79667         }
79668         /**
79669          * Visits an import equals declaration.
79670          *
79671          * @param node The import equals declaration node.
79672          */
79673         function visitImportEqualsDeclaration(node) {
79674             if (ts.isExternalModuleImportEqualsDeclaration(node)) {
79675                 var isReferenced = resolver.isReferencedAliasDeclaration(node);
79676                 // If the alias is unreferenced but we want to keep the import, replace with 'import "mod"'.
79677                 if (!isReferenced && compilerOptions.importsNotUsedAsValues === 1 /* Preserve */) {
79678                     return ts.setOriginalNode(ts.setTextRange(ts.createImportDeclaration(
79679                     /*decorators*/ undefined, 
79680                     /*modifiers*/ undefined, 
79681                     /*importClause*/ undefined, node.moduleReference.expression), node), node);
79682                 }
79683                 return isReferenced ? ts.visitEachChild(node, visitor, context) : undefined;
79684             }
79685             if (!shouldEmitImportEqualsDeclaration(node)) {
79686                 return undefined;
79687             }
79688             var moduleReference = ts.createExpressionFromEntityName(node.moduleReference);
79689             ts.setEmitFlags(moduleReference, 1536 /* NoComments */ | 2048 /* NoNestedComments */);
79690             if (isNamedExternalModuleExport(node) || !isExportOfNamespace(node)) {
79691                 //  export var ${name} = ${moduleReference};
79692                 //  var ${name} = ${moduleReference};
79693                 return ts.setOriginalNode(ts.setTextRange(ts.createVariableStatement(ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), ts.createVariableDeclarationList([
79694                     ts.setOriginalNode(ts.createVariableDeclaration(node.name, 
79695                     /*type*/ undefined, moduleReference), node)
79696                 ])), node), node);
79697             }
79698             else {
79699                 // exports.${name} = ${moduleReference};
79700                 return ts.setOriginalNode(createNamespaceExport(node.name, moduleReference, node), node);
79701             }
79702         }
79703         /**
79704          * Gets a value indicating whether the node is exported from a namespace.
79705          *
79706          * @param node The node to test.
79707          */
79708         function isExportOfNamespace(node) {
79709             return currentNamespace !== undefined && ts.hasModifier(node, 1 /* Export */);
79710         }
79711         /**
79712          * Gets a value indicating whether the node is exported from an external module.
79713          *
79714          * @param node The node to test.
79715          */
79716         function isExternalModuleExport(node) {
79717             return currentNamespace === undefined && ts.hasModifier(node, 1 /* Export */);
79718         }
79719         /**
79720          * Gets a value indicating whether the node is a named export from an external module.
79721          *
79722          * @param node The node to test.
79723          */
79724         function isNamedExternalModuleExport(node) {
79725             return isExternalModuleExport(node)
79726                 && !ts.hasModifier(node, 512 /* Default */);
79727         }
79728         /**
79729          * Gets a value indicating whether the node is the default export of an external module.
79730          *
79731          * @param node The node to test.
79732          */
79733         function isDefaultExternalModuleExport(node) {
79734             return isExternalModuleExport(node)
79735                 && ts.hasModifier(node, 512 /* Default */);
79736         }
79737         /**
79738          * Creates a statement for the provided expression. This is used in calls to `map`.
79739          */
79740         function expressionToStatement(expression) {
79741             return ts.createExpressionStatement(expression);
79742         }
79743         function addExportMemberAssignment(statements, node) {
79744             var expression = ts.createAssignment(ts.getExternalModuleOrNamespaceExportName(currentNamespaceContainerName, node, /*allowComments*/ false, /*allowSourceMaps*/ true), ts.getLocalName(node));
79745             ts.setSourceMapRange(expression, ts.createRange(node.name ? node.name.pos : node.pos, node.end));
79746             var statement = ts.createExpressionStatement(expression);
79747             ts.setSourceMapRange(statement, ts.createRange(-1, node.end));
79748             statements.push(statement);
79749         }
79750         function createNamespaceExport(exportName, exportValue, location) {
79751             return ts.setTextRange(ts.createExpressionStatement(ts.createAssignment(ts.getNamespaceMemberName(currentNamespaceContainerName, exportName, /*allowComments*/ false, /*allowSourceMaps*/ true), exportValue)), location);
79752         }
79753         function createNamespaceExportExpression(exportName, exportValue, location) {
79754             return ts.setTextRange(ts.createAssignment(getNamespaceMemberNameWithSourceMapsAndWithoutComments(exportName), exportValue), location);
79755         }
79756         function getNamespaceMemberNameWithSourceMapsAndWithoutComments(name) {
79757             return ts.getNamespaceMemberName(currentNamespaceContainerName, name, /*allowComments*/ false, /*allowSourceMaps*/ true);
79758         }
79759         /**
79760          * Gets the declaration name used inside of a namespace or enum.
79761          */
79762         function getNamespaceParameterName(node) {
79763             var name = ts.getGeneratedNameForNode(node);
79764             ts.setSourceMapRange(name, node.name);
79765             return name;
79766         }
79767         /**
79768          * Gets the expression used to refer to a namespace or enum within the body
79769          * of its declaration.
79770          */
79771         function getNamespaceContainerName(node) {
79772             return ts.getGeneratedNameForNode(node);
79773         }
79774         /**
79775          * Gets a local alias for a class declaration if it is a decorated class with an internal
79776          * reference to the static side of the class. This is necessary to avoid issues with
79777          * double-binding semantics for the class name.
79778          */
79779         function getClassAliasIfNeeded(node) {
79780             if (resolver.getNodeCheckFlags(node) & 16777216 /* ClassWithConstructorReference */) {
79781                 enableSubstitutionForClassAliases();
79782                 var classAlias = ts.createUniqueName(node.name && !ts.isGeneratedIdentifier(node.name) ? ts.idText(node.name) : "default");
79783                 classAliases[ts.getOriginalNodeId(node)] = classAlias;
79784                 hoistVariableDeclaration(classAlias);
79785                 return classAlias;
79786             }
79787         }
79788         function getClassPrototype(node) {
79789             return ts.createPropertyAccess(ts.getDeclarationName(node), "prototype");
79790         }
79791         function getClassMemberPrefix(node, member) {
79792             return ts.hasModifier(member, 32 /* Static */)
79793                 ? ts.getDeclarationName(node)
79794                 : getClassPrototype(node);
79795         }
79796         function enableSubstitutionForNonQualifiedEnumMembers() {
79797             if ((enabledSubstitutions & 8 /* NonQualifiedEnumMembers */) === 0) {
79798                 enabledSubstitutions |= 8 /* NonQualifiedEnumMembers */;
79799                 context.enableSubstitution(75 /* Identifier */);
79800             }
79801         }
79802         function enableSubstitutionForClassAliases() {
79803             if ((enabledSubstitutions & 1 /* ClassAliases */) === 0) {
79804                 enabledSubstitutions |= 1 /* ClassAliases */;
79805                 // We need to enable substitutions for identifiers. This allows us to
79806                 // substitute class names inside of a class declaration.
79807                 context.enableSubstitution(75 /* Identifier */);
79808                 // Keep track of class aliases.
79809                 classAliases = [];
79810             }
79811         }
79812         function enableSubstitutionForNamespaceExports() {
79813             if ((enabledSubstitutions & 2 /* NamespaceExports */) === 0) {
79814                 enabledSubstitutions |= 2 /* NamespaceExports */;
79815                 // We need to enable substitutions for identifiers and shorthand property assignments. This allows us to
79816                 // substitute the names of exported members of a namespace.
79817                 context.enableSubstitution(75 /* Identifier */);
79818                 context.enableSubstitution(282 /* ShorthandPropertyAssignment */);
79819                 // We need to be notified when entering and exiting namespaces.
79820                 context.enableEmitNotification(249 /* ModuleDeclaration */);
79821             }
79822         }
79823         function isTransformedModuleDeclaration(node) {
79824             return ts.getOriginalNode(node).kind === 249 /* ModuleDeclaration */;
79825         }
79826         function isTransformedEnumDeclaration(node) {
79827             return ts.getOriginalNode(node).kind === 248 /* EnumDeclaration */;
79828         }
79829         /**
79830          * Hook for node emit.
79831          *
79832          * @param hint A hint as to the intended usage of the node.
79833          * @param node The node to emit.
79834          * @param emit A callback used to emit the node in the printer.
79835          */
79836         function onEmitNode(hint, node, emitCallback) {
79837             var savedApplicableSubstitutions = applicableSubstitutions;
79838             var savedCurrentSourceFile = currentSourceFile;
79839             if (ts.isSourceFile(node)) {
79840                 currentSourceFile = node;
79841             }
79842             if (enabledSubstitutions & 2 /* NamespaceExports */ && isTransformedModuleDeclaration(node)) {
79843                 applicableSubstitutions |= 2 /* NamespaceExports */;
79844             }
79845             if (enabledSubstitutions & 8 /* NonQualifiedEnumMembers */ && isTransformedEnumDeclaration(node)) {
79846                 applicableSubstitutions |= 8 /* NonQualifiedEnumMembers */;
79847             }
79848             previousOnEmitNode(hint, node, emitCallback);
79849             applicableSubstitutions = savedApplicableSubstitutions;
79850             currentSourceFile = savedCurrentSourceFile;
79851         }
79852         /**
79853          * Hooks node substitutions.
79854          *
79855          * @param hint A hint as to the intended usage of the node.
79856          * @param node The node to substitute.
79857          */
79858         function onSubstituteNode(hint, node) {
79859             node = previousOnSubstituteNode(hint, node);
79860             if (hint === 1 /* Expression */) {
79861                 return substituteExpression(node);
79862             }
79863             else if (ts.isShorthandPropertyAssignment(node)) {
79864                 return substituteShorthandPropertyAssignment(node);
79865             }
79866             return node;
79867         }
79868         function substituteShorthandPropertyAssignment(node) {
79869             if (enabledSubstitutions & 2 /* NamespaceExports */) {
79870                 var name = node.name;
79871                 var exportedName = trySubstituteNamespaceExportedName(name);
79872                 if (exportedName) {
79873                     // A shorthand property with an assignment initializer is probably part of a
79874                     // destructuring assignment
79875                     if (node.objectAssignmentInitializer) {
79876                         var initializer = ts.createAssignment(exportedName, node.objectAssignmentInitializer);
79877                         return ts.setTextRange(ts.createPropertyAssignment(name, initializer), node);
79878                     }
79879                     return ts.setTextRange(ts.createPropertyAssignment(name, exportedName), node);
79880                 }
79881             }
79882             return node;
79883         }
79884         function substituteExpression(node) {
79885             switch (node.kind) {
79886                 case 75 /* Identifier */:
79887                     return substituteExpressionIdentifier(node);
79888                 case 194 /* PropertyAccessExpression */:
79889                     return substitutePropertyAccessExpression(node);
79890                 case 195 /* ElementAccessExpression */:
79891                     return substituteElementAccessExpression(node);
79892             }
79893             return node;
79894         }
79895         function substituteExpressionIdentifier(node) {
79896             return trySubstituteClassAlias(node)
79897                 || trySubstituteNamespaceExportedName(node)
79898                 || node;
79899         }
79900         function trySubstituteClassAlias(node) {
79901             if (enabledSubstitutions & 1 /* ClassAliases */) {
79902                 if (resolver.getNodeCheckFlags(node) & 33554432 /* ConstructorReferenceInClass */) {
79903                     // Due to the emit for class decorators, any reference to the class from inside of the class body
79904                     // must instead be rewritten to point to a temporary variable to avoid issues with the double-bind
79905                     // behavior of class names in ES6.
79906                     // Also, when emitting statics for class expressions, we must substitute a class alias for
79907                     // constructor references in static property initializers.
79908                     var declaration = resolver.getReferencedValueDeclaration(node);
79909                     if (declaration) {
79910                         var classAlias = classAliases[declaration.id]; // TODO: GH#18217
79911                         if (classAlias) {
79912                             var clone_1 = ts.getSynthesizedClone(classAlias);
79913                             ts.setSourceMapRange(clone_1, node);
79914                             ts.setCommentRange(clone_1, node);
79915                             return clone_1;
79916                         }
79917                     }
79918                 }
79919             }
79920             return undefined;
79921         }
79922         function trySubstituteNamespaceExportedName(node) {
79923             // If this is explicitly a local name, do not substitute.
79924             if (enabledSubstitutions & applicableSubstitutions && !ts.isGeneratedIdentifier(node) && !ts.isLocalName(node)) {
79925                 // If we are nested within a namespace declaration, we may need to qualifiy
79926                 // an identifier that is exported from a merged namespace.
79927                 var container = resolver.getReferencedExportContainer(node, /*prefixLocals*/ false);
79928                 if (container && container.kind !== 290 /* SourceFile */) {
79929                     var substitute = (applicableSubstitutions & 2 /* NamespaceExports */ && container.kind === 249 /* ModuleDeclaration */) ||
79930                         (applicableSubstitutions & 8 /* NonQualifiedEnumMembers */ && container.kind === 248 /* EnumDeclaration */);
79931                     if (substitute) {
79932                         return ts.setTextRange(ts.createPropertyAccess(ts.getGeneratedNameForNode(container), node), 
79933                         /*location*/ node);
79934                     }
79935                 }
79936             }
79937             return undefined;
79938         }
79939         function substitutePropertyAccessExpression(node) {
79940             return substituteConstantValue(node);
79941         }
79942         function substituteElementAccessExpression(node) {
79943             return substituteConstantValue(node);
79944         }
79945         function substituteConstantValue(node) {
79946             var constantValue = tryGetConstEnumValue(node);
79947             if (constantValue !== undefined) {
79948                 // track the constant value on the node for the printer in needsDotDotForPropertyAccess
79949                 ts.setConstantValue(node, constantValue);
79950                 var substitute = ts.createLiteral(constantValue);
79951                 if (!compilerOptions.removeComments) {
79952                     var originalNode = ts.getOriginalNode(node, ts.isAccessExpression);
79953                     var propertyName = ts.isPropertyAccessExpression(originalNode)
79954                         ? ts.declarationNameToString(originalNode.name)
79955                         : ts.getTextOfNode(originalNode.argumentExpression);
79956                     ts.addSyntheticTrailingComment(substitute, 3 /* MultiLineCommentTrivia */, " " + propertyName + " ");
79957                 }
79958                 return substitute;
79959             }
79960             return node;
79961         }
79962         function tryGetConstEnumValue(node) {
79963             if (compilerOptions.isolatedModules) {
79964                 return undefined;
79965             }
79966             return ts.isPropertyAccessExpression(node) || ts.isElementAccessExpression(node) ? resolver.getConstantValue(node) : undefined;
79967         }
79968     }
79969     ts.transformTypeScript = transformTypeScript;
79970     function createDecorateHelper(context, decoratorExpressions, target, memberName, descriptor, location) {
79971         var argumentsArray = [];
79972         argumentsArray.push(ts.createArrayLiteral(decoratorExpressions, /*multiLine*/ true));
79973         argumentsArray.push(target);
79974         if (memberName) {
79975             argumentsArray.push(memberName);
79976             if (descriptor) {
79977                 argumentsArray.push(descriptor);
79978             }
79979         }
79980         context.requestEmitHelper(ts.decorateHelper);
79981         return ts.setTextRange(ts.createCall(ts.getUnscopedHelperName("__decorate"), 
79982         /*typeArguments*/ undefined, argumentsArray), location);
79983     }
79984     ts.decorateHelper = {
79985         name: "typescript:decorate",
79986         importName: "__decorate",
79987         scoped: false,
79988         priority: 2,
79989         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            };"
79990     };
79991     function createMetadataHelper(context, metadataKey, metadataValue) {
79992         context.requestEmitHelper(ts.metadataHelper);
79993         return ts.createCall(ts.getUnscopedHelperName("__metadata"), 
79994         /*typeArguments*/ undefined, [
79995             ts.createLiteral(metadataKey),
79996             metadataValue
79997         ]);
79998     }
79999     ts.metadataHelper = {
80000         name: "typescript:metadata",
80001         importName: "__metadata",
80002         scoped: false,
80003         priority: 3,
80004         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            };"
80005     };
80006     function createParamHelper(context, expression, parameterOffset, location) {
80007         context.requestEmitHelper(ts.paramHelper);
80008         return ts.setTextRange(ts.createCall(ts.getUnscopedHelperName("__param"), 
80009         /*typeArguments*/ undefined, [
80010             ts.createLiteral(parameterOffset),
80011             expression
80012         ]), location);
80013     }
80014     ts.paramHelper = {
80015         name: "typescript:param",
80016         importName: "__param",
80017         scoped: false,
80018         priority: 4,
80019         text: "\n            var __param = (this && this.__param) || function (paramIndex, decorator) {\n                return function (target, key) { decorator(target, key, paramIndex); }\n            };"
80020     };
80021 })(ts || (ts = {}));
80022 /*@internal*/
80023 var ts;
80024 (function (ts) {
80025     var ClassPropertySubstitutionFlags;
80026     (function (ClassPropertySubstitutionFlags) {
80027         /**
80028          * Enables substitutions for class expressions with static fields
80029          * which have initializers that reference the class name.
80030          */
80031         ClassPropertySubstitutionFlags[ClassPropertySubstitutionFlags["ClassAliases"] = 1] = "ClassAliases";
80032     })(ClassPropertySubstitutionFlags || (ClassPropertySubstitutionFlags = {}));
80033     var PrivateIdentifierPlacement;
80034     (function (PrivateIdentifierPlacement) {
80035         PrivateIdentifierPlacement[PrivateIdentifierPlacement["InstanceField"] = 0] = "InstanceField";
80036     })(PrivateIdentifierPlacement || (PrivateIdentifierPlacement = {}));
80037     /**
80038      * Transforms ECMAScript Class Syntax.
80039      * TypeScript parameter property syntax is transformed in the TypeScript transformer.
80040      * For now, this transforms public field declarations using TypeScript class semantics,
80041      * where declarations are elided and initializers are transformed as assignments in the constructor.
80042      * When --useDefineForClassFields is on, this transforms to ECMAScript semantics, with Object.defineProperty.
80043      */
80044     function transformClassFields(context) {
80045         var hoistVariableDeclaration = context.hoistVariableDeclaration, endLexicalEnvironment = context.endLexicalEnvironment, resumeLexicalEnvironment = context.resumeLexicalEnvironment;
80046         var resolver = context.getEmitResolver();
80047         var compilerOptions = context.getCompilerOptions();
80048         var languageVersion = ts.getEmitScriptTarget(compilerOptions);
80049         var shouldTransformPrivateFields = languageVersion < 99 /* ESNext */;
80050         var previousOnSubstituteNode = context.onSubstituteNode;
80051         context.onSubstituteNode = onSubstituteNode;
80052         var enabledSubstitutions;
80053         var classAliases;
80054         /**
80055          * Tracks what computed name expressions originating from elided names must be inlined
80056          * at the next execution site, in document order
80057          */
80058         var pendingExpressions;
80059         /**
80060          * Tracks what computed name expression statements and static property initializers must be
80061          * emitted at the next execution site, in document order (for decorated classes).
80062          */
80063         var pendingStatements;
80064         var privateIdentifierEnvironmentStack = [];
80065         var currentPrivateIdentifierEnvironment;
80066         return ts.chainBundle(transformSourceFile);
80067         function transformSourceFile(node) {
80068             var options = context.getCompilerOptions();
80069             if (node.isDeclarationFile
80070                 || options.useDefineForClassFields && options.target === 99 /* ESNext */) {
80071                 return node;
80072             }
80073             var visited = ts.visitEachChild(node, visitor, context);
80074             ts.addEmitHelpers(visited, context.readEmitHelpers());
80075             return visited;
80076         }
80077         function visitor(node) {
80078             if (!(node.transformFlags & 4194304 /* ContainsClassFields */))
80079                 return node;
80080             switch (node.kind) {
80081                 case 214 /* ClassExpression */:
80082                 case 245 /* ClassDeclaration */:
80083                     return visitClassLike(node);
80084                 case 159 /* PropertyDeclaration */:
80085                     return visitPropertyDeclaration(node);
80086                 case 225 /* VariableStatement */:
80087                     return visitVariableStatement(node);
80088                 case 154 /* ComputedPropertyName */:
80089                     return visitComputedPropertyName(node);
80090                 case 194 /* PropertyAccessExpression */:
80091                     return visitPropertyAccessExpression(node);
80092                 case 207 /* PrefixUnaryExpression */:
80093                     return visitPrefixUnaryExpression(node);
80094                 case 208 /* PostfixUnaryExpression */:
80095                     return visitPostfixUnaryExpression(node, /*valueIsDiscarded*/ false);
80096                 case 196 /* CallExpression */:
80097                     return visitCallExpression(node);
80098                 case 209 /* BinaryExpression */:
80099                     return visitBinaryExpression(node);
80100                 case 76 /* PrivateIdentifier */:
80101                     return visitPrivateIdentifier(node);
80102                 case 226 /* ExpressionStatement */:
80103                     return visitExpressionStatement(node);
80104                 case 230 /* ForStatement */:
80105                     return visitForStatement(node);
80106                 case 198 /* TaggedTemplateExpression */:
80107                     return visitTaggedTemplateExpression(node);
80108             }
80109             return ts.visitEachChild(node, visitor, context);
80110         }
80111         function visitorDestructuringTarget(node) {
80112             switch (node.kind) {
80113                 case 193 /* ObjectLiteralExpression */:
80114                 case 192 /* ArrayLiteralExpression */:
80115                     return visitAssignmentPattern(node);
80116                 default:
80117                     return visitor(node);
80118             }
80119         }
80120         /**
80121          * If we visit a private name, this means it is an undeclared private name.
80122          * Replace it with an empty identifier to indicate a problem with the code.
80123          */
80124         function visitPrivateIdentifier(node) {
80125             if (!shouldTransformPrivateFields) {
80126                 return node;
80127             }
80128             return ts.setOriginalNode(ts.createIdentifier(""), node);
80129         }
80130         /**
80131          * Visits the members of a class that has fields.
80132          *
80133          * @param node The node to visit.
80134          */
80135         function classElementVisitor(node) {
80136             switch (node.kind) {
80137                 case 162 /* Constructor */:
80138                     // Constructors for classes using class fields are transformed in
80139                     // `visitClassDeclaration` or `visitClassExpression`.
80140                     return undefined;
80141                 case 163 /* GetAccessor */:
80142                 case 164 /* SetAccessor */:
80143                 case 161 /* MethodDeclaration */:
80144                     // Visit the name of the member (if it's a computed property name).
80145                     return ts.visitEachChild(node, classElementVisitor, context);
80146                 case 159 /* PropertyDeclaration */:
80147                     return visitPropertyDeclaration(node);
80148                 case 154 /* ComputedPropertyName */:
80149                     return visitComputedPropertyName(node);
80150                 case 222 /* SemicolonClassElement */:
80151                     return node;
80152                 default:
80153                     return visitor(node);
80154             }
80155         }
80156         function visitVariableStatement(node) {
80157             var savedPendingStatements = pendingStatements;
80158             pendingStatements = [];
80159             var visitedNode = ts.visitEachChild(node, visitor, context);
80160             var statement = ts.some(pendingStatements) ? __spreadArrays([visitedNode], pendingStatements) :
80161                 visitedNode;
80162             pendingStatements = savedPendingStatements;
80163             return statement;
80164         }
80165         function visitComputedPropertyName(name) {
80166             var node = ts.visitEachChild(name, visitor, context);
80167             if (ts.some(pendingExpressions)) {
80168                 var expressions = pendingExpressions;
80169                 expressions.push(name.expression);
80170                 pendingExpressions = [];
80171                 node = ts.updateComputedPropertyName(node, ts.inlineExpressions(expressions));
80172             }
80173             return node;
80174         }
80175         function visitPropertyDeclaration(node) {
80176             ts.Debug.assert(!ts.some(node.decorators));
80177             if (!shouldTransformPrivateFields && ts.isPrivateIdentifier(node.name)) {
80178                 // Initializer is elided as the field is initialized in transformConstructor.
80179                 return ts.updateProperty(node, 
80180                 /*decorators*/ undefined, ts.visitNodes(node.modifiers, visitor, ts.isModifier), node.name, 
80181                 /*questionOrExclamationToken*/ undefined, 
80182                 /*type*/ undefined, 
80183                 /*initializer*/ undefined);
80184             }
80185             // Create a temporary variable to store a computed property name (if necessary).
80186             // If it's not inlineable, then we emit an expression after the class which assigns
80187             // the property name to the temporary variable.
80188             var expr = getPropertyNameExpressionIfNeeded(node.name, !!node.initializer || !!context.getCompilerOptions().useDefineForClassFields);
80189             if (expr && !ts.isSimpleInlineableExpression(expr)) {
80190                 (pendingExpressions || (pendingExpressions = [])).push(expr);
80191             }
80192             return undefined;
80193         }
80194         function createPrivateIdentifierAccess(info, receiver) {
80195             receiver = ts.visitNode(receiver, visitor, ts.isExpression);
80196             switch (info.placement) {
80197                 case 0 /* InstanceField */:
80198                     return createClassPrivateFieldGetHelper(context, ts.nodeIsSynthesized(receiver) ? receiver : ts.getSynthesizedClone(receiver), info.weakMapName);
80199                 default: return ts.Debug.fail("Unexpected private identifier placement");
80200             }
80201         }
80202         function visitPropertyAccessExpression(node) {
80203             if (shouldTransformPrivateFields && ts.isPrivateIdentifier(node.name)) {
80204                 var privateIdentifierInfo = accessPrivateIdentifier(node.name);
80205                 if (privateIdentifierInfo) {
80206                     return ts.setOriginalNode(createPrivateIdentifierAccess(privateIdentifierInfo, node.expression), node);
80207                 }
80208             }
80209             return ts.visitEachChild(node, visitor, context);
80210         }
80211         function visitPrefixUnaryExpression(node) {
80212             if (shouldTransformPrivateFields && ts.isPrivateIdentifierPropertyAccessExpression(node.operand)) {
80213                 var operator = node.operator === 45 /* PlusPlusToken */ ?
80214                     39 /* PlusToken */ : node.operator === 46 /* MinusMinusToken */ ?
80215                     40 /* MinusToken */ : undefined;
80216                 var info = void 0;
80217                 if (operator && (info = accessPrivateIdentifier(node.operand.name))) {
80218                     var receiver = ts.visitNode(node.operand.expression, visitor, ts.isExpression);
80219                     var _a = createCopiableReceiverExpr(receiver), readExpression = _a.readExpression, initializeExpression = _a.initializeExpression;
80220                     var existingValue = ts.createPrefix(39 /* PlusToken */, createPrivateIdentifierAccess(info, readExpression));
80221                     return ts.setOriginalNode(createPrivateIdentifierAssignment(info, initializeExpression || readExpression, ts.createBinary(existingValue, operator, ts.createLiteral(1)), 62 /* EqualsToken */), node);
80222                 }
80223             }
80224             return ts.visitEachChild(node, visitor, context);
80225         }
80226         function visitPostfixUnaryExpression(node, valueIsDiscarded) {
80227             if (shouldTransformPrivateFields && ts.isPrivateIdentifierPropertyAccessExpression(node.operand)) {
80228                 var operator = node.operator === 45 /* PlusPlusToken */ ?
80229                     39 /* PlusToken */ : node.operator === 46 /* MinusMinusToken */ ?
80230                     40 /* MinusToken */ : undefined;
80231                 var info = void 0;
80232                 if (operator && (info = accessPrivateIdentifier(node.operand.name))) {
80233                     var receiver = ts.visitNode(node.operand.expression, visitor, ts.isExpression);
80234                     var _a = createCopiableReceiverExpr(receiver), readExpression = _a.readExpression, initializeExpression = _a.initializeExpression;
80235                     var existingValue = ts.createPrefix(39 /* PlusToken */, createPrivateIdentifierAccess(info, readExpression));
80236                     // Create a temporary variable to store the value returned by the expression.
80237                     var returnValue = valueIsDiscarded ? undefined : ts.createTempVariable(hoistVariableDeclaration);
80238                     return ts.setOriginalNode(ts.inlineExpressions(ts.compact([
80239                         createPrivateIdentifierAssignment(info, initializeExpression || readExpression, ts.createBinary(returnValue ? ts.createAssignment(returnValue, existingValue) : existingValue, operator, ts.createLiteral(1)), 62 /* EqualsToken */),
80240                         returnValue
80241                     ])), node);
80242                 }
80243             }
80244             return ts.visitEachChild(node, visitor, context);
80245         }
80246         function visitForStatement(node) {
80247             if (node.incrementor && ts.isPostfixUnaryExpression(node.incrementor)) {
80248                 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));
80249             }
80250             return ts.visitEachChild(node, visitor, context);
80251         }
80252         function visitExpressionStatement(node) {
80253             if (ts.isPostfixUnaryExpression(node.expression)) {
80254                 return ts.updateExpressionStatement(node, visitPostfixUnaryExpression(node.expression, /*valueIsDiscarded*/ true));
80255             }
80256             return ts.visitEachChild(node, visitor, context);
80257         }
80258         function createCopiableReceiverExpr(receiver) {
80259             var clone = ts.nodeIsSynthesized(receiver) ? receiver : ts.getSynthesizedClone(receiver);
80260             if (ts.isSimpleInlineableExpression(receiver)) {
80261                 return { readExpression: clone, initializeExpression: undefined };
80262             }
80263             var readExpression = ts.createTempVariable(hoistVariableDeclaration);
80264             var initializeExpression = ts.createAssignment(readExpression, clone);
80265             return { readExpression: readExpression, initializeExpression: initializeExpression };
80266         }
80267         function visitCallExpression(node) {
80268             if (shouldTransformPrivateFields && ts.isPrivateIdentifierPropertyAccessExpression(node.expression)) {
80269                 // Transform call expressions of private names to properly bind the `this` parameter.
80270                 var _a = ts.createCallBinding(node.expression, hoistVariableDeclaration, languageVersion), thisArg = _a.thisArg, target = _a.target;
80271                 return ts.updateCall(node, ts.createPropertyAccess(ts.visitNode(target, visitor), "call"), 
80272                 /*typeArguments*/ undefined, __spreadArrays([ts.visitNode(thisArg, visitor, ts.isExpression)], ts.visitNodes(node.arguments, visitor, ts.isExpression)));
80273             }
80274             return ts.visitEachChild(node, visitor, context);
80275         }
80276         function visitTaggedTemplateExpression(node) {
80277             if (shouldTransformPrivateFields && ts.isPrivateIdentifierPropertyAccessExpression(node.tag)) {
80278                 // Bind the `this` correctly for tagged template literals when the tag is a private identifier property access.
80279                 var _a = ts.createCallBinding(node.tag, hoistVariableDeclaration, languageVersion), thisArg = _a.thisArg, target = _a.target;
80280                 return ts.updateTaggedTemplate(node, ts.createCall(ts.createPropertyAccess(ts.visitNode(target, visitor), "bind"), 
80281                 /*typeArguments*/ undefined, [ts.visitNode(thisArg, visitor, ts.isExpression)]), ts.visitNode(node.template, visitor, ts.isTemplateLiteral));
80282             }
80283             return ts.visitEachChild(node, visitor, context);
80284         }
80285         function visitBinaryExpression(node) {
80286             if (shouldTransformPrivateFields) {
80287                 if (ts.isDestructuringAssignment(node)) {
80288                     var savedPendingExpressions = pendingExpressions;
80289                     pendingExpressions = undefined;
80290                     node = ts.updateBinary(node, ts.visitNode(node.left, visitorDestructuringTarget), ts.visitNode(node.right, visitor), node.operatorToken);
80291                     var expr = ts.some(pendingExpressions) ?
80292                         ts.inlineExpressions(ts.compact(__spreadArrays(pendingExpressions, [node]))) :
80293                         node;
80294                     pendingExpressions = savedPendingExpressions;
80295                     return expr;
80296                 }
80297                 if (ts.isAssignmentExpression(node) && ts.isPrivateIdentifierPropertyAccessExpression(node.left)) {
80298                     var info = accessPrivateIdentifier(node.left.name);
80299                     if (info) {
80300                         return ts.setOriginalNode(createPrivateIdentifierAssignment(info, node.left.expression, node.right, node.operatorToken.kind), node);
80301                     }
80302                 }
80303             }
80304             return ts.visitEachChild(node, visitor, context);
80305         }
80306         function createPrivateIdentifierAssignment(info, receiver, right, operator) {
80307             switch (info.placement) {
80308                 case 0 /* InstanceField */: {
80309                     return createPrivateIdentifierInstanceFieldAssignment(info, receiver, right, operator);
80310                 }
80311                 default: return ts.Debug.fail("Unexpected private identifier placement");
80312             }
80313         }
80314         function createPrivateIdentifierInstanceFieldAssignment(info, receiver, right, operator) {
80315             receiver = ts.visitNode(receiver, visitor, ts.isExpression);
80316             right = ts.visitNode(right, visitor, ts.isExpression);
80317             if (ts.isCompoundAssignment(operator)) {
80318                 var _a = createCopiableReceiverExpr(receiver), readExpression = _a.readExpression, initializeExpression = _a.initializeExpression;
80319                 return createClassPrivateFieldSetHelper(context, initializeExpression || readExpression, info.weakMapName, ts.createBinary(createClassPrivateFieldGetHelper(context, readExpression, info.weakMapName), ts.getNonAssignmentOperatorForCompoundAssignment(operator), right));
80320             }
80321             else {
80322                 return createClassPrivateFieldSetHelper(context, receiver, info.weakMapName, right);
80323             }
80324         }
80325         /**
80326          * Set up the environment for a class.
80327          */
80328         function visitClassLike(node) {
80329             var savedPendingExpressions = pendingExpressions;
80330             pendingExpressions = undefined;
80331             if (shouldTransformPrivateFields) {
80332                 startPrivateIdentifierEnvironment();
80333             }
80334             var result = ts.isClassDeclaration(node) ?
80335                 visitClassDeclaration(node) :
80336                 visitClassExpression(node);
80337             if (shouldTransformPrivateFields) {
80338                 endPrivateIdentifierEnvironment();
80339             }
80340             pendingExpressions = savedPendingExpressions;
80341             return result;
80342         }
80343         function doesClassElementNeedTransform(node) {
80344             return ts.isPropertyDeclaration(node) || (shouldTransformPrivateFields && node.name && ts.isPrivateIdentifier(node.name));
80345         }
80346         function visitClassDeclaration(node) {
80347             if (!ts.forEach(node.members, doesClassElementNeedTransform)) {
80348                 return ts.visitEachChild(node, visitor, context);
80349             }
80350             var extendsClauseElement = ts.getEffectiveBaseTypeNode(node);
80351             var isDerivedClass = !!(extendsClauseElement && ts.skipOuterExpressions(extendsClauseElement.expression).kind !== 100 /* NullKeyword */);
80352             var statements = [
80353                 ts.updateClassDeclaration(node, 
80354                 /*decorators*/ undefined, node.modifiers, node.name, 
80355                 /*typeParameters*/ undefined, ts.visitNodes(node.heritageClauses, visitor, ts.isHeritageClause), transformClassMembers(node, isDerivedClass))
80356             ];
80357             // Write any pending expressions from elided or moved computed property names
80358             if (ts.some(pendingExpressions)) {
80359                 statements.push(ts.createExpressionStatement(ts.inlineExpressions(pendingExpressions)));
80360             }
80361             // Emit static property assignment. Because classDeclaration is lexically evaluated,
80362             // it is safe to emit static property assignment after classDeclaration
80363             // From ES6 specification:
80364             //      HasLexicalDeclaration (N) : Determines if the argument identifier has a binding in this environment record that was created using
80365             //                                  a lexical declaration such as a LexicalDeclaration or a ClassDeclaration.
80366             var staticProperties = ts.getProperties(node, /*requireInitializer*/ true, /*isStatic*/ true);
80367             if (ts.some(staticProperties)) {
80368                 addPropertyStatements(statements, staticProperties, ts.getInternalName(node));
80369             }
80370             return statements;
80371         }
80372         function visitClassExpression(node) {
80373             if (!ts.forEach(node.members, doesClassElementNeedTransform)) {
80374                 return ts.visitEachChild(node, visitor, context);
80375             }
80376             // If this class expression is a transformation of a decorated class declaration,
80377             // then we want to output the pendingExpressions as statements, not as inlined
80378             // expressions with the class statement.
80379             //
80380             // In this case, we use pendingStatements to produce the same output as the
80381             // class declaration transformation. The VariableStatement visitor will insert
80382             // these statements after the class expression variable statement.
80383             var isDecoratedClassDeclaration = ts.isClassDeclaration(ts.getOriginalNode(node));
80384             var staticProperties = ts.getProperties(node, /*requireInitializer*/ true, /*isStatic*/ true);
80385             var extendsClauseElement = ts.getEffectiveBaseTypeNode(node);
80386             var isDerivedClass = !!(extendsClauseElement && ts.skipOuterExpressions(extendsClauseElement.expression).kind !== 100 /* NullKeyword */);
80387             var classExpression = ts.updateClassExpression(node, node.modifiers, node.name, 
80388             /*typeParameters*/ undefined, ts.visitNodes(node.heritageClauses, visitor, ts.isHeritageClause), transformClassMembers(node, isDerivedClass));
80389             if (ts.some(staticProperties) || ts.some(pendingExpressions)) {
80390                 if (isDecoratedClassDeclaration) {
80391                     ts.Debug.assertIsDefined(pendingStatements, "Decorated classes transformed by TypeScript are expected to be within a variable declaration.");
80392                     // Write any pending expressions from elided or moved computed property names
80393                     if (pendingStatements && pendingExpressions && ts.some(pendingExpressions)) {
80394                         pendingStatements.push(ts.createExpressionStatement(ts.inlineExpressions(pendingExpressions)));
80395                     }
80396                     if (pendingStatements && ts.some(staticProperties)) {
80397                         addPropertyStatements(pendingStatements, staticProperties, ts.getInternalName(node));
80398                     }
80399                     return classExpression;
80400                 }
80401                 else {
80402                     var expressions = [];
80403                     var isClassWithConstructorReference = resolver.getNodeCheckFlags(node) & 16777216 /* ClassWithConstructorReference */;
80404                     var temp = ts.createTempVariable(hoistVariableDeclaration, !!isClassWithConstructorReference);
80405                     if (isClassWithConstructorReference) {
80406                         // record an alias as the class name is not in scope for statics.
80407                         enableSubstitutionForClassAliases();
80408                         var alias = ts.getSynthesizedClone(temp);
80409                         alias.autoGenerateFlags &= ~8 /* ReservedInNestedScopes */;
80410                         classAliases[ts.getOriginalNodeId(node)] = alias;
80411                     }
80412                     // To preserve the behavior of the old emitter, we explicitly indent
80413                     // the body of a class with static initializers.
80414                     ts.setEmitFlags(classExpression, 65536 /* Indented */ | ts.getEmitFlags(classExpression));
80415                     expressions.push(ts.startOnNewLine(ts.createAssignment(temp, classExpression)));
80416                     // Add any pending expressions leftover from elided or relocated computed property names
80417                     ts.addRange(expressions, ts.map(pendingExpressions, ts.startOnNewLine));
80418                     ts.addRange(expressions, generateInitializedPropertyExpressions(staticProperties, temp));
80419                     expressions.push(ts.startOnNewLine(temp));
80420                     return ts.inlineExpressions(expressions);
80421                 }
80422             }
80423             return classExpression;
80424         }
80425         function transformClassMembers(node, isDerivedClass) {
80426             if (shouldTransformPrivateFields) {
80427                 // Declare private names.
80428                 for (var _i = 0, _a = node.members; _i < _a.length; _i++) {
80429                     var member = _a[_i];
80430                     if (ts.isPrivateIdentifierPropertyDeclaration(member)) {
80431                         addPrivateIdentifierToEnvironment(member.name);
80432                     }
80433                 }
80434             }
80435             var members = [];
80436             var constructor = transformConstructor(node, isDerivedClass);
80437             if (constructor) {
80438                 members.push(constructor);
80439             }
80440             ts.addRange(members, ts.visitNodes(node.members, classElementVisitor, ts.isClassElement));
80441             return ts.setTextRange(ts.createNodeArray(members), /*location*/ node.members);
80442         }
80443         function isPropertyDeclarationThatRequiresConstructorStatement(member) {
80444             if (!ts.isPropertyDeclaration(member) || ts.hasStaticModifier(member)) {
80445                 return false;
80446             }
80447             if (context.getCompilerOptions().useDefineForClassFields) {
80448                 // If we are using define semantics and targeting ESNext or higher,
80449                 // then we don't need to transform any class properties.
80450                 return languageVersion < 99 /* ESNext */;
80451             }
80452             return ts.isInitializedProperty(member) || shouldTransformPrivateFields && ts.isPrivateIdentifierPropertyDeclaration(member);
80453         }
80454         function transformConstructor(node, isDerivedClass) {
80455             var constructor = ts.visitNode(ts.getFirstConstructorWithBody(node), visitor, ts.isConstructorDeclaration);
80456             var properties = node.members.filter(isPropertyDeclarationThatRequiresConstructorStatement);
80457             if (!ts.some(properties)) {
80458                 return constructor;
80459             }
80460             var parameters = ts.visitParameterList(constructor ? constructor.parameters : undefined, visitor, context);
80461             var body = transformConstructorBody(node, constructor, isDerivedClass);
80462             if (!body) {
80463                 return undefined;
80464             }
80465             return ts.startOnNewLine(ts.setOriginalNode(ts.setTextRange(ts.createConstructor(
80466             /*decorators*/ undefined, 
80467             /*modifiers*/ undefined, parameters !== null && parameters !== void 0 ? parameters : [], body), constructor || node), constructor));
80468         }
80469         function transformConstructorBody(node, constructor, isDerivedClass) {
80470             var useDefineForClassFields = context.getCompilerOptions().useDefineForClassFields;
80471             var properties = ts.getProperties(node, /*requireInitializer*/ false, /*isStatic*/ false);
80472             if (!useDefineForClassFields) {
80473                 properties = ts.filter(properties, function (property) { return !!property.initializer || ts.isPrivateIdentifier(property.name); });
80474             }
80475             // Only generate synthetic constructor when there are property initializers to move.
80476             if (!constructor && !ts.some(properties)) {
80477                 return ts.visitFunctionBody(/*node*/ undefined, visitor, context);
80478             }
80479             resumeLexicalEnvironment();
80480             var indexOfFirstStatement = 0;
80481             var statements = [];
80482             if (!constructor && isDerivedClass) {
80483                 // Add a synthetic `super` call:
80484                 //
80485                 //  super(...arguments);
80486                 //
80487                 statements.push(ts.createExpressionStatement(ts.createCall(ts.createSuper(), 
80488                 /*typeArguments*/ undefined, [ts.createSpread(ts.createIdentifier("arguments"))])));
80489             }
80490             if (constructor) {
80491                 indexOfFirstStatement = ts.addPrologueDirectivesAndInitialSuperCall(constructor, statements, visitor);
80492             }
80493             // Add the property initializers. Transforms this:
80494             //
80495             //  public x = 1;
80496             //
80497             // Into this:
80498             //
80499             //  constructor() {
80500             //      this.x = 1;
80501             //  }
80502             //
80503             if (constructor === null || constructor === void 0 ? void 0 : constructor.body) {
80504                 var afterParameterProperties = ts.findIndex(constructor.body.statements, function (s) { return !ts.isParameterPropertyDeclaration(ts.getOriginalNode(s), constructor); }, indexOfFirstStatement);
80505                 if (afterParameterProperties === -1) {
80506                     afterParameterProperties = constructor.body.statements.length;
80507                 }
80508                 if (afterParameterProperties > indexOfFirstStatement) {
80509                     if (!useDefineForClassFields) {
80510                         ts.addRange(statements, ts.visitNodes(constructor.body.statements, visitor, ts.isStatement, indexOfFirstStatement, afterParameterProperties - indexOfFirstStatement));
80511                     }
80512                     indexOfFirstStatement = afterParameterProperties;
80513                 }
80514             }
80515             addPropertyStatements(statements, properties, ts.createThis());
80516             // Add existing statements, skipping the initial super call.
80517             if (constructor) {
80518                 ts.addRange(statements, ts.visitNodes(constructor.body.statements, visitor, ts.isStatement, indexOfFirstStatement));
80519             }
80520             statements = ts.mergeLexicalEnvironment(statements, endLexicalEnvironment());
80521             return ts.setTextRange(ts.createBlock(ts.setTextRange(ts.createNodeArray(statements), 
80522             /*location*/ constructor ? constructor.body.statements : node.members), 
80523             /*multiLine*/ true), 
80524             /*location*/ constructor ? constructor.body : undefined);
80525         }
80526         /**
80527          * Generates assignment statements for property initializers.
80528          *
80529          * @param properties An array of property declarations to transform.
80530          * @param receiver The receiver on which each property should be assigned.
80531          */
80532         function addPropertyStatements(statements, properties, receiver) {
80533             for (var _i = 0, properties_8 = properties; _i < properties_8.length; _i++) {
80534                 var property = properties_8[_i];
80535                 var expression = transformProperty(property, receiver);
80536                 if (!expression) {
80537                     continue;
80538                 }
80539                 var statement = ts.createExpressionStatement(expression);
80540                 ts.setSourceMapRange(statement, ts.moveRangePastModifiers(property));
80541                 ts.setCommentRange(statement, property);
80542                 ts.setOriginalNode(statement, property);
80543                 statements.push(statement);
80544             }
80545         }
80546         /**
80547          * Generates assignment expressions for property initializers.
80548          *
80549          * @param properties An array of property declarations to transform.
80550          * @param receiver The receiver on which each property should be assigned.
80551          */
80552         function generateInitializedPropertyExpressions(properties, receiver) {
80553             var expressions = [];
80554             for (var _i = 0, properties_9 = properties; _i < properties_9.length; _i++) {
80555                 var property = properties_9[_i];
80556                 var expression = transformProperty(property, receiver);
80557                 if (!expression) {
80558                     continue;
80559                 }
80560                 ts.startOnNewLine(expression);
80561                 ts.setSourceMapRange(expression, ts.moveRangePastModifiers(property));
80562                 ts.setCommentRange(expression, property);
80563                 ts.setOriginalNode(expression, property);
80564                 expressions.push(expression);
80565             }
80566             return expressions;
80567         }
80568         /**
80569          * Transforms a property initializer into an assignment statement.
80570          *
80571          * @param property The property declaration.
80572          * @param receiver The object receiving the property assignment.
80573          */
80574         function transformProperty(property, receiver) {
80575             // We generate a name here in order to reuse the value cached by the relocated computed name expression (which uses the same generated name)
80576             var emitAssignment = !context.getCompilerOptions().useDefineForClassFields;
80577             var propertyName = ts.isComputedPropertyName(property.name) && !ts.isSimpleInlineableExpression(property.name.expression)
80578                 ? ts.updateComputedPropertyName(property.name, ts.getGeneratedNameForNode(property.name))
80579                 : property.name;
80580             if (shouldTransformPrivateFields && ts.isPrivateIdentifier(propertyName)) {
80581                 var privateIdentifierInfo = accessPrivateIdentifier(propertyName);
80582                 if (privateIdentifierInfo) {
80583                     switch (privateIdentifierInfo.placement) {
80584                         case 0 /* InstanceField */: {
80585                             return createPrivateInstanceFieldInitializer(receiver, ts.visitNode(property.initializer, visitor, ts.isExpression), privateIdentifierInfo.weakMapName);
80586                         }
80587                     }
80588                 }
80589                 else {
80590                     ts.Debug.fail("Undeclared private name for property declaration.");
80591                 }
80592             }
80593             if (ts.isPrivateIdentifier(propertyName) && !property.initializer) {
80594                 return undefined;
80595             }
80596             if (ts.isPrivateIdentifier(propertyName) && !property.initializer) {
80597                 return undefined;
80598             }
80599             var propertyOriginalNode = ts.getOriginalNode(property);
80600             var initializer = property.initializer || emitAssignment ? ts.visitNode(property.initializer, visitor, ts.isExpression)
80601                 : ts.isParameterPropertyDeclaration(propertyOriginalNode, propertyOriginalNode.parent) && ts.isIdentifier(propertyName) ? propertyName
80602                     : ts.createVoidZero();
80603             if (emitAssignment || ts.isPrivateIdentifier(propertyName)) {
80604                 var memberAccess = ts.createMemberAccessForPropertyName(receiver, propertyName, /*location*/ propertyName);
80605                 return ts.createAssignment(memberAccess, initializer);
80606             }
80607             else {
80608                 var name = ts.isComputedPropertyName(propertyName) ? propertyName.expression
80609                     : ts.isIdentifier(propertyName) ? ts.createStringLiteral(ts.unescapeLeadingUnderscores(propertyName.escapedText))
80610                         : propertyName;
80611                 var descriptor = ts.createPropertyDescriptor({ value: initializer, configurable: true, writable: true, enumerable: true });
80612                 return ts.createObjectDefinePropertyCall(receiver, name, descriptor);
80613             }
80614         }
80615         function enableSubstitutionForClassAliases() {
80616             if ((enabledSubstitutions & 1 /* ClassAliases */) === 0) {
80617                 enabledSubstitutions |= 1 /* ClassAliases */;
80618                 // We need to enable substitutions for identifiers. This allows us to
80619                 // substitute class names inside of a class declaration.
80620                 context.enableSubstitution(75 /* Identifier */);
80621                 // Keep track of class aliases.
80622                 classAliases = [];
80623             }
80624         }
80625         /**
80626          * Hooks node substitutions.
80627          *
80628          * @param hint The context for the emitter.
80629          * @param node The node to substitute.
80630          */
80631         function onSubstituteNode(hint, node) {
80632             node = previousOnSubstituteNode(hint, node);
80633             if (hint === 1 /* Expression */) {
80634                 return substituteExpression(node);
80635             }
80636             return node;
80637         }
80638         function substituteExpression(node) {
80639             switch (node.kind) {
80640                 case 75 /* Identifier */:
80641                     return substituteExpressionIdentifier(node);
80642             }
80643             return node;
80644         }
80645         function substituteExpressionIdentifier(node) {
80646             return trySubstituteClassAlias(node) || node;
80647         }
80648         function trySubstituteClassAlias(node) {
80649             if (enabledSubstitutions & 1 /* ClassAliases */) {
80650                 if (resolver.getNodeCheckFlags(node) & 33554432 /* ConstructorReferenceInClass */) {
80651                     // Due to the emit for class decorators, any reference to the class from inside of the class body
80652                     // must instead be rewritten to point to a temporary variable to avoid issues with the double-bind
80653                     // behavior of class names in ES6.
80654                     // Also, when emitting statics for class expressions, we must substitute a class alias for
80655                     // constructor references in static property initializers.
80656                     var declaration = resolver.getReferencedValueDeclaration(node);
80657                     if (declaration) {
80658                         var classAlias = classAliases[declaration.id]; // TODO: GH#18217
80659                         if (classAlias) {
80660                             var clone_2 = ts.getSynthesizedClone(classAlias);
80661                             ts.setSourceMapRange(clone_2, node);
80662                             ts.setCommentRange(clone_2, node);
80663                             return clone_2;
80664                         }
80665                     }
80666                 }
80667             }
80668             return undefined;
80669         }
80670         /**
80671          * If the name is a computed property, this function transforms it, then either returns an expression which caches the
80672          * value of the result or the expression itself if the value is either unused or safe to inline into multiple locations
80673          * @param shouldHoist Does the expression need to be reused? (ie, for an initializer or a decorator)
80674          */
80675         function getPropertyNameExpressionIfNeeded(name, shouldHoist) {
80676             if (ts.isComputedPropertyName(name)) {
80677                 var expression = ts.visitNode(name.expression, visitor, ts.isExpression);
80678                 var innerExpression = ts.skipPartiallyEmittedExpressions(expression);
80679                 var inlinable = ts.isSimpleInlineableExpression(innerExpression);
80680                 var alreadyTransformed = ts.isAssignmentExpression(innerExpression) && ts.isGeneratedIdentifier(innerExpression.left);
80681                 if (!alreadyTransformed && !inlinable && shouldHoist) {
80682                     var generatedName = ts.getGeneratedNameForNode(name);
80683                     hoistVariableDeclaration(generatedName);
80684                     return ts.createAssignment(generatedName, expression);
80685                 }
80686                 return (inlinable || ts.isIdentifier(innerExpression)) ? undefined : expression;
80687             }
80688         }
80689         function startPrivateIdentifierEnvironment() {
80690             privateIdentifierEnvironmentStack.push(currentPrivateIdentifierEnvironment);
80691             currentPrivateIdentifierEnvironment = undefined;
80692         }
80693         function endPrivateIdentifierEnvironment() {
80694             currentPrivateIdentifierEnvironment = privateIdentifierEnvironmentStack.pop();
80695         }
80696         function addPrivateIdentifierToEnvironment(name) {
80697             var text = ts.getTextOfPropertyName(name);
80698             var weakMapName = ts.createOptimisticUniqueName("_" + text.substring(1));
80699             weakMapName.autoGenerateFlags |= 8 /* ReservedInNestedScopes */;
80700             hoistVariableDeclaration(weakMapName);
80701             (currentPrivateIdentifierEnvironment || (currentPrivateIdentifierEnvironment = ts.createUnderscoreEscapedMap()))
80702                 .set(name.escapedText, { placement: 0 /* InstanceField */, weakMapName: weakMapName });
80703             (pendingExpressions || (pendingExpressions = [])).push(ts.createAssignment(weakMapName, ts.createNew(ts.createIdentifier("WeakMap"), 
80704             /*typeArguments*/ undefined, [])));
80705         }
80706         function accessPrivateIdentifier(name) {
80707             if (currentPrivateIdentifierEnvironment) {
80708                 var info = currentPrivateIdentifierEnvironment.get(name.escapedText);
80709                 if (info) {
80710                     return info;
80711                 }
80712             }
80713             for (var i = privateIdentifierEnvironmentStack.length - 1; i >= 0; --i) {
80714                 var env = privateIdentifierEnvironmentStack[i];
80715                 if (!env) {
80716                     continue;
80717                 }
80718                 var info = env.get(name.escapedText);
80719                 if (info) {
80720                     return info;
80721                 }
80722             }
80723             return undefined;
80724         }
80725         function wrapPrivateIdentifierForDestructuringTarget(node) {
80726             var parameter = ts.getGeneratedNameForNode(node);
80727             var info = accessPrivateIdentifier(node.name);
80728             if (!info) {
80729                 return ts.visitEachChild(node, visitor, context);
80730             }
80731             var receiver = node.expression;
80732             // We cannot copy `this` or `super` into the function because they will be bound
80733             // differently inside the function.
80734             if (ts.isThisProperty(node) || ts.isSuperProperty(node) || !ts.isSimpleCopiableExpression(node.expression)) {
80735                 receiver = ts.createTempVariable(hoistVariableDeclaration);
80736                 receiver.autoGenerateFlags |= 8 /* ReservedInNestedScopes */;
80737                 (pendingExpressions || (pendingExpressions = [])).push(ts.createBinary(receiver, 62 /* EqualsToken */, node.expression));
80738             }
80739             return ts.createPropertyAccess(
80740             // Explicit parens required because of v8 regression (https://bugs.chromium.org/p/v8/issues/detail?id=9560)
80741             ts.createParen(ts.createObjectLiteral([
80742                 ts.createSetAccessor(
80743                 /*decorators*/ undefined, 
80744                 /*modifiers*/ undefined, "value", [ts.createParameter(
80745                     /*decorators*/ undefined, 
80746                     /*modifiers*/ undefined, 
80747                     /*dotDotDotToken*/ undefined, parameter, 
80748                     /*questionToken*/ undefined, 
80749                     /*type*/ undefined, 
80750                     /*initializer*/ undefined)], ts.createBlock([ts.createExpressionStatement(createPrivateIdentifierAssignment(info, receiver, parameter, 62 /* EqualsToken */))]))
80751             ])), "value");
80752         }
80753         function visitArrayAssignmentTarget(node) {
80754             var target = ts.getTargetOfBindingOrAssignmentElement(node);
80755             if (target && ts.isPrivateIdentifierPropertyAccessExpression(target)) {
80756                 var wrapped = wrapPrivateIdentifierForDestructuringTarget(target);
80757                 if (ts.isAssignmentExpression(node)) {
80758                     return ts.updateBinary(node, wrapped, ts.visitNode(node.right, visitor, ts.isExpression), node.operatorToken);
80759                 }
80760                 else if (ts.isSpreadElement(node)) {
80761                     return ts.updateSpread(node, wrapped);
80762                 }
80763                 else {
80764                     return wrapped;
80765                 }
80766             }
80767             return ts.visitNode(node, visitorDestructuringTarget);
80768         }
80769         function visitObjectAssignmentTarget(node) {
80770             if (ts.isPropertyAssignment(node)) {
80771                 var target = ts.getTargetOfBindingOrAssignmentElement(node);
80772                 if (target && ts.isPrivateIdentifierPropertyAccessExpression(target)) {
80773                     var initializer = ts.getInitializerOfBindingOrAssignmentElement(node);
80774                     var wrapped = wrapPrivateIdentifierForDestructuringTarget(target);
80775                     return ts.updatePropertyAssignment(node, ts.visitNode(node.name, visitor), initializer ? ts.createAssignment(wrapped, ts.visitNode(initializer, visitor)) : wrapped);
80776                 }
80777                 return ts.updatePropertyAssignment(node, ts.visitNode(node.name, visitor), ts.visitNode(node.initializer, visitorDestructuringTarget));
80778             }
80779             return ts.visitNode(node, visitor);
80780         }
80781         function visitAssignmentPattern(node) {
80782             if (ts.isArrayLiteralExpression(node)) {
80783                 // Transforms private names in destructuring assignment array bindings.
80784                 //
80785                 // Source:
80786                 // ([ this.#myProp ] = [ "hello" ]);
80787                 //
80788                 // Transformation:
80789                 // [ { set value(x) { this.#myProp = x; } }.value ] = [ "hello" ];
80790                 return ts.updateArrayLiteral(node, ts.visitNodes(node.elements, visitArrayAssignmentTarget, ts.isExpression));
80791             }
80792             else {
80793                 // Transforms private names in destructuring assignment object bindings.
80794                 //
80795                 // Source:
80796                 // ({ stringProperty: this.#myProp } = { stringProperty: "hello" });
80797                 //
80798                 // Transformation:
80799                 // ({ stringProperty: { set value(x) { this.#myProp = x; } }.value }) = { stringProperty: "hello" };
80800                 return ts.updateObjectLiteral(node, ts.visitNodes(node.properties, visitObjectAssignmentTarget, ts.isObjectLiteralElementLike));
80801             }
80802         }
80803     }
80804     ts.transformClassFields = transformClassFields;
80805     function createPrivateInstanceFieldInitializer(receiver, initializer, weakMapName) {
80806         return ts.createCall(ts.createPropertyAccess(weakMapName, "set"), 
80807         /*typeArguments*/ undefined, [receiver, initializer || ts.createVoidZero()]);
80808     }
80809     ts.classPrivateFieldGetHelper = {
80810         name: "typescript:classPrivateFieldGet",
80811         scoped: false,
80812         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            };"
80813     };
80814     function createClassPrivateFieldGetHelper(context, receiver, privateField) {
80815         context.requestEmitHelper(ts.classPrivateFieldGetHelper);
80816         return ts.createCall(ts.getUnscopedHelperName("__classPrivateFieldGet"), /* typeArguments */ undefined, [receiver, privateField]);
80817     }
80818     ts.classPrivateFieldSetHelper = {
80819         name: "typescript:classPrivateFieldSet",
80820         scoped: false,
80821         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            };"
80822     };
80823     function createClassPrivateFieldSetHelper(context, receiver, privateField, value) {
80824         context.requestEmitHelper(ts.classPrivateFieldSetHelper);
80825         return ts.createCall(ts.getUnscopedHelperName("__classPrivateFieldSet"), /* typeArguments */ undefined, [receiver, privateField, value]);
80826     }
80827 })(ts || (ts = {}));
80828 /*@internal*/
80829 var ts;
80830 (function (ts) {
80831     var ES2017SubstitutionFlags;
80832     (function (ES2017SubstitutionFlags) {
80833         /** Enables substitutions for async methods with `super` calls. */
80834         ES2017SubstitutionFlags[ES2017SubstitutionFlags["AsyncMethodsWithSuper"] = 1] = "AsyncMethodsWithSuper";
80835     })(ES2017SubstitutionFlags || (ES2017SubstitutionFlags = {}));
80836     var ContextFlags;
80837     (function (ContextFlags) {
80838         ContextFlags[ContextFlags["NonTopLevel"] = 1] = "NonTopLevel";
80839         ContextFlags[ContextFlags["HasLexicalThis"] = 2] = "HasLexicalThis";
80840     })(ContextFlags || (ContextFlags = {}));
80841     function transformES2017(context) {
80842         var resumeLexicalEnvironment = context.resumeLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistVariableDeclaration = context.hoistVariableDeclaration;
80843         var resolver = context.getEmitResolver();
80844         var compilerOptions = context.getCompilerOptions();
80845         var languageVersion = ts.getEmitScriptTarget(compilerOptions);
80846         /**
80847          * Keeps track of whether expression substitution has been enabled for specific edge cases.
80848          * They are persisted between each SourceFile transformation and should not be reset.
80849          */
80850         var enabledSubstitutions;
80851         /**
80852          * This keeps track of containers where `super` is valid, for use with
80853          * just-in-time substitution for `super` expressions inside of async methods.
80854          */
80855         var enclosingSuperContainerFlags = 0;
80856         var enclosingFunctionParameterNames;
80857         /**
80858          * Keeps track of property names accessed on super (`super.x`) within async functions.
80859          */
80860         var capturedSuperProperties;
80861         /** Whether the async function contains an element access on super (`super[x]`). */
80862         var hasSuperElementAccess;
80863         /** A set of node IDs for generated super accessors (variable statements). */
80864         var substitutedSuperAccessors = [];
80865         var contextFlags = 0;
80866         // Save the previous transformation hooks.
80867         var previousOnEmitNode = context.onEmitNode;
80868         var previousOnSubstituteNode = context.onSubstituteNode;
80869         // Set new transformation hooks.
80870         context.onEmitNode = onEmitNode;
80871         context.onSubstituteNode = onSubstituteNode;
80872         return ts.chainBundle(transformSourceFile);
80873         function transformSourceFile(node) {
80874             if (node.isDeclarationFile) {
80875                 return node;
80876             }
80877             setContextFlag(1 /* NonTopLevel */, false);
80878             setContextFlag(2 /* HasLexicalThis */, !ts.isEffectiveStrictModeSourceFile(node, compilerOptions));
80879             var visited = ts.visitEachChild(node, visitor, context);
80880             ts.addEmitHelpers(visited, context.readEmitHelpers());
80881             return visited;
80882         }
80883         function setContextFlag(flag, val) {
80884             contextFlags = val ? contextFlags | flag : contextFlags & ~flag;
80885         }
80886         function inContext(flags) {
80887             return (contextFlags & flags) !== 0;
80888         }
80889         function inTopLevelContext() {
80890             return !inContext(1 /* NonTopLevel */);
80891         }
80892         function inHasLexicalThisContext() {
80893             return inContext(2 /* HasLexicalThis */);
80894         }
80895         function doWithContext(flags, cb, value) {
80896             var contextFlagsToSet = flags & ~contextFlags;
80897             if (contextFlagsToSet) {
80898                 setContextFlag(contextFlagsToSet, /*val*/ true);
80899                 var result = cb(value);
80900                 setContextFlag(contextFlagsToSet, /*val*/ false);
80901                 return result;
80902             }
80903             return cb(value);
80904         }
80905         function visitDefault(node) {
80906             return ts.visitEachChild(node, visitor, context);
80907         }
80908         function visitor(node) {
80909             if ((node.transformFlags & 64 /* ContainsES2017 */) === 0) {
80910                 return node;
80911             }
80912             switch (node.kind) {
80913                 case 126 /* AsyncKeyword */:
80914                     // ES2017 async modifier should be elided for targets < ES2017
80915                     return undefined;
80916                 case 206 /* AwaitExpression */:
80917                     return visitAwaitExpression(node);
80918                 case 161 /* MethodDeclaration */:
80919                     return doWithContext(1 /* NonTopLevel */ | 2 /* HasLexicalThis */, visitMethodDeclaration, node);
80920                 case 244 /* FunctionDeclaration */:
80921                     return doWithContext(1 /* NonTopLevel */ | 2 /* HasLexicalThis */, visitFunctionDeclaration, node);
80922                 case 201 /* FunctionExpression */:
80923                     return doWithContext(1 /* NonTopLevel */ | 2 /* HasLexicalThis */, visitFunctionExpression, node);
80924                 case 202 /* ArrowFunction */:
80925                     return doWithContext(1 /* NonTopLevel */, visitArrowFunction, node);
80926                 case 194 /* PropertyAccessExpression */:
80927                     if (capturedSuperProperties && ts.isPropertyAccessExpression(node) && node.expression.kind === 102 /* SuperKeyword */) {
80928                         capturedSuperProperties.set(node.name.escapedText, true);
80929                     }
80930                     return ts.visitEachChild(node, visitor, context);
80931                 case 195 /* ElementAccessExpression */:
80932                     if (capturedSuperProperties && node.expression.kind === 102 /* SuperKeyword */) {
80933                         hasSuperElementAccess = true;
80934                     }
80935                     return ts.visitEachChild(node, visitor, context);
80936                 case 163 /* GetAccessor */:
80937                 case 164 /* SetAccessor */:
80938                 case 162 /* Constructor */:
80939                 case 245 /* ClassDeclaration */:
80940                 case 214 /* ClassExpression */:
80941                     return doWithContext(1 /* NonTopLevel */ | 2 /* HasLexicalThis */, visitDefault, node);
80942                 default:
80943                     return ts.visitEachChild(node, visitor, context);
80944             }
80945         }
80946         function asyncBodyVisitor(node) {
80947             if (ts.isNodeWithPossibleHoistedDeclaration(node)) {
80948                 switch (node.kind) {
80949                     case 225 /* VariableStatement */:
80950                         return visitVariableStatementInAsyncBody(node);
80951                     case 230 /* ForStatement */:
80952                         return visitForStatementInAsyncBody(node);
80953                     case 231 /* ForInStatement */:
80954                         return visitForInStatementInAsyncBody(node);
80955                     case 232 /* ForOfStatement */:
80956                         return visitForOfStatementInAsyncBody(node);
80957                     case 280 /* CatchClause */:
80958                         return visitCatchClauseInAsyncBody(node);
80959                     case 223 /* Block */:
80960                     case 237 /* SwitchStatement */:
80961                     case 251 /* CaseBlock */:
80962                     case 277 /* CaseClause */:
80963                     case 278 /* DefaultClause */:
80964                     case 240 /* TryStatement */:
80965                     case 228 /* DoStatement */:
80966                     case 229 /* WhileStatement */:
80967                     case 227 /* IfStatement */:
80968                     case 236 /* WithStatement */:
80969                     case 238 /* LabeledStatement */:
80970                         return ts.visitEachChild(node, asyncBodyVisitor, context);
80971                     default:
80972                         return ts.Debug.assertNever(node, "Unhandled node.");
80973                 }
80974             }
80975             return visitor(node);
80976         }
80977         function visitCatchClauseInAsyncBody(node) {
80978             var catchClauseNames = ts.createUnderscoreEscapedMap();
80979             recordDeclarationName(node.variableDeclaration, catchClauseNames); // TODO: GH#18217
80980             // names declared in a catch variable are block scoped
80981             var catchClauseUnshadowedNames;
80982             catchClauseNames.forEach(function (_, escapedName) {
80983                 if (enclosingFunctionParameterNames.has(escapedName)) {
80984                     if (!catchClauseUnshadowedNames) {
80985                         catchClauseUnshadowedNames = ts.cloneMap(enclosingFunctionParameterNames);
80986                     }
80987                     catchClauseUnshadowedNames.delete(escapedName);
80988                 }
80989             });
80990             if (catchClauseUnshadowedNames) {
80991                 var savedEnclosingFunctionParameterNames = enclosingFunctionParameterNames;
80992                 enclosingFunctionParameterNames = catchClauseUnshadowedNames;
80993                 var result = ts.visitEachChild(node, asyncBodyVisitor, context);
80994                 enclosingFunctionParameterNames = savedEnclosingFunctionParameterNames;
80995                 return result;
80996             }
80997             else {
80998                 return ts.visitEachChild(node, asyncBodyVisitor, context);
80999             }
81000         }
81001         function visitVariableStatementInAsyncBody(node) {
81002             if (isVariableDeclarationListWithCollidingName(node.declarationList)) {
81003                 var expression = visitVariableDeclarationListWithCollidingNames(node.declarationList, /*hasReceiver*/ false);
81004                 return expression ? ts.createExpressionStatement(expression) : undefined;
81005             }
81006             return ts.visitEachChild(node, visitor, context);
81007         }
81008         function visitForInStatementInAsyncBody(node) {
81009             return ts.updateForIn(node, isVariableDeclarationListWithCollidingName(node.initializer)
81010                 ? visitVariableDeclarationListWithCollidingNames(node.initializer, /*hasReceiver*/ true)
81011                 : ts.visitNode(node.initializer, visitor, ts.isForInitializer), ts.visitNode(node.expression, visitor, ts.isExpression), ts.visitNode(node.statement, asyncBodyVisitor, ts.isStatement, ts.liftToBlock));
81012         }
81013         function visitForOfStatementInAsyncBody(node) {
81014             return ts.updateForOf(node, ts.visitNode(node.awaitModifier, visitor, ts.isToken), isVariableDeclarationListWithCollidingName(node.initializer)
81015                 ? visitVariableDeclarationListWithCollidingNames(node.initializer, /*hasReceiver*/ true)
81016                 : ts.visitNode(node.initializer, visitor, ts.isForInitializer), ts.visitNode(node.expression, visitor, ts.isExpression), ts.visitNode(node.statement, asyncBodyVisitor, ts.isStatement, ts.liftToBlock));
81017         }
81018         function visitForStatementInAsyncBody(node) {
81019             var initializer = node.initializer; // TODO: GH#18217
81020             return ts.updateFor(node, isVariableDeclarationListWithCollidingName(initializer)
81021                 ? visitVariableDeclarationListWithCollidingNames(initializer, /*hasReceiver*/ false)
81022                 : 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));
81023         }
81024         /**
81025          * Visits an AwaitExpression node.
81026          *
81027          * This function will be called any time a ES2017 await expression is encountered.
81028          *
81029          * @param node The node to visit.
81030          */
81031         function visitAwaitExpression(node) {
81032             // do not downlevel a top-level await as it is module syntax...
81033             if (inTopLevelContext()) {
81034                 return ts.visitEachChild(node, visitor, context);
81035             }
81036             return ts.setOriginalNode(ts.setTextRange(ts.createYield(
81037             /*asteriskToken*/ undefined, ts.visitNode(node.expression, visitor, ts.isExpression)), node), node);
81038         }
81039         /**
81040          * Visits a MethodDeclaration node.
81041          *
81042          * This function will be called when one of the following conditions are met:
81043          * - The node is marked as async
81044          *
81045          * @param node The node to visit.
81046          */
81047         function visitMethodDeclaration(node) {
81048             return ts.updateMethod(node, 
81049             /*decorators*/ undefined, ts.visitNodes(node.modifiers, visitor, ts.isModifier), node.asteriskToken, node.name, 
81050             /*questionToken*/ undefined, 
81051             /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), 
81052             /*type*/ undefined, ts.getFunctionFlags(node) & 2 /* Async */
81053                 ? transformAsyncFunctionBody(node)
81054                 : ts.visitFunctionBody(node.body, visitor, context));
81055         }
81056         /**
81057          * Visits a FunctionDeclaration node.
81058          *
81059          * This function will be called when one of the following conditions are met:
81060          * - The node is marked async
81061          *
81062          * @param node The node to visit.
81063          */
81064         function visitFunctionDeclaration(node) {
81065             return ts.updateFunctionDeclaration(node, 
81066             /*decorators*/ undefined, ts.visitNodes(node.modifiers, visitor, ts.isModifier), node.asteriskToken, node.name, 
81067             /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), 
81068             /*type*/ undefined, ts.getFunctionFlags(node) & 2 /* Async */
81069                 ? transformAsyncFunctionBody(node)
81070                 : ts.visitFunctionBody(node.body, visitor, context));
81071         }
81072         /**
81073          * Visits a FunctionExpression node.
81074          *
81075          * This function will be called when one of the following conditions are met:
81076          * - The node is marked async
81077          *
81078          * @param node The node to visit.
81079          */
81080         function visitFunctionExpression(node) {
81081             return ts.updateFunctionExpression(node, ts.visitNodes(node.modifiers, visitor, ts.isModifier), node.asteriskToken, node.name, 
81082             /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), 
81083             /*type*/ undefined, ts.getFunctionFlags(node) & 2 /* Async */
81084                 ? transformAsyncFunctionBody(node)
81085                 : ts.visitFunctionBody(node.body, visitor, context));
81086         }
81087         /**
81088          * Visits an ArrowFunction.
81089          *
81090          * This function will be called when one of the following conditions are met:
81091          * - The node is marked async
81092          *
81093          * @param node The node to visit.
81094          */
81095         function visitArrowFunction(node) {
81096             return ts.updateArrowFunction(node, ts.visitNodes(node.modifiers, visitor, ts.isModifier), 
81097             /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), 
81098             /*type*/ undefined, node.equalsGreaterThanToken, ts.getFunctionFlags(node) & 2 /* Async */
81099                 ? transformAsyncFunctionBody(node)
81100                 : ts.visitFunctionBody(node.body, visitor, context));
81101         }
81102         function recordDeclarationName(_a, names) {
81103             var name = _a.name;
81104             if (ts.isIdentifier(name)) {
81105                 names.set(name.escapedText, true);
81106             }
81107             else {
81108                 for (var _i = 0, _b = name.elements; _i < _b.length; _i++) {
81109                     var element = _b[_i];
81110                     if (!ts.isOmittedExpression(element)) {
81111                         recordDeclarationName(element, names);
81112                     }
81113                 }
81114             }
81115         }
81116         function isVariableDeclarationListWithCollidingName(node) {
81117             return !!node
81118                 && ts.isVariableDeclarationList(node)
81119                 && !(node.flags & 3 /* BlockScoped */)
81120                 && node.declarations.some(collidesWithParameterName);
81121         }
81122         function visitVariableDeclarationListWithCollidingNames(node, hasReceiver) {
81123             hoistVariableDeclarationList(node);
81124             var variables = ts.getInitializedVariables(node);
81125             if (variables.length === 0) {
81126                 if (hasReceiver) {
81127                     return ts.visitNode(ts.convertToAssignmentElementTarget(node.declarations[0].name), visitor, ts.isExpression);
81128                 }
81129                 return undefined;
81130             }
81131             return ts.inlineExpressions(ts.map(variables, transformInitializedVariable));
81132         }
81133         function hoistVariableDeclarationList(node) {
81134             ts.forEach(node.declarations, hoistVariable);
81135         }
81136         function hoistVariable(_a) {
81137             var name = _a.name;
81138             if (ts.isIdentifier(name)) {
81139                 hoistVariableDeclaration(name);
81140             }
81141             else {
81142                 for (var _i = 0, _b = name.elements; _i < _b.length; _i++) {
81143                     var element = _b[_i];
81144                     if (!ts.isOmittedExpression(element)) {
81145                         hoistVariable(element);
81146                     }
81147                 }
81148             }
81149         }
81150         function transformInitializedVariable(node) {
81151             var converted = ts.setSourceMapRange(ts.createAssignment(ts.convertToAssignmentElementTarget(node.name), node.initializer), node);
81152             return ts.visitNode(converted, visitor, ts.isExpression);
81153         }
81154         function collidesWithParameterName(_a) {
81155             var name = _a.name;
81156             if (ts.isIdentifier(name)) {
81157                 return enclosingFunctionParameterNames.has(name.escapedText);
81158             }
81159             else {
81160                 for (var _i = 0, _b = name.elements; _i < _b.length; _i++) {
81161                     var element = _b[_i];
81162                     if (!ts.isOmittedExpression(element) && collidesWithParameterName(element)) {
81163                         return true;
81164                     }
81165                 }
81166             }
81167             return false;
81168         }
81169         function transformAsyncFunctionBody(node) {
81170             resumeLexicalEnvironment();
81171             var original = ts.getOriginalNode(node, ts.isFunctionLike);
81172             var nodeType = original.type;
81173             var promiseConstructor = languageVersion < 2 /* ES2015 */ ? getPromiseConstructor(nodeType) : undefined;
81174             var isArrowFunction = node.kind === 202 /* ArrowFunction */;
81175             var hasLexicalArguments = (resolver.getNodeCheckFlags(node) & 8192 /* CaptureArguments */) !== 0;
81176             // An async function is emit as an outer function that calls an inner
81177             // generator function. To preserve lexical bindings, we pass the current
81178             // `this` and `arguments` objects to `__awaiter`. The generator function
81179             // passed to `__awaiter` is executed inside of the callback to the
81180             // promise constructor.
81181             var savedEnclosingFunctionParameterNames = enclosingFunctionParameterNames;
81182             enclosingFunctionParameterNames = ts.createUnderscoreEscapedMap();
81183             for (var _i = 0, _a = node.parameters; _i < _a.length; _i++) {
81184                 var parameter = _a[_i];
81185                 recordDeclarationName(parameter, enclosingFunctionParameterNames);
81186             }
81187             var savedCapturedSuperProperties = capturedSuperProperties;
81188             var savedHasSuperElementAccess = hasSuperElementAccess;
81189             if (!isArrowFunction) {
81190                 capturedSuperProperties = ts.createUnderscoreEscapedMap();
81191                 hasSuperElementAccess = false;
81192             }
81193             var result;
81194             if (!isArrowFunction) {
81195                 var statements = [];
81196                 var statementOffset = ts.addPrologue(statements, node.body.statements, /*ensureUseStrict*/ false, visitor);
81197                 statements.push(ts.createReturn(createAwaiterHelper(context, inHasLexicalThisContext(), hasLexicalArguments, promiseConstructor, transformAsyncFunctionBodyWorker(node.body, statementOffset))));
81198                 ts.insertStatementsAfterStandardPrologue(statements, endLexicalEnvironment());
81199                 // Minor optimization, emit `_super` helper to capture `super` access in an arrow.
81200                 // This step isn't needed if we eventually transform this to ES5.
81201                 var emitSuperHelpers = languageVersion >= 2 /* ES2015 */ && resolver.getNodeCheckFlags(node) & (4096 /* AsyncMethodWithSuperBinding */ | 2048 /* AsyncMethodWithSuper */);
81202                 if (emitSuperHelpers) {
81203                     enableSubstitutionForAsyncMethodsWithSuper();
81204                     if (ts.hasEntries(capturedSuperProperties)) {
81205                         var variableStatement = createSuperAccessVariableStatement(resolver, node, capturedSuperProperties);
81206                         substitutedSuperAccessors[ts.getNodeId(variableStatement)] = true;
81207                         ts.insertStatementsAfterStandardPrologue(statements, [variableStatement]);
81208                     }
81209                 }
81210                 var block = ts.createBlock(statements, /*multiLine*/ true);
81211                 ts.setTextRange(block, node.body);
81212                 if (emitSuperHelpers && hasSuperElementAccess) {
81213                     // Emit helpers for super element access expressions (`super[x]`).
81214                     if (resolver.getNodeCheckFlags(node) & 4096 /* AsyncMethodWithSuperBinding */) {
81215                         ts.addEmitHelper(block, ts.advancedAsyncSuperHelper);
81216                     }
81217                     else if (resolver.getNodeCheckFlags(node) & 2048 /* AsyncMethodWithSuper */) {
81218                         ts.addEmitHelper(block, ts.asyncSuperHelper);
81219                     }
81220                 }
81221                 result = block;
81222             }
81223             else {
81224                 var expression = createAwaiterHelper(context, inHasLexicalThisContext(), hasLexicalArguments, promiseConstructor, transformAsyncFunctionBodyWorker(node.body));
81225                 var declarations = endLexicalEnvironment();
81226                 if (ts.some(declarations)) {
81227                     var block = ts.convertToFunctionBody(expression);
81228                     result = ts.updateBlock(block, ts.setTextRange(ts.createNodeArray(ts.concatenate(declarations, block.statements)), block.statements));
81229                 }
81230                 else {
81231                     result = expression;
81232                 }
81233             }
81234             enclosingFunctionParameterNames = savedEnclosingFunctionParameterNames;
81235             if (!isArrowFunction) {
81236                 capturedSuperProperties = savedCapturedSuperProperties;
81237                 hasSuperElementAccess = savedHasSuperElementAccess;
81238             }
81239             return result;
81240         }
81241         function transformAsyncFunctionBodyWorker(body, start) {
81242             if (ts.isBlock(body)) {
81243                 return ts.updateBlock(body, ts.visitNodes(body.statements, asyncBodyVisitor, ts.isStatement, start));
81244             }
81245             else {
81246                 return ts.convertToFunctionBody(ts.visitNode(body, asyncBodyVisitor, ts.isConciseBody));
81247             }
81248         }
81249         function getPromiseConstructor(type) {
81250             var typeName = type && ts.getEntityNameFromTypeNode(type);
81251             if (typeName && ts.isEntityName(typeName)) {
81252                 var serializationKind = resolver.getTypeReferenceSerializationKind(typeName);
81253                 if (serializationKind === ts.TypeReferenceSerializationKind.TypeWithConstructSignatureAndValue
81254                     || serializationKind === ts.TypeReferenceSerializationKind.Unknown) {
81255                     return typeName;
81256                 }
81257             }
81258             return undefined;
81259         }
81260         function enableSubstitutionForAsyncMethodsWithSuper() {
81261             if ((enabledSubstitutions & 1 /* AsyncMethodsWithSuper */) === 0) {
81262                 enabledSubstitutions |= 1 /* AsyncMethodsWithSuper */;
81263                 // We need to enable substitutions for call, property access, and element access
81264                 // if we need to rewrite super calls.
81265                 context.enableSubstitution(196 /* CallExpression */);
81266                 context.enableSubstitution(194 /* PropertyAccessExpression */);
81267                 context.enableSubstitution(195 /* ElementAccessExpression */);
81268                 // We need to be notified when entering and exiting declarations that bind super.
81269                 context.enableEmitNotification(245 /* ClassDeclaration */);
81270                 context.enableEmitNotification(161 /* MethodDeclaration */);
81271                 context.enableEmitNotification(163 /* GetAccessor */);
81272                 context.enableEmitNotification(164 /* SetAccessor */);
81273                 context.enableEmitNotification(162 /* Constructor */);
81274                 // We need to be notified when entering the generated accessor arrow functions.
81275                 context.enableEmitNotification(225 /* VariableStatement */);
81276             }
81277         }
81278         /**
81279          * Hook for node emit.
81280          *
81281          * @param hint A hint as to the intended usage of the node.
81282          * @param node The node to emit.
81283          * @param emit A callback used to emit the node in the printer.
81284          */
81285         function onEmitNode(hint, node, emitCallback) {
81286             // If we need to support substitutions for `super` in an async method,
81287             // we should track it here.
81288             if (enabledSubstitutions & 1 /* AsyncMethodsWithSuper */ && isSuperContainer(node)) {
81289                 var superContainerFlags = resolver.getNodeCheckFlags(node) & (2048 /* AsyncMethodWithSuper */ | 4096 /* AsyncMethodWithSuperBinding */);
81290                 if (superContainerFlags !== enclosingSuperContainerFlags) {
81291                     var savedEnclosingSuperContainerFlags = enclosingSuperContainerFlags;
81292                     enclosingSuperContainerFlags = superContainerFlags;
81293                     previousOnEmitNode(hint, node, emitCallback);
81294                     enclosingSuperContainerFlags = savedEnclosingSuperContainerFlags;
81295                     return;
81296                 }
81297             }
81298             // Disable substitution in the generated super accessor itself.
81299             else if (enabledSubstitutions && substitutedSuperAccessors[ts.getNodeId(node)]) {
81300                 var savedEnclosingSuperContainerFlags = enclosingSuperContainerFlags;
81301                 enclosingSuperContainerFlags = 0;
81302                 previousOnEmitNode(hint, node, emitCallback);
81303                 enclosingSuperContainerFlags = savedEnclosingSuperContainerFlags;
81304                 return;
81305             }
81306             previousOnEmitNode(hint, node, emitCallback);
81307         }
81308         /**
81309          * Hooks node substitutions.
81310          *
81311          * @param hint A hint as to the intended usage of the node.
81312          * @param node The node to substitute.
81313          */
81314         function onSubstituteNode(hint, node) {
81315             node = previousOnSubstituteNode(hint, node);
81316             if (hint === 1 /* Expression */ && enclosingSuperContainerFlags) {
81317                 return substituteExpression(node);
81318             }
81319             return node;
81320         }
81321         function substituteExpression(node) {
81322             switch (node.kind) {
81323                 case 194 /* PropertyAccessExpression */:
81324                     return substitutePropertyAccessExpression(node);
81325                 case 195 /* ElementAccessExpression */:
81326                     return substituteElementAccessExpression(node);
81327                 case 196 /* CallExpression */:
81328                     return substituteCallExpression(node);
81329             }
81330             return node;
81331         }
81332         function substitutePropertyAccessExpression(node) {
81333             if (node.expression.kind === 102 /* SuperKeyword */) {
81334                 return ts.setTextRange(ts.createPropertyAccess(ts.createFileLevelUniqueName("_super"), node.name), node);
81335             }
81336             return node;
81337         }
81338         function substituteElementAccessExpression(node) {
81339             if (node.expression.kind === 102 /* SuperKeyword */) {
81340                 return createSuperElementAccessInAsyncMethod(node.argumentExpression, node);
81341             }
81342             return node;
81343         }
81344         function substituteCallExpression(node) {
81345             var expression = node.expression;
81346             if (ts.isSuperProperty(expression)) {
81347                 var argumentExpression = ts.isPropertyAccessExpression(expression)
81348                     ? substitutePropertyAccessExpression(expression)
81349                     : substituteElementAccessExpression(expression);
81350                 return ts.createCall(ts.createPropertyAccess(argumentExpression, "call"), 
81351                 /*typeArguments*/ undefined, __spreadArrays([
81352                     ts.createThis()
81353                 ], node.arguments));
81354             }
81355             return node;
81356         }
81357         function isSuperContainer(node) {
81358             var kind = node.kind;
81359             return kind === 245 /* ClassDeclaration */
81360                 || kind === 162 /* Constructor */
81361                 || kind === 161 /* MethodDeclaration */
81362                 || kind === 163 /* GetAccessor */
81363                 || kind === 164 /* SetAccessor */;
81364         }
81365         function createSuperElementAccessInAsyncMethod(argumentExpression, location) {
81366             if (enclosingSuperContainerFlags & 4096 /* AsyncMethodWithSuperBinding */) {
81367                 return ts.setTextRange(ts.createPropertyAccess(ts.createCall(ts.createFileLevelUniqueName("_superIndex"), 
81368                 /*typeArguments*/ undefined, [argumentExpression]), "value"), location);
81369             }
81370             else {
81371                 return ts.setTextRange(ts.createCall(ts.createFileLevelUniqueName("_superIndex"), 
81372                 /*typeArguments*/ undefined, [argumentExpression]), location);
81373             }
81374         }
81375     }
81376     ts.transformES2017 = transformES2017;
81377     /** Creates a variable named `_super` with accessor properties for the given property names. */
81378     function createSuperAccessVariableStatement(resolver, node, names) {
81379         // Create a variable declaration with a getter/setter (if binding) definition for each name:
81380         //   const _super = Object.create(null, { x: { get: () => super.x, set: (v) => super.x = v }, ... });
81381         var hasBinding = (resolver.getNodeCheckFlags(node) & 4096 /* AsyncMethodWithSuperBinding */) !== 0;
81382         var accessors = [];
81383         names.forEach(function (_, key) {
81384             var name = ts.unescapeLeadingUnderscores(key);
81385             var getterAndSetter = [];
81386             getterAndSetter.push(ts.createPropertyAssignment("get", ts.createArrowFunction(
81387             /* modifiers */ undefined, 
81388             /* typeParameters */ undefined, 
81389             /* parameters */ [], 
81390             /* type */ undefined, 
81391             /* equalsGreaterThanToken */ undefined, ts.setEmitFlags(ts.createPropertyAccess(ts.setEmitFlags(ts.createSuper(), 4 /* NoSubstitution */), name), 4 /* NoSubstitution */))));
81392             if (hasBinding) {
81393                 getterAndSetter.push(ts.createPropertyAssignment("set", ts.createArrowFunction(
81394                 /* modifiers */ undefined, 
81395                 /* typeParameters */ undefined, 
81396                 /* parameters */ [
81397                     ts.createParameter(
81398                     /* decorators */ undefined, 
81399                     /* modifiers */ undefined, 
81400                     /* dotDotDotToken */ undefined, "v", 
81401                     /* questionToken */ undefined, 
81402                     /* type */ undefined, 
81403                     /* initializer */ undefined)
81404                 ], 
81405                 /* type */ undefined, 
81406                 /* equalsGreaterThanToken */ undefined, ts.createAssignment(ts.setEmitFlags(ts.createPropertyAccess(ts.setEmitFlags(ts.createSuper(), 4 /* NoSubstitution */), name), 4 /* NoSubstitution */), ts.createIdentifier("v")))));
81407             }
81408             accessors.push(ts.createPropertyAssignment(name, ts.createObjectLiteral(getterAndSetter)));
81409         });
81410         return ts.createVariableStatement(
81411         /* modifiers */ undefined, ts.createVariableDeclarationList([
81412             ts.createVariableDeclaration(ts.createFileLevelUniqueName("_super"), 
81413             /* type */ undefined, ts.createCall(ts.createPropertyAccess(ts.createIdentifier("Object"), "create"), 
81414             /* typeArguments */ undefined, [
81415                 ts.createNull(),
81416                 ts.createObjectLiteral(accessors, /* multiline */ true)
81417             ]))
81418         ], 2 /* Const */));
81419     }
81420     ts.createSuperAccessVariableStatement = createSuperAccessVariableStatement;
81421     ts.awaiterHelper = {
81422         name: "typescript:awaiter",
81423         importName: "__awaiter",
81424         scoped: false,
81425         priority: 5,
81426         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            };"
81427     };
81428     function createAwaiterHelper(context, hasLexicalThis, hasLexicalArguments, promiseConstructor, body) {
81429         context.requestEmitHelper(ts.awaiterHelper);
81430         var generatorFunc = ts.createFunctionExpression(
81431         /*modifiers*/ undefined, ts.createToken(41 /* AsteriskToken */), 
81432         /*name*/ undefined, 
81433         /*typeParameters*/ undefined, 
81434         /*parameters*/ [], 
81435         /*type*/ undefined, body);
81436         // Mark this node as originally an async function
81437         (generatorFunc.emitNode || (generatorFunc.emitNode = {})).flags |= 262144 /* AsyncFunctionBody */ | 524288 /* ReuseTempVariableScope */;
81438         return ts.createCall(ts.getUnscopedHelperName("__awaiter"), 
81439         /*typeArguments*/ undefined, [
81440             hasLexicalThis ? ts.createThis() : ts.createVoidZero(),
81441             hasLexicalArguments ? ts.createIdentifier("arguments") : ts.createVoidZero(),
81442             promiseConstructor ? ts.createExpressionFromEntityName(promiseConstructor) : ts.createVoidZero(),
81443             generatorFunc
81444         ]);
81445     }
81446     ts.asyncSuperHelper = {
81447         name: "typescript:async-super",
81448         scoped: true,
81449         text: ts.helperString(__makeTemplateObject(["\n            const ", " = name => super[name];"], ["\n            const ", " = name => super[name];"]), "_superIndex")
81450     };
81451     ts.advancedAsyncSuperHelper = {
81452         name: "typescript:advanced-async-super",
81453         scoped: true,
81454         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")
81455     };
81456 })(ts || (ts = {}));
81457 /*@internal*/
81458 var ts;
81459 (function (ts) {
81460     var ESNextSubstitutionFlags;
81461     (function (ESNextSubstitutionFlags) {
81462         /** Enables substitutions for async methods with `super` calls. */
81463         ESNextSubstitutionFlags[ESNextSubstitutionFlags["AsyncMethodsWithSuper"] = 1] = "AsyncMethodsWithSuper";
81464     })(ESNextSubstitutionFlags || (ESNextSubstitutionFlags = {}));
81465     // Facts we track as we traverse the tree
81466     var HierarchyFacts;
81467     (function (HierarchyFacts) {
81468         HierarchyFacts[HierarchyFacts["None"] = 0] = "None";
81469         //
81470         // Ancestor facts
81471         //
81472         HierarchyFacts[HierarchyFacts["HasLexicalThis"] = 1] = "HasLexicalThis";
81473         HierarchyFacts[HierarchyFacts["IterationContainer"] = 2] = "IterationContainer";
81474         // NOTE: do not add more ancestor flags without also updating AncestorFactsMask below.
81475         //
81476         // Ancestor masks
81477         //
81478         HierarchyFacts[HierarchyFacts["AncestorFactsMask"] = 3] = "AncestorFactsMask";
81479         HierarchyFacts[HierarchyFacts["SourceFileIncludes"] = 1] = "SourceFileIncludes";
81480         HierarchyFacts[HierarchyFacts["SourceFileExcludes"] = 2] = "SourceFileExcludes";
81481         HierarchyFacts[HierarchyFacts["StrictModeSourceFileIncludes"] = 0] = "StrictModeSourceFileIncludes";
81482         HierarchyFacts[HierarchyFacts["ClassOrFunctionIncludes"] = 1] = "ClassOrFunctionIncludes";
81483         HierarchyFacts[HierarchyFacts["ClassOrFunctionExcludes"] = 2] = "ClassOrFunctionExcludes";
81484         HierarchyFacts[HierarchyFacts["ArrowFunctionIncludes"] = 0] = "ArrowFunctionIncludes";
81485         HierarchyFacts[HierarchyFacts["ArrowFunctionExcludes"] = 2] = "ArrowFunctionExcludes";
81486         HierarchyFacts[HierarchyFacts["IterationStatementIncludes"] = 2] = "IterationStatementIncludes";
81487         HierarchyFacts[HierarchyFacts["IterationStatementExcludes"] = 0] = "IterationStatementExcludes";
81488     })(HierarchyFacts || (HierarchyFacts = {}));
81489     function transformES2018(context) {
81490         var resumeLexicalEnvironment = context.resumeLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistVariableDeclaration = context.hoistVariableDeclaration;
81491         var resolver = context.getEmitResolver();
81492         var compilerOptions = context.getCompilerOptions();
81493         var languageVersion = ts.getEmitScriptTarget(compilerOptions);
81494         var previousOnEmitNode = context.onEmitNode;
81495         context.onEmitNode = onEmitNode;
81496         var previousOnSubstituteNode = context.onSubstituteNode;
81497         context.onSubstituteNode = onSubstituteNode;
81498         var exportedVariableStatement = false;
81499         var enabledSubstitutions;
81500         var enclosingFunctionFlags;
81501         var enclosingSuperContainerFlags = 0;
81502         var hierarchyFacts = 0;
81503         var currentSourceFile;
81504         var taggedTemplateStringDeclarations;
81505         /** Keeps track of property names accessed on super (`super.x`) within async functions. */
81506         var capturedSuperProperties;
81507         /** Whether the async function contains an element access on super (`super[x]`). */
81508         var hasSuperElementAccess;
81509         /** A set of node IDs for generated super accessors. */
81510         var substitutedSuperAccessors = [];
81511         return ts.chainBundle(transformSourceFile);
81512         function affectsSubtree(excludeFacts, includeFacts) {
81513             return hierarchyFacts !== (hierarchyFacts & ~excludeFacts | includeFacts);
81514         }
81515         /**
81516          * Sets the `HierarchyFacts` for this node prior to visiting this node's subtree, returning the facts set prior to modification.
81517          * @param excludeFacts The existing `HierarchyFacts` to reset before visiting the subtree.
81518          * @param includeFacts The new `HierarchyFacts` to set before visiting the subtree.
81519          */
81520         function enterSubtree(excludeFacts, includeFacts) {
81521             var ancestorFacts = hierarchyFacts;
81522             hierarchyFacts = (hierarchyFacts & ~excludeFacts | includeFacts) & 3 /* AncestorFactsMask */;
81523             return ancestorFacts;
81524         }
81525         /**
81526          * Restores the `HierarchyFacts` for this node's ancestor after visiting this node's
81527          * subtree.
81528          * @param ancestorFacts The `HierarchyFacts` of the ancestor to restore after visiting the subtree.
81529          */
81530         function exitSubtree(ancestorFacts) {
81531             hierarchyFacts = ancestorFacts;
81532         }
81533         function recordTaggedTemplateString(temp) {
81534             taggedTemplateStringDeclarations = ts.append(taggedTemplateStringDeclarations, ts.createVariableDeclaration(temp));
81535         }
81536         function transformSourceFile(node) {
81537             if (node.isDeclarationFile) {
81538                 return node;
81539             }
81540             currentSourceFile = node;
81541             var visited = visitSourceFile(node);
81542             ts.addEmitHelpers(visited, context.readEmitHelpers());
81543             currentSourceFile = undefined;
81544             taggedTemplateStringDeclarations = undefined;
81545             return visited;
81546         }
81547         function visitor(node) {
81548             return visitorWorker(node, /*noDestructuringValue*/ false);
81549         }
81550         function visitorNoDestructuringValue(node) {
81551             return visitorWorker(node, /*noDestructuringValue*/ true);
81552         }
81553         function visitorNoAsyncModifier(node) {
81554             if (node.kind === 126 /* AsyncKeyword */) {
81555                 return undefined;
81556             }
81557             return node;
81558         }
81559         function doWithHierarchyFacts(cb, value, excludeFacts, includeFacts) {
81560             if (affectsSubtree(excludeFacts, includeFacts)) {
81561                 var ancestorFacts = enterSubtree(excludeFacts, includeFacts);
81562                 var result = cb(value);
81563                 exitSubtree(ancestorFacts);
81564                 return result;
81565             }
81566             return cb(value);
81567         }
81568         function visitDefault(node) {
81569             return ts.visitEachChild(node, visitor, context);
81570         }
81571         function visitorWorker(node, noDestructuringValue) {
81572             if ((node.transformFlags & 32 /* ContainsES2018 */) === 0) {
81573                 return node;
81574             }
81575             switch (node.kind) {
81576                 case 206 /* AwaitExpression */:
81577                     return visitAwaitExpression(node);
81578                 case 212 /* YieldExpression */:
81579                     return visitYieldExpression(node);
81580                 case 235 /* ReturnStatement */:
81581                     return visitReturnStatement(node);
81582                 case 238 /* LabeledStatement */:
81583                     return visitLabeledStatement(node);
81584                 case 193 /* ObjectLiteralExpression */:
81585                     return visitObjectLiteralExpression(node);
81586                 case 209 /* BinaryExpression */:
81587                     return visitBinaryExpression(node, noDestructuringValue);
81588                 case 280 /* CatchClause */:
81589                     return visitCatchClause(node);
81590                 case 225 /* VariableStatement */:
81591                     return visitVariableStatement(node);
81592                 case 242 /* VariableDeclaration */:
81593                     return visitVariableDeclaration(node);
81594                 case 228 /* DoStatement */:
81595                 case 229 /* WhileStatement */:
81596                 case 231 /* ForInStatement */:
81597                     return doWithHierarchyFacts(visitDefault, node, 0 /* IterationStatementExcludes */, 2 /* IterationStatementIncludes */);
81598                 case 232 /* ForOfStatement */:
81599                     return visitForOfStatement(node, /*outermostLabeledStatement*/ undefined);
81600                 case 230 /* ForStatement */:
81601                     return doWithHierarchyFacts(visitForStatement, node, 0 /* IterationStatementExcludes */, 2 /* IterationStatementIncludes */);
81602                 case 205 /* VoidExpression */:
81603                     return visitVoidExpression(node);
81604                 case 162 /* Constructor */:
81605                     return doWithHierarchyFacts(visitConstructorDeclaration, node, 2 /* ClassOrFunctionExcludes */, 1 /* ClassOrFunctionIncludes */);
81606                 case 161 /* MethodDeclaration */:
81607                     return doWithHierarchyFacts(visitMethodDeclaration, node, 2 /* ClassOrFunctionExcludes */, 1 /* ClassOrFunctionIncludes */);
81608                 case 163 /* GetAccessor */:
81609                     return doWithHierarchyFacts(visitGetAccessorDeclaration, node, 2 /* ClassOrFunctionExcludes */, 1 /* ClassOrFunctionIncludes */);
81610                 case 164 /* SetAccessor */:
81611                     return doWithHierarchyFacts(visitSetAccessorDeclaration, node, 2 /* ClassOrFunctionExcludes */, 1 /* ClassOrFunctionIncludes */);
81612                 case 244 /* FunctionDeclaration */:
81613                     return doWithHierarchyFacts(visitFunctionDeclaration, node, 2 /* ClassOrFunctionExcludes */, 1 /* ClassOrFunctionIncludes */);
81614                 case 201 /* FunctionExpression */:
81615                     return doWithHierarchyFacts(visitFunctionExpression, node, 2 /* ClassOrFunctionExcludes */, 1 /* ClassOrFunctionIncludes */);
81616                 case 202 /* ArrowFunction */:
81617                     return doWithHierarchyFacts(visitArrowFunction, node, 2 /* ArrowFunctionExcludes */, 0 /* ArrowFunctionIncludes */);
81618                 case 156 /* Parameter */:
81619                     return visitParameter(node);
81620                 case 226 /* ExpressionStatement */:
81621                     return visitExpressionStatement(node);
81622                 case 200 /* ParenthesizedExpression */:
81623                     return visitParenthesizedExpression(node, noDestructuringValue);
81624                 case 198 /* TaggedTemplateExpression */:
81625                     return visitTaggedTemplateExpression(node);
81626                 case 194 /* PropertyAccessExpression */:
81627                     if (capturedSuperProperties && ts.isPropertyAccessExpression(node) && node.expression.kind === 102 /* SuperKeyword */) {
81628                         capturedSuperProperties.set(node.name.escapedText, true);
81629                     }
81630                     return ts.visitEachChild(node, visitor, context);
81631                 case 195 /* ElementAccessExpression */:
81632                     if (capturedSuperProperties && node.expression.kind === 102 /* SuperKeyword */) {
81633                         hasSuperElementAccess = true;
81634                     }
81635                     return ts.visitEachChild(node, visitor, context);
81636                 case 245 /* ClassDeclaration */:
81637                 case 214 /* ClassExpression */:
81638                     return doWithHierarchyFacts(visitDefault, node, 2 /* ClassOrFunctionExcludes */, 1 /* ClassOrFunctionIncludes */);
81639                 default:
81640                     return ts.visitEachChild(node, visitor, context);
81641             }
81642         }
81643         function visitAwaitExpression(node) {
81644             if (enclosingFunctionFlags & 2 /* Async */ && enclosingFunctionFlags & 1 /* Generator */) {
81645                 return ts.setOriginalNode(ts.setTextRange(ts.createYield(createAwaitHelper(context, ts.visitNode(node.expression, visitor, ts.isExpression))), 
81646                 /*location*/ node), node);
81647             }
81648             return ts.visitEachChild(node, visitor, context);
81649         }
81650         function visitYieldExpression(node) {
81651             if (enclosingFunctionFlags & 2 /* Async */ && enclosingFunctionFlags & 1 /* Generator */) {
81652                 if (node.asteriskToken) {
81653                     var expression = ts.visitNode(node.expression, visitor, ts.isExpression);
81654                     return ts.setOriginalNode(ts.setTextRange(ts.createYield(createAwaitHelper(context, ts.updateYield(node, node.asteriskToken, createAsyncDelegatorHelper(context, createAsyncValuesHelper(context, expression, expression), expression)))), node), node);
81655                 }
81656                 return ts.setOriginalNode(ts.setTextRange(ts.createYield(createDownlevelAwait(node.expression
81657                     ? ts.visitNode(node.expression, visitor, ts.isExpression)
81658                     : ts.createVoidZero())), node), node);
81659             }
81660             return ts.visitEachChild(node, visitor, context);
81661         }
81662         function visitReturnStatement(node) {
81663             if (enclosingFunctionFlags & 2 /* Async */ && enclosingFunctionFlags & 1 /* Generator */) {
81664                 return ts.updateReturn(node, createDownlevelAwait(node.expression ? ts.visitNode(node.expression, visitor, ts.isExpression) : ts.createVoidZero()));
81665             }
81666             return ts.visitEachChild(node, visitor, context);
81667         }
81668         function visitLabeledStatement(node) {
81669             if (enclosingFunctionFlags & 2 /* Async */) {
81670                 var statement = ts.unwrapInnermostStatementOfLabel(node);
81671                 if (statement.kind === 232 /* ForOfStatement */ && statement.awaitModifier) {
81672                     return visitForOfStatement(statement, node);
81673                 }
81674                 return ts.restoreEnclosingLabel(ts.visitNode(statement, visitor, ts.isStatement, ts.liftToBlock), node);
81675             }
81676             return ts.visitEachChild(node, visitor, context);
81677         }
81678         function chunkObjectLiteralElements(elements) {
81679             var chunkObject;
81680             var objects = [];
81681             for (var _i = 0, elements_4 = elements; _i < elements_4.length; _i++) {
81682                 var e = elements_4[_i];
81683                 if (e.kind === 283 /* SpreadAssignment */) {
81684                     if (chunkObject) {
81685                         objects.push(ts.createObjectLiteral(chunkObject));
81686                         chunkObject = undefined;
81687                     }
81688                     var target = e.expression;
81689                     objects.push(ts.visitNode(target, visitor, ts.isExpression));
81690                 }
81691                 else {
81692                     chunkObject = ts.append(chunkObject, e.kind === 281 /* PropertyAssignment */
81693                         ? ts.createPropertyAssignment(e.name, ts.visitNode(e.initializer, visitor, ts.isExpression))
81694                         : ts.visitNode(e, visitor, ts.isObjectLiteralElementLike));
81695                 }
81696             }
81697             if (chunkObject) {
81698                 objects.push(ts.createObjectLiteral(chunkObject));
81699             }
81700             return objects;
81701         }
81702         function visitObjectLiteralExpression(node) {
81703             if (node.transformFlags & 16384 /* ContainsObjectRestOrSpread */) {
81704                 // spread elements emit like so:
81705                 // non-spread elements are chunked together into object literals, and then all are passed to __assign:
81706                 //     { a, ...o, b } => __assign(__assign({a}, o), {b});
81707                 // If the first element is a spread element, then the first argument to __assign is {}:
81708                 //     { ...o, a, b, ...o2 } => __assign(__assign(__assign({}, o), {a, b}), o2)
81709                 //
81710                 // We cannot call __assign with more than two elements, since any element could cause side effects. For
81711                 // example:
81712                 //      var k = { a: 1, b: 2 };
81713                 //      var o = { a: 3, ...k, b: k.a++ };
81714                 //      // expected: { a: 1, b: 1 }
81715                 // If we translate the above to `__assign({ a: 3 }, k, { b: k.a++ })`, the `k.a++` will evaluate before
81716                 // `k` is spread and we end up with `{ a: 2, b: 1 }`.
81717                 //
81718                 // This also occurs for spread elements, not just property assignments:
81719                 //      var k = { a: 1, get b() { l = { z: 9 }; return 2; } };
81720                 //      var l = { c: 3 };
81721                 //      var o = { ...k, ...l };
81722                 //      // expected: { a: 1, b: 2, z: 9 }
81723                 // If we translate the above to `__assign({}, k, l)`, the `l` will evaluate before `k` is spread and we
81724                 // end up with `{ a: 1, b: 2, c: 3 }`
81725                 var objects = chunkObjectLiteralElements(node.properties);
81726                 if (objects.length && objects[0].kind !== 193 /* ObjectLiteralExpression */) {
81727                     objects.unshift(ts.createObjectLiteral());
81728                 }
81729                 var expression = objects[0];
81730                 if (objects.length > 1) {
81731                     for (var i = 1; i < objects.length; i++) {
81732                         expression = createAssignHelper(context, [expression, objects[i]]);
81733                     }
81734                     return expression;
81735                 }
81736                 else {
81737                     return createAssignHelper(context, objects);
81738                 }
81739             }
81740             return ts.visitEachChild(node, visitor, context);
81741         }
81742         function visitExpressionStatement(node) {
81743             return ts.visitEachChild(node, visitorNoDestructuringValue, context);
81744         }
81745         function visitParenthesizedExpression(node, noDestructuringValue) {
81746             return ts.visitEachChild(node, noDestructuringValue ? visitorNoDestructuringValue : visitor, context);
81747         }
81748         function visitSourceFile(node) {
81749             var ancestorFacts = enterSubtree(2 /* SourceFileExcludes */, ts.isEffectiveStrictModeSourceFile(node, compilerOptions) ?
81750                 0 /* StrictModeSourceFileIncludes */ :
81751                 1 /* SourceFileIncludes */);
81752             exportedVariableStatement = false;
81753             var visited = ts.visitEachChild(node, visitor, context);
81754             var statement = ts.concatenate(visited.statements, taggedTemplateStringDeclarations && [
81755                 ts.createVariableStatement(/*modifiers*/ undefined, ts.createVariableDeclarationList(taggedTemplateStringDeclarations))
81756             ]);
81757             var result = ts.updateSourceFileNode(visited, ts.setTextRange(ts.createNodeArray(statement), node.statements));
81758             exitSubtree(ancestorFacts);
81759             return result;
81760         }
81761         function visitTaggedTemplateExpression(node) {
81762             return ts.processTaggedTemplateExpression(context, node, visitor, currentSourceFile, recordTaggedTemplateString, ts.ProcessLevel.LiftRestriction);
81763         }
81764         /**
81765          * Visits a BinaryExpression that contains a destructuring assignment.
81766          *
81767          * @param node A BinaryExpression node.
81768          */
81769         function visitBinaryExpression(node, noDestructuringValue) {
81770             if (ts.isDestructuringAssignment(node) && node.left.transformFlags & 16384 /* ContainsObjectRestOrSpread */) {
81771                 return ts.flattenDestructuringAssignment(node, visitor, context, 1 /* ObjectRest */, !noDestructuringValue);
81772             }
81773             else if (node.operatorToken.kind === 27 /* CommaToken */) {
81774                 return ts.updateBinary(node, ts.visitNode(node.left, visitorNoDestructuringValue, ts.isExpression), ts.visitNode(node.right, noDestructuringValue ? visitorNoDestructuringValue : visitor, ts.isExpression));
81775             }
81776             return ts.visitEachChild(node, visitor, context);
81777         }
81778         function visitCatchClause(node) {
81779             if (node.variableDeclaration &&
81780                 ts.isBindingPattern(node.variableDeclaration.name) &&
81781                 node.variableDeclaration.name.transformFlags & 16384 /* ContainsObjectRestOrSpread */) {
81782                 var name = ts.getGeneratedNameForNode(node.variableDeclaration.name);
81783                 var updatedDecl = ts.updateVariableDeclaration(node.variableDeclaration, node.variableDeclaration.name, /*type*/ undefined, name);
81784                 var visitedBindings = ts.flattenDestructuringBinding(updatedDecl, visitor, context, 1 /* ObjectRest */);
81785                 var block = ts.visitNode(node.block, visitor, ts.isBlock);
81786                 if (ts.some(visitedBindings)) {
81787                     block = ts.updateBlock(block, __spreadArrays([
81788                         ts.createVariableStatement(/*modifiers*/ undefined, visitedBindings)
81789                     ], block.statements));
81790                 }
81791                 return ts.updateCatchClause(node, ts.updateVariableDeclaration(node.variableDeclaration, name, /*type*/ undefined, /*initializer*/ undefined), block);
81792             }
81793             return ts.visitEachChild(node, visitor, context);
81794         }
81795         function visitVariableStatement(node) {
81796             if (ts.hasModifier(node, 1 /* Export */)) {
81797                 var savedExportedVariableStatement = exportedVariableStatement;
81798                 exportedVariableStatement = true;
81799                 var visited = ts.visitEachChild(node, visitor, context);
81800                 exportedVariableStatement = savedExportedVariableStatement;
81801                 return visited;
81802             }
81803             return ts.visitEachChild(node, visitor, context);
81804         }
81805         /**
81806          * Visits a VariableDeclaration node with a binding pattern.
81807          *
81808          * @param node A VariableDeclaration node.
81809          */
81810         function visitVariableDeclaration(node) {
81811             if (exportedVariableStatement) {
81812                 var savedExportedVariableStatement = exportedVariableStatement;
81813                 exportedVariableStatement = false;
81814                 var visited = visitVariableDeclarationWorker(node, /*exportedVariableStatement*/ true);
81815                 exportedVariableStatement = savedExportedVariableStatement;
81816                 return visited;
81817             }
81818             return visitVariableDeclarationWorker(node, /*exportedVariableStatement*/ false);
81819         }
81820         function visitVariableDeclarationWorker(node, exportedVariableStatement) {
81821             // If we are here it is because the name contains a binding pattern with a rest somewhere in it.
81822             if (ts.isBindingPattern(node.name) && node.name.transformFlags & 16384 /* ContainsObjectRestOrSpread */) {
81823                 return ts.flattenDestructuringBinding(node, visitor, context, 1 /* ObjectRest */, 
81824                 /*rval*/ undefined, exportedVariableStatement);
81825             }
81826             return ts.visitEachChild(node, visitor, context);
81827         }
81828         function visitForStatement(node) {
81829             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));
81830         }
81831         function visitVoidExpression(node) {
81832             return ts.visitEachChild(node, visitorNoDestructuringValue, context);
81833         }
81834         /**
81835          * Visits a ForOfStatement and converts it into a ES2015-compatible ForOfStatement.
81836          *
81837          * @param node A ForOfStatement.
81838          */
81839         function visitForOfStatement(node, outermostLabeledStatement) {
81840             var ancestorFacts = enterSubtree(0 /* IterationStatementExcludes */, 2 /* IterationStatementIncludes */);
81841             if (node.initializer.transformFlags & 16384 /* ContainsObjectRestOrSpread */) {
81842                 node = transformForOfStatementWithObjectRest(node);
81843             }
81844             var result = node.awaitModifier ?
81845                 transformForAwaitOfStatement(node, outermostLabeledStatement, ancestorFacts) :
81846                 ts.restoreEnclosingLabel(ts.visitEachChild(node, visitor, context), outermostLabeledStatement);
81847             exitSubtree(ancestorFacts);
81848             return result;
81849         }
81850         function transformForOfStatementWithObjectRest(node) {
81851             var initializerWithoutParens = ts.skipParentheses(node.initializer);
81852             if (ts.isVariableDeclarationList(initializerWithoutParens) || ts.isAssignmentPattern(initializerWithoutParens)) {
81853                 var bodyLocation = void 0;
81854                 var statementsLocation = void 0;
81855                 var temp = ts.createTempVariable(/*recordTempVariable*/ undefined);
81856                 var statements = [ts.createForOfBindingStatement(initializerWithoutParens, temp)];
81857                 if (ts.isBlock(node.statement)) {
81858                     ts.addRange(statements, node.statement.statements);
81859                     bodyLocation = node.statement;
81860                     statementsLocation = node.statement.statements;
81861                 }
81862                 else if (node.statement) {
81863                     ts.append(statements, node.statement);
81864                     bodyLocation = node.statement;
81865                     statementsLocation = node.statement;
81866                 }
81867                 return ts.updateForOf(node, node.awaitModifier, ts.setTextRange(ts.createVariableDeclarationList([
81868                     ts.setTextRange(ts.createVariableDeclaration(temp), node.initializer)
81869                 ], 1 /* Let */), node.initializer), node.expression, ts.setTextRange(ts.createBlock(ts.setTextRange(ts.createNodeArray(statements), statementsLocation), 
81870                 /*multiLine*/ true), bodyLocation));
81871             }
81872             return node;
81873         }
81874         function convertForOfStatementHead(node, boundValue) {
81875             var binding = ts.createForOfBindingStatement(node.initializer, boundValue);
81876             var bodyLocation;
81877             var statementsLocation;
81878             var statements = [ts.visitNode(binding, visitor, ts.isStatement)];
81879             var statement = ts.visitNode(node.statement, visitor, ts.isStatement);
81880             if (ts.isBlock(statement)) {
81881                 ts.addRange(statements, statement.statements);
81882                 bodyLocation = statement;
81883                 statementsLocation = statement.statements;
81884             }
81885             else {
81886                 statements.push(statement);
81887             }
81888             return ts.setEmitFlags(ts.setTextRange(ts.createBlock(ts.setTextRange(ts.createNodeArray(statements), statementsLocation), 
81889             /*multiLine*/ true), bodyLocation), 48 /* NoSourceMap */ | 384 /* NoTokenSourceMaps */);
81890         }
81891         function createDownlevelAwait(expression) {
81892             return enclosingFunctionFlags & 1 /* Generator */
81893                 ? ts.createYield(/*asteriskToken*/ undefined, createAwaitHelper(context, expression))
81894                 : ts.createAwait(expression);
81895         }
81896         function transformForAwaitOfStatement(node, outermostLabeledStatement, ancestorFacts) {
81897             var expression = ts.visitNode(node.expression, visitor, ts.isExpression);
81898             var iterator = ts.isIdentifier(expression) ? ts.getGeneratedNameForNode(expression) : ts.createTempVariable(/*recordTempVariable*/ undefined);
81899             var result = ts.isIdentifier(expression) ? ts.getGeneratedNameForNode(iterator) : ts.createTempVariable(/*recordTempVariable*/ undefined);
81900             var errorRecord = ts.createUniqueName("e");
81901             var catchVariable = ts.getGeneratedNameForNode(errorRecord);
81902             var returnMethod = ts.createTempVariable(/*recordTempVariable*/ undefined);
81903             var callValues = createAsyncValuesHelper(context, expression, /*location*/ node.expression);
81904             var callNext = ts.createCall(ts.createPropertyAccess(iterator, "next"), /*typeArguments*/ undefined, []);
81905             var getDone = ts.createPropertyAccess(result, "done");
81906             var getValue = ts.createPropertyAccess(result, "value");
81907             var callReturn = ts.createFunctionCall(returnMethod, iterator, []);
81908             hoistVariableDeclaration(errorRecord);
81909             hoistVariableDeclaration(returnMethod);
81910             // if we are enclosed in an outer loop ensure we reset 'errorRecord' per each iteration
81911             var initializer = ancestorFacts & 2 /* IterationContainer */ ?
81912                 ts.inlineExpressions([ts.createAssignment(errorRecord, ts.createVoidZero()), callValues]) :
81913                 callValues;
81914             var forStatement = ts.setEmitFlags(ts.setTextRange(ts.createFor(
81915             /*initializer*/ ts.setEmitFlags(ts.setTextRange(ts.createVariableDeclarationList([
81916                 ts.setTextRange(ts.createVariableDeclaration(iterator, /*type*/ undefined, initializer), node.expression),
81917                 ts.createVariableDeclaration(result)
81918             ]), node.expression), 2097152 /* NoHoisting */), 
81919             /*condition*/ ts.createComma(ts.createAssignment(result, createDownlevelAwait(callNext)), ts.createLogicalNot(getDone)), 
81920             /*incrementor*/ undefined, 
81921             /*statement*/ convertForOfStatementHead(node, getValue)), 
81922             /*location*/ node), 256 /* NoTokenTrailingSourceMaps */);
81923             return ts.createTry(ts.createBlock([
81924                 ts.restoreEnclosingLabel(forStatement, outermostLabeledStatement)
81925             ]), ts.createCatchClause(ts.createVariableDeclaration(catchVariable), ts.setEmitFlags(ts.createBlock([
81926                 ts.createExpressionStatement(ts.createAssignment(errorRecord, ts.createObjectLiteral([
81927                     ts.createPropertyAssignment("error", catchVariable)
81928                 ])))
81929             ]), 1 /* SingleLine */)), ts.createBlock([
81930                 ts.createTry(
81931                 /*tryBlock*/ ts.createBlock([
81932                     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 */)
81933                 ]), 
81934                 /*catchClause*/ undefined, 
81935                 /*finallyBlock*/ ts.setEmitFlags(ts.createBlock([
81936                     ts.setEmitFlags(ts.createIf(errorRecord, ts.createThrow(ts.createPropertyAccess(errorRecord, "error"))), 1 /* SingleLine */)
81937                 ]), 1 /* SingleLine */))
81938             ]));
81939         }
81940         function visitParameter(node) {
81941             if (node.transformFlags & 16384 /* ContainsObjectRestOrSpread */) {
81942                 // Binding patterns are converted into a generated name and are
81943                 // evaluated inside the function body.
81944                 return ts.updateParameter(node, 
81945                 /*decorators*/ undefined, 
81946                 /*modifiers*/ undefined, node.dotDotDotToken, ts.getGeneratedNameForNode(node), 
81947                 /*questionToken*/ undefined, 
81948                 /*type*/ undefined, ts.visitNode(node.initializer, visitor, ts.isExpression));
81949             }
81950             return ts.visitEachChild(node, visitor, context);
81951         }
81952         function visitConstructorDeclaration(node) {
81953             var savedEnclosingFunctionFlags = enclosingFunctionFlags;
81954             enclosingFunctionFlags = 0 /* Normal */;
81955             var updated = ts.updateConstructor(node, 
81956             /*decorators*/ undefined, node.modifiers, ts.visitParameterList(node.parameters, visitor, context), transformFunctionBody(node));
81957             enclosingFunctionFlags = savedEnclosingFunctionFlags;
81958             return updated;
81959         }
81960         function visitGetAccessorDeclaration(node) {
81961             var savedEnclosingFunctionFlags = enclosingFunctionFlags;
81962             enclosingFunctionFlags = 0 /* Normal */;
81963             var updated = ts.updateGetAccessor(node, 
81964             /*decorators*/ undefined, node.modifiers, ts.visitNode(node.name, visitor, ts.isPropertyName), ts.visitParameterList(node.parameters, visitor, context), 
81965             /*type*/ undefined, transformFunctionBody(node));
81966             enclosingFunctionFlags = savedEnclosingFunctionFlags;
81967             return updated;
81968         }
81969         function visitSetAccessorDeclaration(node) {
81970             var savedEnclosingFunctionFlags = enclosingFunctionFlags;
81971             enclosingFunctionFlags = 0 /* Normal */;
81972             var updated = ts.updateSetAccessor(node, 
81973             /*decorators*/ undefined, node.modifiers, ts.visitNode(node.name, visitor, ts.isPropertyName), ts.visitParameterList(node.parameters, visitor, context), transformFunctionBody(node));
81974             enclosingFunctionFlags = savedEnclosingFunctionFlags;
81975             return updated;
81976         }
81977         function visitMethodDeclaration(node) {
81978             var savedEnclosingFunctionFlags = enclosingFunctionFlags;
81979             enclosingFunctionFlags = ts.getFunctionFlags(node);
81980             var updated = ts.updateMethod(node, 
81981             /*decorators*/ undefined, enclosingFunctionFlags & 1 /* Generator */
81982                 ? ts.visitNodes(node.modifiers, visitorNoAsyncModifier, ts.isModifier)
81983                 : node.modifiers, enclosingFunctionFlags & 2 /* Async */
81984                 ? undefined
81985                 : node.asteriskToken, ts.visitNode(node.name, visitor, ts.isPropertyName), ts.visitNode(/*questionToken*/ undefined, visitor, ts.isToken), 
81986             /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), 
81987             /*type*/ undefined, enclosingFunctionFlags & 2 /* Async */ && enclosingFunctionFlags & 1 /* Generator */
81988                 ? transformAsyncGeneratorFunctionBody(node)
81989                 : transformFunctionBody(node));
81990             enclosingFunctionFlags = savedEnclosingFunctionFlags;
81991             return updated;
81992         }
81993         function visitFunctionDeclaration(node) {
81994             var savedEnclosingFunctionFlags = enclosingFunctionFlags;
81995             enclosingFunctionFlags = ts.getFunctionFlags(node);
81996             var updated = ts.updateFunctionDeclaration(node, 
81997             /*decorators*/ undefined, enclosingFunctionFlags & 1 /* Generator */
81998                 ? ts.visitNodes(node.modifiers, visitorNoAsyncModifier, ts.isModifier)
81999                 : node.modifiers, enclosingFunctionFlags & 2 /* Async */
82000                 ? undefined
82001                 : node.asteriskToken, node.name, 
82002             /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), 
82003             /*type*/ undefined, enclosingFunctionFlags & 2 /* Async */ && enclosingFunctionFlags & 1 /* Generator */
82004                 ? transformAsyncGeneratorFunctionBody(node)
82005                 : transformFunctionBody(node));
82006             enclosingFunctionFlags = savedEnclosingFunctionFlags;
82007             return updated;
82008         }
82009         function visitArrowFunction(node) {
82010             var savedEnclosingFunctionFlags = enclosingFunctionFlags;
82011             enclosingFunctionFlags = ts.getFunctionFlags(node);
82012             var updated = ts.updateArrowFunction(node, node.modifiers, 
82013             /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), 
82014             /*type*/ undefined, node.equalsGreaterThanToken, transformFunctionBody(node));
82015             enclosingFunctionFlags = savedEnclosingFunctionFlags;
82016             return updated;
82017         }
82018         function visitFunctionExpression(node) {
82019             var savedEnclosingFunctionFlags = enclosingFunctionFlags;
82020             enclosingFunctionFlags = ts.getFunctionFlags(node);
82021             var updated = ts.updateFunctionExpression(node, enclosingFunctionFlags & 1 /* Generator */
82022                 ? ts.visitNodes(node.modifiers, visitorNoAsyncModifier, ts.isModifier)
82023                 : node.modifiers, enclosingFunctionFlags & 2 /* Async */
82024                 ? undefined
82025                 : node.asteriskToken, node.name, 
82026             /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), 
82027             /*type*/ undefined, enclosingFunctionFlags & 2 /* Async */ && enclosingFunctionFlags & 1 /* Generator */
82028                 ? transformAsyncGeneratorFunctionBody(node)
82029                 : transformFunctionBody(node));
82030             enclosingFunctionFlags = savedEnclosingFunctionFlags;
82031             return updated;
82032         }
82033         function transformAsyncGeneratorFunctionBody(node) {
82034             resumeLexicalEnvironment();
82035             var statements = [];
82036             var statementOffset = ts.addPrologue(statements, node.body.statements, /*ensureUseStrict*/ false, visitor);
82037             appendObjectRestAssignmentsIfNeeded(statements, node);
82038             var savedCapturedSuperProperties = capturedSuperProperties;
82039             var savedHasSuperElementAccess = hasSuperElementAccess;
82040             capturedSuperProperties = ts.createUnderscoreEscapedMap();
82041             hasSuperElementAccess = false;
82042             var returnStatement = ts.createReturn(createAsyncGeneratorHelper(context, ts.createFunctionExpression(
82043             /*modifiers*/ undefined, ts.createToken(41 /* AsteriskToken */), node.name && ts.getGeneratedNameForNode(node.name), 
82044             /*typeParameters*/ undefined, 
82045             /*parameters*/ [], 
82046             /*type*/ undefined, ts.updateBlock(node.body, ts.visitLexicalEnvironment(node.body.statements, visitor, context, statementOffset))), !!(hierarchyFacts & 1 /* HasLexicalThis */)));
82047             // Minor optimization, emit `_super` helper to capture `super` access in an arrow.
82048             // This step isn't needed if we eventually transform this to ES5.
82049             var emitSuperHelpers = languageVersion >= 2 /* ES2015 */ && resolver.getNodeCheckFlags(node) & (4096 /* AsyncMethodWithSuperBinding */ | 2048 /* AsyncMethodWithSuper */);
82050             if (emitSuperHelpers) {
82051                 enableSubstitutionForAsyncMethodsWithSuper();
82052                 var variableStatement = ts.createSuperAccessVariableStatement(resolver, node, capturedSuperProperties);
82053                 substitutedSuperAccessors[ts.getNodeId(variableStatement)] = true;
82054                 ts.insertStatementsAfterStandardPrologue(statements, [variableStatement]);
82055             }
82056             statements.push(returnStatement);
82057             ts.insertStatementsAfterStandardPrologue(statements, endLexicalEnvironment());
82058             var block = ts.updateBlock(node.body, statements);
82059             if (emitSuperHelpers && hasSuperElementAccess) {
82060                 if (resolver.getNodeCheckFlags(node) & 4096 /* AsyncMethodWithSuperBinding */) {
82061                     ts.addEmitHelper(block, ts.advancedAsyncSuperHelper);
82062                 }
82063                 else if (resolver.getNodeCheckFlags(node) & 2048 /* AsyncMethodWithSuper */) {
82064                     ts.addEmitHelper(block, ts.asyncSuperHelper);
82065                 }
82066             }
82067             capturedSuperProperties = savedCapturedSuperProperties;
82068             hasSuperElementAccess = savedHasSuperElementAccess;
82069             return block;
82070         }
82071         function transformFunctionBody(node) {
82072             resumeLexicalEnvironment();
82073             var statementOffset = 0;
82074             var statements = [];
82075             var body = ts.visitNode(node.body, visitor, ts.isConciseBody);
82076             if (ts.isBlock(body)) {
82077                 statementOffset = ts.addPrologue(statements, body.statements, /*ensureUseStrict*/ false, visitor);
82078             }
82079             ts.addRange(statements, appendObjectRestAssignmentsIfNeeded(/*statements*/ undefined, node));
82080             var leadingStatements = endLexicalEnvironment();
82081             if (statementOffset > 0 || ts.some(statements) || ts.some(leadingStatements)) {
82082                 var block = ts.convertToFunctionBody(body, /*multiLine*/ true);
82083                 ts.insertStatementsAfterStandardPrologue(statements, leadingStatements);
82084                 ts.addRange(statements, block.statements.slice(statementOffset));
82085                 return ts.updateBlock(block, ts.setTextRange(ts.createNodeArray(statements), block.statements));
82086             }
82087             return body;
82088         }
82089         function appendObjectRestAssignmentsIfNeeded(statements, node) {
82090             for (var _i = 0, _a = node.parameters; _i < _a.length; _i++) {
82091                 var parameter = _a[_i];
82092                 if (parameter.transformFlags & 16384 /* ContainsObjectRestOrSpread */) {
82093                     var temp = ts.getGeneratedNameForNode(parameter);
82094                     var declarations = ts.flattenDestructuringBinding(parameter, visitor, context, 1 /* ObjectRest */, temp, 
82095                     /*doNotRecordTempVariablesInLine*/ false, 
82096                     /*skipInitializer*/ true);
82097                     if (ts.some(declarations)) {
82098                         var statement = ts.createVariableStatement(
82099                         /*modifiers*/ undefined, ts.createVariableDeclarationList(declarations));
82100                         ts.setEmitFlags(statement, 1048576 /* CustomPrologue */);
82101                         statements = ts.append(statements, statement);
82102                     }
82103                 }
82104             }
82105             return statements;
82106         }
82107         function enableSubstitutionForAsyncMethodsWithSuper() {
82108             if ((enabledSubstitutions & 1 /* AsyncMethodsWithSuper */) === 0) {
82109                 enabledSubstitutions |= 1 /* AsyncMethodsWithSuper */;
82110                 // We need to enable substitutions for call, property access, and element access
82111                 // if we need to rewrite super calls.
82112                 context.enableSubstitution(196 /* CallExpression */);
82113                 context.enableSubstitution(194 /* PropertyAccessExpression */);
82114                 context.enableSubstitution(195 /* ElementAccessExpression */);
82115                 // We need to be notified when entering and exiting declarations that bind super.
82116                 context.enableEmitNotification(245 /* ClassDeclaration */);
82117                 context.enableEmitNotification(161 /* MethodDeclaration */);
82118                 context.enableEmitNotification(163 /* GetAccessor */);
82119                 context.enableEmitNotification(164 /* SetAccessor */);
82120                 context.enableEmitNotification(162 /* Constructor */);
82121                 // We need to be notified when entering the generated accessor arrow functions.
82122                 context.enableEmitNotification(225 /* VariableStatement */);
82123             }
82124         }
82125         /**
82126          * Called by the printer just before a node is printed.
82127          *
82128          * @param hint A hint as to the intended usage of the node.
82129          * @param node The node to be printed.
82130          * @param emitCallback The callback used to emit the node.
82131          */
82132         function onEmitNode(hint, node, emitCallback) {
82133             // If we need to support substitutions for `super` in an async method,
82134             // we should track it here.
82135             if (enabledSubstitutions & 1 /* AsyncMethodsWithSuper */ && isSuperContainer(node)) {
82136                 var superContainerFlags = resolver.getNodeCheckFlags(node) & (2048 /* AsyncMethodWithSuper */ | 4096 /* AsyncMethodWithSuperBinding */);
82137                 if (superContainerFlags !== enclosingSuperContainerFlags) {
82138                     var savedEnclosingSuperContainerFlags = enclosingSuperContainerFlags;
82139                     enclosingSuperContainerFlags = superContainerFlags;
82140                     previousOnEmitNode(hint, node, emitCallback);
82141                     enclosingSuperContainerFlags = savedEnclosingSuperContainerFlags;
82142                     return;
82143                 }
82144             }
82145             // Disable substitution in the generated super accessor itself.
82146             else if (enabledSubstitutions && substitutedSuperAccessors[ts.getNodeId(node)]) {
82147                 var savedEnclosingSuperContainerFlags = enclosingSuperContainerFlags;
82148                 enclosingSuperContainerFlags = 0;
82149                 previousOnEmitNode(hint, node, emitCallback);
82150                 enclosingSuperContainerFlags = savedEnclosingSuperContainerFlags;
82151                 return;
82152             }
82153             previousOnEmitNode(hint, node, emitCallback);
82154         }
82155         /**
82156          * Hooks node substitutions.
82157          *
82158          * @param hint The context for the emitter.
82159          * @param node The node to substitute.
82160          */
82161         function onSubstituteNode(hint, node) {
82162             node = previousOnSubstituteNode(hint, node);
82163             if (hint === 1 /* Expression */ && enclosingSuperContainerFlags) {
82164                 return substituteExpression(node);
82165             }
82166             return node;
82167         }
82168         function substituteExpression(node) {
82169             switch (node.kind) {
82170                 case 194 /* PropertyAccessExpression */:
82171                     return substitutePropertyAccessExpression(node);
82172                 case 195 /* ElementAccessExpression */:
82173                     return substituteElementAccessExpression(node);
82174                 case 196 /* CallExpression */:
82175                     return substituteCallExpression(node);
82176             }
82177             return node;
82178         }
82179         function substitutePropertyAccessExpression(node) {
82180             if (node.expression.kind === 102 /* SuperKeyword */) {
82181                 return ts.setTextRange(ts.createPropertyAccess(ts.createFileLevelUniqueName("_super"), node.name), node);
82182             }
82183             return node;
82184         }
82185         function substituteElementAccessExpression(node) {
82186             if (node.expression.kind === 102 /* SuperKeyword */) {
82187                 return createSuperElementAccessInAsyncMethod(node.argumentExpression, node);
82188             }
82189             return node;
82190         }
82191         function substituteCallExpression(node) {
82192             var expression = node.expression;
82193             if (ts.isSuperProperty(expression)) {
82194                 var argumentExpression = ts.isPropertyAccessExpression(expression)
82195                     ? substitutePropertyAccessExpression(expression)
82196                     : substituteElementAccessExpression(expression);
82197                 return ts.createCall(ts.createPropertyAccess(argumentExpression, "call"), 
82198                 /*typeArguments*/ undefined, __spreadArrays([
82199                     ts.createThis()
82200                 ], node.arguments));
82201             }
82202             return node;
82203         }
82204         function isSuperContainer(node) {
82205             var kind = node.kind;
82206             return kind === 245 /* ClassDeclaration */
82207                 || kind === 162 /* Constructor */
82208                 || kind === 161 /* MethodDeclaration */
82209                 || kind === 163 /* GetAccessor */
82210                 || kind === 164 /* SetAccessor */;
82211         }
82212         function createSuperElementAccessInAsyncMethod(argumentExpression, location) {
82213             if (enclosingSuperContainerFlags & 4096 /* AsyncMethodWithSuperBinding */) {
82214                 return ts.setTextRange(ts.createPropertyAccess(ts.createCall(ts.createIdentifier("_superIndex"), 
82215                 /*typeArguments*/ undefined, [argumentExpression]), "value"), location);
82216             }
82217             else {
82218                 return ts.setTextRange(ts.createCall(ts.createIdentifier("_superIndex"), 
82219                 /*typeArguments*/ undefined, [argumentExpression]), location);
82220             }
82221         }
82222     }
82223     ts.transformES2018 = transformES2018;
82224     ts.assignHelper = {
82225         name: "typescript:assign",
82226         importName: "__assign",
82227         scoped: false,
82228         priority: 1,
82229         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            };"
82230     };
82231     function createAssignHelper(context, attributesSegments) {
82232         if (context.getCompilerOptions().target >= 2 /* ES2015 */) {
82233             return ts.createCall(ts.createPropertyAccess(ts.createIdentifier("Object"), "assign"), /*typeArguments*/ undefined, attributesSegments);
82234         }
82235         context.requestEmitHelper(ts.assignHelper);
82236         return ts.createCall(ts.getUnscopedHelperName("__assign"), 
82237         /*typeArguments*/ undefined, attributesSegments);
82238     }
82239     ts.createAssignHelper = createAssignHelper;
82240     ts.awaitHelper = {
82241         name: "typescript:await",
82242         importName: "__await",
82243         scoped: false,
82244         text: "\n            var __await = (this && this.__await) || function (v) { return this instanceof __await ? (this.v = v, this) : new __await(v); }"
82245     };
82246     function createAwaitHelper(context, expression) {
82247         context.requestEmitHelper(ts.awaitHelper);
82248         return ts.createCall(ts.getUnscopedHelperName("__await"), /*typeArguments*/ undefined, [expression]);
82249     }
82250     ts.asyncGeneratorHelper = {
82251         name: "typescript:asyncGenerator",
82252         importName: "__asyncGenerator",
82253         scoped: false,
82254         dependencies: [ts.awaitHelper],
82255         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            };"
82256     };
82257     function createAsyncGeneratorHelper(context, generatorFunc, hasLexicalThis) {
82258         context.requestEmitHelper(ts.asyncGeneratorHelper);
82259         // Mark this node as originally an async function
82260         (generatorFunc.emitNode || (generatorFunc.emitNode = {})).flags |= 262144 /* AsyncFunctionBody */ | 524288 /* ReuseTempVariableScope */;
82261         return ts.createCall(ts.getUnscopedHelperName("__asyncGenerator"), 
82262         /*typeArguments*/ undefined, [
82263             hasLexicalThis ? ts.createThis() : ts.createVoidZero(),
82264             ts.createIdentifier("arguments"),
82265             generatorFunc
82266         ]);
82267     }
82268     ts.asyncDelegator = {
82269         name: "typescript:asyncDelegator",
82270         importName: "__asyncDelegator",
82271         scoped: false,
82272         dependencies: [ts.awaitHelper],
82273         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            };"
82274     };
82275     function createAsyncDelegatorHelper(context, expression, location) {
82276         context.requestEmitHelper(ts.asyncDelegator);
82277         return ts.setTextRange(ts.createCall(ts.getUnscopedHelperName("__asyncDelegator"), 
82278         /*typeArguments*/ undefined, [expression]), location);
82279     }
82280     ts.asyncValues = {
82281         name: "typescript:asyncValues",
82282         importName: "__asyncValues",
82283         scoped: false,
82284         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            };"
82285     };
82286     function createAsyncValuesHelper(context, expression, location) {
82287         context.requestEmitHelper(ts.asyncValues);
82288         return ts.setTextRange(ts.createCall(ts.getUnscopedHelperName("__asyncValues"), 
82289         /*typeArguments*/ undefined, [expression]), location);
82290     }
82291 })(ts || (ts = {}));
82292 /*@internal*/
82293 var ts;
82294 (function (ts) {
82295     function transformES2019(context) {
82296         return ts.chainBundle(transformSourceFile);
82297         function transformSourceFile(node) {
82298             if (node.isDeclarationFile) {
82299                 return node;
82300             }
82301             return ts.visitEachChild(node, visitor, context);
82302         }
82303         function visitor(node) {
82304             if ((node.transformFlags & 16 /* ContainsES2019 */) === 0) {
82305                 return node;
82306             }
82307             switch (node.kind) {
82308                 case 280 /* CatchClause */:
82309                     return visitCatchClause(node);
82310                 default:
82311                     return ts.visitEachChild(node, visitor, context);
82312             }
82313         }
82314         function visitCatchClause(node) {
82315             if (!node.variableDeclaration) {
82316                 return ts.updateCatchClause(node, ts.createVariableDeclaration(ts.createTempVariable(/*recordTempVariable*/ undefined)), ts.visitNode(node.block, visitor, ts.isBlock));
82317             }
82318             return ts.visitEachChild(node, visitor, context);
82319         }
82320     }
82321     ts.transformES2019 = transformES2019;
82322 })(ts || (ts = {}));
82323 /*@internal*/
82324 var ts;
82325 (function (ts) {
82326     function transformES2020(context) {
82327         var hoistVariableDeclaration = context.hoistVariableDeclaration;
82328         return ts.chainBundle(transformSourceFile);
82329         function transformSourceFile(node) {
82330             if (node.isDeclarationFile) {
82331                 return node;
82332             }
82333             return ts.visitEachChild(node, visitor, context);
82334         }
82335         function visitor(node) {
82336             if ((node.transformFlags & 8 /* ContainsES2020 */) === 0) {
82337                 return node;
82338             }
82339             switch (node.kind) {
82340                 case 194 /* PropertyAccessExpression */:
82341                 case 195 /* ElementAccessExpression */:
82342                 case 196 /* CallExpression */:
82343                     if (node.flags & 32 /* OptionalChain */) {
82344                         var updated = visitOptionalExpression(node, /*captureThisArg*/ false, /*isDelete*/ false);
82345                         ts.Debug.assertNotNode(updated, ts.isSyntheticReference);
82346                         return updated;
82347                     }
82348                     return ts.visitEachChild(node, visitor, context);
82349                 case 209 /* BinaryExpression */:
82350                     if (node.operatorToken.kind === 60 /* QuestionQuestionToken */) {
82351                         return transformNullishCoalescingExpression(node);
82352                     }
82353                     return ts.visitEachChild(node, visitor, context);
82354                 case 203 /* DeleteExpression */:
82355                     return visitDeleteExpression(node);
82356                 default:
82357                     return ts.visitEachChild(node, visitor, context);
82358             }
82359         }
82360         function flattenChain(chain) {
82361             ts.Debug.assertNotNode(chain, ts.isNonNullChain);
82362             var links = [chain];
82363             while (!chain.questionDotToken && !ts.isTaggedTemplateExpression(chain)) {
82364                 chain = ts.cast(ts.skipPartiallyEmittedExpressions(chain.expression), ts.isOptionalChain);
82365                 ts.Debug.assertNotNode(chain, ts.isNonNullChain);
82366                 links.unshift(chain);
82367             }
82368             return { expression: chain.expression, chain: links };
82369         }
82370         function visitNonOptionalParenthesizedExpression(node, captureThisArg, isDelete) {
82371             var expression = visitNonOptionalExpression(node.expression, captureThisArg, isDelete);
82372             if (ts.isSyntheticReference(expression)) {
82373                 // `(a.b)` -> { expression `((_a = a).b)`, thisArg: `_a` }
82374                 // `(a[b])` -> { expression `((_a = a)[b])`, thisArg: `_a` }
82375                 return ts.createSyntheticReferenceExpression(ts.updateParen(node, expression.expression), expression.thisArg);
82376             }
82377             return ts.updateParen(node, expression);
82378         }
82379         function visitNonOptionalPropertyOrElementAccessExpression(node, captureThisArg, isDelete) {
82380             if (ts.isOptionalChain(node)) {
82381                 // If `node` is an optional chain, then it is the outermost chain of an optional expression.
82382                 return visitOptionalExpression(node, captureThisArg, isDelete);
82383             }
82384             var expression = ts.visitNode(node.expression, visitor, ts.isExpression);
82385             ts.Debug.assertNotNode(expression, ts.isSyntheticReference);
82386             var thisArg;
82387             if (captureThisArg) {
82388                 if (shouldCaptureInTempVariable(expression)) {
82389                     thisArg = ts.createTempVariable(hoistVariableDeclaration);
82390                     expression = ts.createAssignment(thisArg, expression);
82391                     // if (inParameterInitializer) tempVariableInParameter = true;
82392                 }
82393                 else {
82394                     thisArg = expression;
82395                 }
82396             }
82397             expression = node.kind === 194 /* PropertyAccessExpression */
82398                 ? ts.updatePropertyAccess(node, expression, ts.visitNode(node.name, visitor, ts.isIdentifier))
82399                 : ts.updateElementAccess(node, expression, ts.visitNode(node.argumentExpression, visitor, ts.isExpression));
82400             return thisArg ? ts.createSyntheticReferenceExpression(expression, thisArg) : expression;
82401         }
82402         function visitNonOptionalCallExpression(node, captureThisArg) {
82403             if (ts.isOptionalChain(node)) {
82404                 // If `node` is an optional chain, then it is the outermost chain of an optional expression.
82405                 return visitOptionalExpression(node, captureThisArg, /*isDelete*/ false);
82406             }
82407             return ts.visitEachChild(node, visitor, context);
82408         }
82409         function visitNonOptionalExpression(node, captureThisArg, isDelete) {
82410             switch (node.kind) {
82411                 case 200 /* ParenthesizedExpression */: return visitNonOptionalParenthesizedExpression(node, captureThisArg, isDelete);
82412                 case 194 /* PropertyAccessExpression */:
82413                 case 195 /* ElementAccessExpression */: return visitNonOptionalPropertyOrElementAccessExpression(node, captureThisArg, isDelete);
82414                 case 196 /* CallExpression */: return visitNonOptionalCallExpression(node, captureThisArg);
82415                 default: return ts.visitNode(node, visitor, ts.isExpression);
82416             }
82417         }
82418         function visitOptionalExpression(node, captureThisArg, isDelete) {
82419             var _a = flattenChain(node), expression = _a.expression, chain = _a.chain;
82420             var left = visitNonOptionalExpression(expression, ts.isCallChain(chain[0]), /*isDelete*/ false);
82421             var leftThisArg = ts.isSyntheticReference(left) ? left.thisArg : undefined;
82422             var leftExpression = ts.isSyntheticReference(left) ? left.expression : left;
82423             var capturedLeft = leftExpression;
82424             if (shouldCaptureInTempVariable(leftExpression)) {
82425                 capturedLeft = ts.createTempVariable(hoistVariableDeclaration);
82426                 leftExpression = ts.createAssignment(capturedLeft, leftExpression);
82427                 // if (inParameterInitializer) tempVariableInParameter = true;
82428             }
82429             var rightExpression = capturedLeft;
82430             var thisArg;
82431             for (var i = 0; i < chain.length; i++) {
82432                 var segment = chain[i];
82433                 switch (segment.kind) {
82434                     case 194 /* PropertyAccessExpression */:
82435                     case 195 /* ElementAccessExpression */:
82436                         if (i === chain.length - 1 && captureThisArg) {
82437                             if (shouldCaptureInTempVariable(rightExpression)) {
82438                                 thisArg = ts.createTempVariable(hoistVariableDeclaration);
82439                                 rightExpression = ts.createAssignment(thisArg, rightExpression);
82440                                 // if (inParameterInitializer) tempVariableInParameter = true;
82441                             }
82442                             else {
82443                                 thisArg = rightExpression;
82444                             }
82445                         }
82446                         rightExpression = segment.kind === 194 /* PropertyAccessExpression */
82447                             ? ts.createPropertyAccess(rightExpression, ts.visitNode(segment.name, visitor, ts.isIdentifier))
82448                             : ts.createElementAccess(rightExpression, ts.visitNode(segment.argumentExpression, visitor, ts.isExpression));
82449                         break;
82450                     case 196 /* CallExpression */:
82451                         if (i === 0 && leftThisArg) {
82452                             rightExpression = ts.createFunctionCall(rightExpression, leftThisArg.kind === 102 /* SuperKeyword */ ? ts.createThis() : leftThisArg, ts.visitNodes(segment.arguments, visitor, ts.isExpression));
82453                         }
82454                         else {
82455                             rightExpression = ts.createCall(rightExpression, 
82456                             /*typeArguments*/ undefined, ts.visitNodes(segment.arguments, visitor, ts.isExpression));
82457                         }
82458                         break;
82459                 }
82460                 ts.setOriginalNode(rightExpression, segment);
82461             }
82462             var target = isDelete
82463                 ? ts.createConditional(createNotNullCondition(leftExpression, capturedLeft, /*invert*/ true), ts.createTrue(), ts.createDelete(rightExpression))
82464                 : ts.createConditional(createNotNullCondition(leftExpression, capturedLeft, /*invert*/ true), ts.createVoidZero(), rightExpression);
82465             return thisArg ? ts.createSyntheticReferenceExpression(target, thisArg) : target;
82466         }
82467         function createNotNullCondition(left, right, invert) {
82468             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()));
82469         }
82470         function transformNullishCoalescingExpression(node) {
82471             var left = ts.visitNode(node.left, visitor, ts.isExpression);
82472             var right = left;
82473             if (shouldCaptureInTempVariable(left)) {
82474                 right = ts.createTempVariable(hoistVariableDeclaration);
82475                 left = ts.createAssignment(right, left);
82476                 // if (inParameterInitializer) tempVariableInParameter = true;
82477             }
82478             return ts.createConditional(createNotNullCondition(left, right), right, ts.visitNode(node.right, visitor, ts.isExpression));
82479         }
82480         function shouldCaptureInTempVariable(expression) {
82481             // don't capture identifiers and `this` in a temporary variable
82482             // `super` cannot be captured as it's no real variable
82483             return !ts.isIdentifier(expression) &&
82484                 expression.kind !== 104 /* ThisKeyword */ &&
82485                 expression.kind !== 102 /* SuperKeyword */;
82486         }
82487         function visitDeleteExpression(node) {
82488             return ts.isOptionalChain(ts.skipParentheses(node.expression))
82489                 ? ts.setOriginalNode(visitNonOptionalExpression(node.expression, /*captureThisArg*/ false, /*isDelete*/ true), node)
82490                 : ts.updateDelete(node, ts.visitNode(node.expression, visitor, ts.isExpression));
82491         }
82492     }
82493     ts.transformES2020 = transformES2020;
82494 })(ts || (ts = {}));
82495 /*@internal*/
82496 var ts;
82497 (function (ts) {
82498     function transformESNext(context) {
82499         return ts.chainBundle(transformSourceFile);
82500         function transformSourceFile(node) {
82501             if (node.isDeclarationFile) {
82502                 return node;
82503             }
82504             return ts.visitEachChild(node, visitor, context);
82505         }
82506         function visitor(node) {
82507             if ((node.transformFlags & 4 /* ContainsESNext */) === 0) {
82508                 return node;
82509             }
82510             switch (node.kind) {
82511                 default:
82512                     return ts.visitEachChild(node, visitor, context);
82513             }
82514         }
82515     }
82516     ts.transformESNext = transformESNext;
82517 })(ts || (ts = {}));
82518 /*@internal*/
82519 var ts;
82520 (function (ts) {
82521     function transformJsx(context) {
82522         var compilerOptions = context.getCompilerOptions();
82523         var currentSourceFile;
82524         return ts.chainBundle(transformSourceFile);
82525         /**
82526          * Transform JSX-specific syntax in a SourceFile.
82527          *
82528          * @param node A SourceFile node.
82529          */
82530         function transformSourceFile(node) {
82531             if (node.isDeclarationFile) {
82532                 return node;
82533             }
82534             currentSourceFile = node;
82535             var visited = ts.visitEachChild(node, visitor, context);
82536             ts.addEmitHelpers(visited, context.readEmitHelpers());
82537             return visited;
82538         }
82539         function visitor(node) {
82540             if (node.transformFlags & 2 /* ContainsJsx */) {
82541                 return visitorWorker(node);
82542             }
82543             else {
82544                 return node;
82545             }
82546         }
82547         function visitorWorker(node) {
82548             switch (node.kind) {
82549                 case 266 /* JsxElement */:
82550                     return visitJsxElement(node, /*isChild*/ false);
82551                 case 267 /* JsxSelfClosingElement */:
82552                     return visitJsxSelfClosingElement(node, /*isChild*/ false);
82553                 case 270 /* JsxFragment */:
82554                     return visitJsxFragment(node, /*isChild*/ false);
82555                 case 276 /* JsxExpression */:
82556                     return visitJsxExpression(node);
82557                 default:
82558                     return ts.visitEachChild(node, visitor, context);
82559             }
82560         }
82561         function transformJsxChildToExpression(node) {
82562             switch (node.kind) {
82563                 case 11 /* JsxText */:
82564                     return visitJsxText(node);
82565                 case 276 /* JsxExpression */:
82566                     return visitJsxExpression(node);
82567                 case 266 /* JsxElement */:
82568                     return visitJsxElement(node, /*isChild*/ true);
82569                 case 267 /* JsxSelfClosingElement */:
82570                     return visitJsxSelfClosingElement(node, /*isChild*/ true);
82571                 case 270 /* JsxFragment */:
82572                     return visitJsxFragment(node, /*isChild*/ true);
82573                 default:
82574                     return ts.Debug.failBadSyntaxKind(node);
82575             }
82576         }
82577         function visitJsxElement(node, isChild) {
82578             return visitJsxOpeningLikeElement(node.openingElement, node.children, isChild, /*location*/ node);
82579         }
82580         function visitJsxSelfClosingElement(node, isChild) {
82581             return visitJsxOpeningLikeElement(node, /*children*/ undefined, isChild, /*location*/ node);
82582         }
82583         function visitJsxFragment(node, isChild) {
82584             return visitJsxOpeningFragment(node.openingFragment, node.children, isChild, /*location*/ node);
82585         }
82586         function visitJsxOpeningLikeElement(node, children, isChild, location) {
82587             var tagName = getTagName(node);
82588             var objectProperties;
82589             var attrs = node.attributes.properties;
82590             if (attrs.length === 0) {
82591                 // When there are no attributes, React wants "null"
82592                 objectProperties = ts.createNull();
82593             }
82594             else {
82595                 // Map spans of JsxAttribute nodes into object literals and spans
82596                 // of JsxSpreadAttribute nodes into expressions.
82597                 var segments = ts.flatten(ts.spanMap(attrs, ts.isJsxSpreadAttribute, function (attrs, isSpread) { return isSpread
82598                     ? ts.map(attrs, transformJsxSpreadAttributeToExpression)
82599                     : ts.createObjectLiteral(ts.map(attrs, transformJsxAttributeToObjectLiteralElement)); }));
82600                 if (ts.isJsxSpreadAttribute(attrs[0])) {
82601                     // We must always emit at least one object literal before a spread
82602                     // argument.
82603                     segments.unshift(ts.createObjectLiteral());
82604                 }
82605                 // Either emit one big object literal (no spread attribs), or
82606                 // a call to the __assign helper.
82607                 objectProperties = ts.singleOrUndefined(segments);
82608                 if (!objectProperties) {
82609                     objectProperties = ts.createAssignHelper(context, segments);
82610                 }
82611             }
82612             var element = ts.createExpressionForJsxElement(context.getEmitResolver().getJsxFactoryEntity(currentSourceFile), compilerOptions.reactNamespace, // TODO: GH#18217
82613             tagName, objectProperties, ts.mapDefined(children, transformJsxChildToExpression), node, location);
82614             if (isChild) {
82615                 ts.startOnNewLine(element);
82616             }
82617             return element;
82618         }
82619         function visitJsxOpeningFragment(node, children, isChild, location) {
82620             var element = ts.createExpressionForJsxFragment(context.getEmitResolver().getJsxFactoryEntity(currentSourceFile), compilerOptions.reactNamespace, // TODO: GH#18217
82621             ts.mapDefined(children, transformJsxChildToExpression), node, location);
82622             if (isChild) {
82623                 ts.startOnNewLine(element);
82624             }
82625             return element;
82626         }
82627         function transformJsxSpreadAttributeToExpression(node) {
82628             return ts.visitNode(node.expression, visitor, ts.isExpression);
82629         }
82630         function transformJsxAttributeToObjectLiteralElement(node) {
82631             var name = getAttributeName(node);
82632             var expression = transformJsxAttributeInitializer(node.initializer);
82633             return ts.createPropertyAssignment(name, expression);
82634         }
82635         function transformJsxAttributeInitializer(node) {
82636             if (node === undefined) {
82637                 return ts.createTrue();
82638             }
82639             else if (node.kind === 10 /* StringLiteral */) {
82640                 // Always recreate the literal to escape any escape sequences or newlines which may be in the original jsx string and which
82641                 // Need to be escaped to be handled correctly in a normal string
82642                 var literal = ts.createLiteral(tryDecodeEntities(node.text) || node.text);
82643                 literal.singleQuote = node.singleQuote !== undefined ? node.singleQuote : !ts.isStringDoubleQuoted(node, currentSourceFile);
82644                 return ts.setTextRange(literal, node);
82645             }
82646             else if (node.kind === 276 /* JsxExpression */) {
82647                 if (node.expression === undefined) {
82648                     return ts.createTrue();
82649                 }
82650                 return visitJsxExpression(node);
82651             }
82652             else {
82653                 return ts.Debug.failBadSyntaxKind(node);
82654             }
82655         }
82656         function visitJsxText(node) {
82657             var fixed = fixupWhitespaceAndDecodeEntities(node.text);
82658             return fixed === undefined ? undefined : ts.createLiteral(fixed);
82659         }
82660         /**
82661          * JSX trims whitespace at the end and beginning of lines, except that the
82662          * start/end of a tag is considered a start/end of a line only if that line is
82663          * on the same line as the closing tag. See examples in
82664          * tests/cases/conformance/jsx/tsxReactEmitWhitespace.tsx
82665          * 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
82666          *
82667          * An equivalent algorithm would be:
82668          * - If there is only one line, return it.
82669          * - If there is only whitespace (but multiple lines), return `undefined`.
82670          * - Split the text into lines.
82671          * - 'trimRight' the first line, 'trimLeft' the last line, 'trim' middle lines.
82672          * - Decode entities on each line (individually).
82673          * - Remove empty lines and join the rest with " ".
82674          */
82675         function fixupWhitespaceAndDecodeEntities(text) {
82676             var acc;
82677             // First non-whitespace character on this line.
82678             var firstNonWhitespace = 0;
82679             // Last non-whitespace character on this line.
82680             var lastNonWhitespace = -1;
82681             // These initial values are special because the first line is:
82682             // firstNonWhitespace = 0 to indicate that we want leading whitsepace,
82683             // but lastNonWhitespace = -1 as a special flag to indicate that we *don't* include the line if it's all whitespace.
82684             for (var i = 0; i < text.length; i++) {
82685                 var c = text.charCodeAt(i);
82686                 if (ts.isLineBreak(c)) {
82687                     // If we've seen any non-whitespace characters on this line, add the 'trim' of the line.
82688                     // (lastNonWhitespace === -1 is a special flag to detect whether the first line is all whitespace.)
82689                     if (firstNonWhitespace !== -1 && lastNonWhitespace !== -1) {
82690                         acc = addLineOfJsxText(acc, text.substr(firstNonWhitespace, lastNonWhitespace - firstNonWhitespace + 1));
82691                     }
82692                     // Reset firstNonWhitespace for the next line.
82693                     // Don't bother to reset lastNonWhitespace because we ignore it if firstNonWhitespace = -1.
82694                     firstNonWhitespace = -1;
82695                 }
82696                 else if (!ts.isWhiteSpaceSingleLine(c)) {
82697                     lastNonWhitespace = i;
82698                     if (firstNonWhitespace === -1) {
82699                         firstNonWhitespace = i;
82700                     }
82701                 }
82702             }
82703             return firstNonWhitespace !== -1
82704                 // Last line had a non-whitespace character. Emit the 'trimLeft', meaning keep trailing whitespace.
82705                 ? addLineOfJsxText(acc, text.substr(firstNonWhitespace))
82706                 // Last line was all whitespace, so ignore it
82707                 : acc;
82708         }
82709         function addLineOfJsxText(acc, trimmedLine) {
82710             // We do not escape the string here as that is handled by the printer
82711             // when it emits the literal. We do, however, need to decode JSX entities.
82712             var decoded = decodeEntities(trimmedLine);
82713             return acc === undefined ? decoded : acc + " " + decoded;
82714         }
82715         /**
82716          * Replace entities like "&nbsp;", "&#123;", and "&#xDEADBEEF;" with the characters they encode.
82717          * See https://en.wikipedia.org/wiki/List_of_XML_and_HTML_character_entity_references
82718          */
82719         function decodeEntities(text) {
82720             return text.replace(/&((#((\d+)|x([\da-fA-F]+)))|(\w+));/g, function (match, _all, _number, _digits, decimal, hex, word) {
82721                 if (decimal) {
82722                     return ts.utf16EncodeAsString(parseInt(decimal, 10));
82723                 }
82724                 else if (hex) {
82725                     return ts.utf16EncodeAsString(parseInt(hex, 16));
82726                 }
82727                 else {
82728                     var ch = entities.get(word);
82729                     // If this is not a valid entity, then just use `match` (replace it with itself, i.e. don't replace)
82730                     return ch ? ts.utf16EncodeAsString(ch) : match;
82731                 }
82732             });
82733         }
82734         /** Like `decodeEntities` but returns `undefined` if there were no entities to decode. */
82735         function tryDecodeEntities(text) {
82736             var decoded = decodeEntities(text);
82737             return decoded === text ? undefined : decoded;
82738         }
82739         function getTagName(node) {
82740             if (node.kind === 266 /* JsxElement */) {
82741                 return getTagName(node.openingElement);
82742             }
82743             else {
82744                 var name = node.tagName;
82745                 if (ts.isIdentifier(name) && ts.isIntrinsicJsxName(name.escapedText)) {
82746                     return ts.createLiteral(ts.idText(name));
82747                 }
82748                 else {
82749                     return ts.createExpressionFromEntityName(name);
82750                 }
82751             }
82752         }
82753         /**
82754          * Emit an attribute name, which is quoted if it needs to be quoted. Because
82755          * these emit into an object literal property name, we don't need to be worried
82756          * about keywords, just non-identifier characters
82757          */
82758         function getAttributeName(node) {
82759             var name = node.name;
82760             var text = ts.idText(name);
82761             if (/^[A-Za-z_]\w*$/.test(text)) {
82762                 return name;
82763             }
82764             else {
82765                 return ts.createLiteral(text);
82766             }
82767         }
82768         function visitJsxExpression(node) {
82769             return ts.visitNode(node.expression, visitor, ts.isExpression);
82770         }
82771     }
82772     ts.transformJsx = transformJsx;
82773     var entities = ts.createMapFromTemplate({
82774         quot: 0x0022,
82775         amp: 0x0026,
82776         apos: 0x0027,
82777         lt: 0x003C,
82778         gt: 0x003E,
82779         nbsp: 0x00A0,
82780         iexcl: 0x00A1,
82781         cent: 0x00A2,
82782         pound: 0x00A3,
82783         curren: 0x00A4,
82784         yen: 0x00A5,
82785         brvbar: 0x00A6,
82786         sect: 0x00A7,
82787         uml: 0x00A8,
82788         copy: 0x00A9,
82789         ordf: 0x00AA,
82790         laquo: 0x00AB,
82791         not: 0x00AC,
82792         shy: 0x00AD,
82793         reg: 0x00AE,
82794         macr: 0x00AF,
82795         deg: 0x00B0,
82796         plusmn: 0x00B1,
82797         sup2: 0x00B2,
82798         sup3: 0x00B3,
82799         acute: 0x00B4,
82800         micro: 0x00B5,
82801         para: 0x00B6,
82802         middot: 0x00B7,
82803         cedil: 0x00B8,
82804         sup1: 0x00B9,
82805         ordm: 0x00BA,
82806         raquo: 0x00BB,
82807         frac14: 0x00BC,
82808         frac12: 0x00BD,
82809         frac34: 0x00BE,
82810         iquest: 0x00BF,
82811         Agrave: 0x00C0,
82812         Aacute: 0x00C1,
82813         Acirc: 0x00C2,
82814         Atilde: 0x00C3,
82815         Auml: 0x00C4,
82816         Aring: 0x00C5,
82817         AElig: 0x00C6,
82818         Ccedil: 0x00C7,
82819         Egrave: 0x00C8,
82820         Eacute: 0x00C9,
82821         Ecirc: 0x00CA,
82822         Euml: 0x00CB,
82823         Igrave: 0x00CC,
82824         Iacute: 0x00CD,
82825         Icirc: 0x00CE,
82826         Iuml: 0x00CF,
82827         ETH: 0x00D0,
82828         Ntilde: 0x00D1,
82829         Ograve: 0x00D2,
82830         Oacute: 0x00D3,
82831         Ocirc: 0x00D4,
82832         Otilde: 0x00D5,
82833         Ouml: 0x00D6,
82834         times: 0x00D7,
82835         Oslash: 0x00D8,
82836         Ugrave: 0x00D9,
82837         Uacute: 0x00DA,
82838         Ucirc: 0x00DB,
82839         Uuml: 0x00DC,
82840         Yacute: 0x00DD,
82841         THORN: 0x00DE,
82842         szlig: 0x00DF,
82843         agrave: 0x00E0,
82844         aacute: 0x00E1,
82845         acirc: 0x00E2,
82846         atilde: 0x00E3,
82847         auml: 0x00E4,
82848         aring: 0x00E5,
82849         aelig: 0x00E6,
82850         ccedil: 0x00E7,
82851         egrave: 0x00E8,
82852         eacute: 0x00E9,
82853         ecirc: 0x00EA,
82854         euml: 0x00EB,
82855         igrave: 0x00EC,
82856         iacute: 0x00ED,
82857         icirc: 0x00EE,
82858         iuml: 0x00EF,
82859         eth: 0x00F0,
82860         ntilde: 0x00F1,
82861         ograve: 0x00F2,
82862         oacute: 0x00F3,
82863         ocirc: 0x00F4,
82864         otilde: 0x00F5,
82865         ouml: 0x00F6,
82866         divide: 0x00F7,
82867         oslash: 0x00F8,
82868         ugrave: 0x00F9,
82869         uacute: 0x00FA,
82870         ucirc: 0x00FB,
82871         uuml: 0x00FC,
82872         yacute: 0x00FD,
82873         thorn: 0x00FE,
82874         yuml: 0x00FF,
82875         OElig: 0x0152,
82876         oelig: 0x0153,
82877         Scaron: 0x0160,
82878         scaron: 0x0161,
82879         Yuml: 0x0178,
82880         fnof: 0x0192,
82881         circ: 0x02C6,
82882         tilde: 0x02DC,
82883         Alpha: 0x0391,
82884         Beta: 0x0392,
82885         Gamma: 0x0393,
82886         Delta: 0x0394,
82887         Epsilon: 0x0395,
82888         Zeta: 0x0396,
82889         Eta: 0x0397,
82890         Theta: 0x0398,
82891         Iota: 0x0399,
82892         Kappa: 0x039A,
82893         Lambda: 0x039B,
82894         Mu: 0x039C,
82895         Nu: 0x039D,
82896         Xi: 0x039E,
82897         Omicron: 0x039F,
82898         Pi: 0x03A0,
82899         Rho: 0x03A1,
82900         Sigma: 0x03A3,
82901         Tau: 0x03A4,
82902         Upsilon: 0x03A5,
82903         Phi: 0x03A6,
82904         Chi: 0x03A7,
82905         Psi: 0x03A8,
82906         Omega: 0x03A9,
82907         alpha: 0x03B1,
82908         beta: 0x03B2,
82909         gamma: 0x03B3,
82910         delta: 0x03B4,
82911         epsilon: 0x03B5,
82912         zeta: 0x03B6,
82913         eta: 0x03B7,
82914         theta: 0x03B8,
82915         iota: 0x03B9,
82916         kappa: 0x03BA,
82917         lambda: 0x03BB,
82918         mu: 0x03BC,
82919         nu: 0x03BD,
82920         xi: 0x03BE,
82921         omicron: 0x03BF,
82922         pi: 0x03C0,
82923         rho: 0x03C1,
82924         sigmaf: 0x03C2,
82925         sigma: 0x03C3,
82926         tau: 0x03C4,
82927         upsilon: 0x03C5,
82928         phi: 0x03C6,
82929         chi: 0x03C7,
82930         psi: 0x03C8,
82931         omega: 0x03C9,
82932         thetasym: 0x03D1,
82933         upsih: 0x03D2,
82934         piv: 0x03D6,
82935         ensp: 0x2002,
82936         emsp: 0x2003,
82937         thinsp: 0x2009,
82938         zwnj: 0x200C,
82939         zwj: 0x200D,
82940         lrm: 0x200E,
82941         rlm: 0x200F,
82942         ndash: 0x2013,
82943         mdash: 0x2014,
82944         lsquo: 0x2018,
82945         rsquo: 0x2019,
82946         sbquo: 0x201A,
82947         ldquo: 0x201C,
82948         rdquo: 0x201D,
82949         bdquo: 0x201E,
82950         dagger: 0x2020,
82951         Dagger: 0x2021,
82952         bull: 0x2022,
82953         hellip: 0x2026,
82954         permil: 0x2030,
82955         prime: 0x2032,
82956         Prime: 0x2033,
82957         lsaquo: 0x2039,
82958         rsaquo: 0x203A,
82959         oline: 0x203E,
82960         frasl: 0x2044,
82961         euro: 0x20AC,
82962         image: 0x2111,
82963         weierp: 0x2118,
82964         real: 0x211C,
82965         trade: 0x2122,
82966         alefsym: 0x2135,
82967         larr: 0x2190,
82968         uarr: 0x2191,
82969         rarr: 0x2192,
82970         darr: 0x2193,
82971         harr: 0x2194,
82972         crarr: 0x21B5,
82973         lArr: 0x21D0,
82974         uArr: 0x21D1,
82975         rArr: 0x21D2,
82976         dArr: 0x21D3,
82977         hArr: 0x21D4,
82978         forall: 0x2200,
82979         part: 0x2202,
82980         exist: 0x2203,
82981         empty: 0x2205,
82982         nabla: 0x2207,
82983         isin: 0x2208,
82984         notin: 0x2209,
82985         ni: 0x220B,
82986         prod: 0x220F,
82987         sum: 0x2211,
82988         minus: 0x2212,
82989         lowast: 0x2217,
82990         radic: 0x221A,
82991         prop: 0x221D,
82992         infin: 0x221E,
82993         ang: 0x2220,
82994         and: 0x2227,
82995         or: 0x2228,
82996         cap: 0x2229,
82997         cup: 0x222A,
82998         int: 0x222B,
82999         there4: 0x2234,
83000         sim: 0x223C,
83001         cong: 0x2245,
83002         asymp: 0x2248,
83003         ne: 0x2260,
83004         equiv: 0x2261,
83005         le: 0x2264,
83006         ge: 0x2265,
83007         sub: 0x2282,
83008         sup: 0x2283,
83009         nsub: 0x2284,
83010         sube: 0x2286,
83011         supe: 0x2287,
83012         oplus: 0x2295,
83013         otimes: 0x2297,
83014         perp: 0x22A5,
83015         sdot: 0x22C5,
83016         lceil: 0x2308,
83017         rceil: 0x2309,
83018         lfloor: 0x230A,
83019         rfloor: 0x230B,
83020         lang: 0x2329,
83021         rang: 0x232A,
83022         loz: 0x25CA,
83023         spades: 0x2660,
83024         clubs: 0x2663,
83025         hearts: 0x2665,
83026         diams: 0x2666
83027     });
83028 })(ts || (ts = {}));
83029 /*@internal*/
83030 var ts;
83031 (function (ts) {
83032     function transformES2016(context) {
83033         var hoistVariableDeclaration = context.hoistVariableDeclaration;
83034         return ts.chainBundle(transformSourceFile);
83035         function transformSourceFile(node) {
83036             if (node.isDeclarationFile) {
83037                 return node;
83038             }
83039             return ts.visitEachChild(node, visitor, context);
83040         }
83041         function visitor(node) {
83042             if ((node.transformFlags & 128 /* ContainsES2016 */) === 0) {
83043                 return node;
83044             }
83045             switch (node.kind) {
83046                 case 209 /* BinaryExpression */:
83047                     return visitBinaryExpression(node);
83048                 default:
83049                     return ts.visitEachChild(node, visitor, context);
83050             }
83051         }
83052         function visitBinaryExpression(node) {
83053             switch (node.operatorToken.kind) {
83054                 case 66 /* AsteriskAsteriskEqualsToken */:
83055                     return visitExponentiationAssignmentExpression(node);
83056                 case 42 /* AsteriskAsteriskToken */:
83057                     return visitExponentiationExpression(node);
83058                 default:
83059                     return ts.visitEachChild(node, visitor, context);
83060             }
83061         }
83062         function visitExponentiationAssignmentExpression(node) {
83063             var target;
83064             var value;
83065             var left = ts.visitNode(node.left, visitor, ts.isExpression);
83066             var right = ts.visitNode(node.right, visitor, ts.isExpression);
83067             if (ts.isElementAccessExpression(left)) {
83068                 // Transforms `a[x] **= b` into `(_a = a)[_x = x] = Math.pow(_a[_x], b)`
83069                 var expressionTemp = ts.createTempVariable(hoistVariableDeclaration);
83070                 var argumentExpressionTemp = ts.createTempVariable(hoistVariableDeclaration);
83071                 target = ts.setTextRange(ts.createElementAccess(ts.setTextRange(ts.createAssignment(expressionTemp, left.expression), left.expression), ts.setTextRange(ts.createAssignment(argumentExpressionTemp, left.argumentExpression), left.argumentExpression)), left);
83072                 value = ts.setTextRange(ts.createElementAccess(expressionTemp, argumentExpressionTemp), left);
83073             }
83074             else if (ts.isPropertyAccessExpression(left)) {
83075                 // Transforms `a.x **= b` into `(_a = a).x = Math.pow(_a.x, b)`
83076                 var expressionTemp = ts.createTempVariable(hoistVariableDeclaration);
83077                 target = ts.setTextRange(ts.createPropertyAccess(ts.setTextRange(ts.createAssignment(expressionTemp, left.expression), left.expression), left.name), left);
83078                 value = ts.setTextRange(ts.createPropertyAccess(expressionTemp, left.name), left);
83079             }
83080             else {
83081                 // Transforms `a **= b` into `a = Math.pow(a, b)`
83082                 target = left;
83083                 value = left;
83084             }
83085             return ts.setTextRange(ts.createAssignment(target, ts.createMathPow(value, right, /*location*/ node)), node);
83086         }
83087         function visitExponentiationExpression(node) {
83088             // Transforms `a ** b` into `Math.pow(a, b)`
83089             var left = ts.visitNode(node.left, visitor, ts.isExpression);
83090             var right = ts.visitNode(node.right, visitor, ts.isExpression);
83091             return ts.createMathPow(left, right, /*location*/ node);
83092         }
83093     }
83094     ts.transformES2016 = transformES2016;
83095 })(ts || (ts = {}));
83096 /*@internal*/
83097 var ts;
83098 (function (ts) {
83099     var ES2015SubstitutionFlags;
83100     (function (ES2015SubstitutionFlags) {
83101         /** Enables substitutions for captured `this` */
83102         ES2015SubstitutionFlags[ES2015SubstitutionFlags["CapturedThis"] = 1] = "CapturedThis";
83103         /** Enables substitutions for block-scoped bindings. */
83104         ES2015SubstitutionFlags[ES2015SubstitutionFlags["BlockScopedBindings"] = 2] = "BlockScopedBindings";
83105     })(ES2015SubstitutionFlags || (ES2015SubstitutionFlags = {}));
83106     var LoopOutParameterFlags;
83107     (function (LoopOutParameterFlags) {
83108         LoopOutParameterFlags[LoopOutParameterFlags["Body"] = 1] = "Body";
83109         LoopOutParameterFlags[LoopOutParameterFlags["Initializer"] = 2] = "Initializer";
83110     })(LoopOutParameterFlags || (LoopOutParameterFlags = {}));
83111     var CopyDirection;
83112     (function (CopyDirection) {
83113         CopyDirection[CopyDirection["ToOriginal"] = 0] = "ToOriginal";
83114         CopyDirection[CopyDirection["ToOutParameter"] = 1] = "ToOutParameter";
83115     })(CopyDirection || (CopyDirection = {}));
83116     var Jump;
83117     (function (Jump) {
83118         Jump[Jump["Break"] = 2] = "Break";
83119         Jump[Jump["Continue"] = 4] = "Continue";
83120         Jump[Jump["Return"] = 8] = "Return";
83121     })(Jump || (Jump = {}));
83122     // Facts we track as we traverse the tree
83123     var HierarchyFacts;
83124     (function (HierarchyFacts) {
83125         HierarchyFacts[HierarchyFacts["None"] = 0] = "None";
83126         //
83127         // Ancestor facts
83128         //
83129         HierarchyFacts[HierarchyFacts["Function"] = 1] = "Function";
83130         HierarchyFacts[HierarchyFacts["ArrowFunction"] = 2] = "ArrowFunction";
83131         HierarchyFacts[HierarchyFacts["AsyncFunctionBody"] = 4] = "AsyncFunctionBody";
83132         HierarchyFacts[HierarchyFacts["NonStaticClassElement"] = 8] = "NonStaticClassElement";
83133         HierarchyFacts[HierarchyFacts["CapturesThis"] = 16] = "CapturesThis";
83134         HierarchyFacts[HierarchyFacts["ExportedVariableStatement"] = 32] = "ExportedVariableStatement";
83135         HierarchyFacts[HierarchyFacts["TopLevel"] = 64] = "TopLevel";
83136         HierarchyFacts[HierarchyFacts["Block"] = 128] = "Block";
83137         HierarchyFacts[HierarchyFacts["IterationStatement"] = 256] = "IterationStatement";
83138         HierarchyFacts[HierarchyFacts["IterationStatementBlock"] = 512] = "IterationStatementBlock";
83139         HierarchyFacts[HierarchyFacts["IterationContainer"] = 1024] = "IterationContainer";
83140         HierarchyFacts[HierarchyFacts["ForStatement"] = 2048] = "ForStatement";
83141         HierarchyFacts[HierarchyFacts["ForInOrForOfStatement"] = 4096] = "ForInOrForOfStatement";
83142         HierarchyFacts[HierarchyFacts["ConstructorWithCapturedSuper"] = 8192] = "ConstructorWithCapturedSuper";
83143         // NOTE: do not add more ancestor flags without also updating AncestorFactsMask below.
83144         // NOTE: when adding a new ancestor flag, be sure to update the subtree flags below.
83145         //
83146         // Ancestor masks
83147         //
83148         HierarchyFacts[HierarchyFacts["AncestorFactsMask"] = 16383] = "AncestorFactsMask";
83149         // We are always in *some* kind of block scope, but only specific block-scope containers are
83150         // top-level or Blocks.
83151         HierarchyFacts[HierarchyFacts["BlockScopeIncludes"] = 0] = "BlockScopeIncludes";
83152         HierarchyFacts[HierarchyFacts["BlockScopeExcludes"] = 7104] = "BlockScopeExcludes";
83153         // A source file is a top-level block scope.
83154         HierarchyFacts[HierarchyFacts["SourceFileIncludes"] = 64] = "SourceFileIncludes";
83155         HierarchyFacts[HierarchyFacts["SourceFileExcludes"] = 8064] = "SourceFileExcludes";
83156         // Functions, methods, and accessors are both new lexical scopes and new block scopes.
83157         HierarchyFacts[HierarchyFacts["FunctionIncludes"] = 65] = "FunctionIncludes";
83158         HierarchyFacts[HierarchyFacts["FunctionExcludes"] = 16286] = "FunctionExcludes";
83159         HierarchyFacts[HierarchyFacts["AsyncFunctionBodyIncludes"] = 69] = "AsyncFunctionBodyIncludes";
83160         HierarchyFacts[HierarchyFacts["AsyncFunctionBodyExcludes"] = 16278] = "AsyncFunctionBodyExcludes";
83161         // Arrow functions are lexically scoped to their container, but are new block scopes.
83162         HierarchyFacts[HierarchyFacts["ArrowFunctionIncludes"] = 66] = "ArrowFunctionIncludes";
83163         HierarchyFacts[HierarchyFacts["ArrowFunctionExcludes"] = 15232] = "ArrowFunctionExcludes";
83164         // Constructors are both new lexical scopes and new block scopes. Constructors are also
83165         // always considered non-static members of a class.
83166         HierarchyFacts[HierarchyFacts["ConstructorIncludes"] = 73] = "ConstructorIncludes";
83167         HierarchyFacts[HierarchyFacts["ConstructorExcludes"] = 16278] = "ConstructorExcludes";
83168         // 'do' and 'while' statements are not block scopes. We track that the subtree is contained
83169         // within an IterationStatement to indicate whether the embedded statement is an
83170         // IterationStatementBlock.
83171         HierarchyFacts[HierarchyFacts["DoOrWhileStatementIncludes"] = 1280] = "DoOrWhileStatementIncludes";
83172         HierarchyFacts[HierarchyFacts["DoOrWhileStatementExcludes"] = 0] = "DoOrWhileStatementExcludes";
83173         // 'for' statements are new block scopes and have special handling for 'let' declarations.
83174         HierarchyFacts[HierarchyFacts["ForStatementIncludes"] = 3328] = "ForStatementIncludes";
83175         HierarchyFacts[HierarchyFacts["ForStatementExcludes"] = 5056] = "ForStatementExcludes";
83176         // 'for-in' and 'for-of' statements are new block scopes and have special handling for
83177         // 'let' declarations.
83178         HierarchyFacts[HierarchyFacts["ForInOrForOfStatementIncludes"] = 5376] = "ForInOrForOfStatementIncludes";
83179         HierarchyFacts[HierarchyFacts["ForInOrForOfStatementExcludes"] = 3008] = "ForInOrForOfStatementExcludes";
83180         // Blocks (other than function bodies) are new block scopes.
83181         HierarchyFacts[HierarchyFacts["BlockIncludes"] = 128] = "BlockIncludes";
83182         HierarchyFacts[HierarchyFacts["BlockExcludes"] = 6976] = "BlockExcludes";
83183         HierarchyFacts[HierarchyFacts["IterationStatementBlockIncludes"] = 512] = "IterationStatementBlockIncludes";
83184         HierarchyFacts[HierarchyFacts["IterationStatementBlockExcludes"] = 7104] = "IterationStatementBlockExcludes";
83185         //
83186         // Subtree facts
83187         //
83188         HierarchyFacts[HierarchyFacts["NewTarget"] = 16384] = "NewTarget";
83189         HierarchyFacts[HierarchyFacts["CapturedLexicalThis"] = 32768] = "CapturedLexicalThis";
83190         //
83191         // Subtree masks
83192         //
83193         HierarchyFacts[HierarchyFacts["SubtreeFactsMask"] = -16384] = "SubtreeFactsMask";
83194         HierarchyFacts[HierarchyFacts["ArrowFunctionSubtreeExcludes"] = 0] = "ArrowFunctionSubtreeExcludes";
83195         HierarchyFacts[HierarchyFacts["FunctionSubtreeExcludes"] = 49152] = "FunctionSubtreeExcludes";
83196     })(HierarchyFacts || (HierarchyFacts = {}));
83197     function transformES2015(context) {
83198         var startLexicalEnvironment = context.startLexicalEnvironment, resumeLexicalEnvironment = context.resumeLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistVariableDeclaration = context.hoistVariableDeclaration;
83199         var compilerOptions = context.getCompilerOptions();
83200         var resolver = context.getEmitResolver();
83201         var previousOnSubstituteNode = context.onSubstituteNode;
83202         var previousOnEmitNode = context.onEmitNode;
83203         context.onEmitNode = onEmitNode;
83204         context.onSubstituteNode = onSubstituteNode;
83205         var currentSourceFile;
83206         var currentText;
83207         var hierarchyFacts;
83208         var taggedTemplateStringDeclarations;
83209         function recordTaggedTemplateString(temp) {
83210             taggedTemplateStringDeclarations = ts.append(taggedTemplateStringDeclarations, ts.createVariableDeclaration(temp));
83211         }
83212         /**
83213          * Used to track if we are emitting body of the converted loop
83214          */
83215         var convertedLoopState;
83216         /**
83217          * Keeps track of whether substitutions have been enabled for specific cases.
83218          * They are persisted between each SourceFile transformation and should not
83219          * be reset.
83220          */
83221         var enabledSubstitutions;
83222         return ts.chainBundle(transformSourceFile);
83223         function transformSourceFile(node) {
83224             if (node.isDeclarationFile) {
83225                 return node;
83226             }
83227             currentSourceFile = node;
83228             currentText = node.text;
83229             var visited = visitSourceFile(node);
83230             ts.addEmitHelpers(visited, context.readEmitHelpers());
83231             currentSourceFile = undefined;
83232             currentText = undefined;
83233             taggedTemplateStringDeclarations = undefined;
83234             hierarchyFacts = 0 /* None */;
83235             return visited;
83236         }
83237         /**
83238          * Sets the `HierarchyFacts` for this node prior to visiting this node's subtree, returning the facts set prior to modification.
83239          * @param excludeFacts The existing `HierarchyFacts` to reset before visiting the subtree.
83240          * @param includeFacts The new `HierarchyFacts` to set before visiting the subtree.
83241          */
83242         function enterSubtree(excludeFacts, includeFacts) {
83243             var ancestorFacts = hierarchyFacts;
83244             hierarchyFacts = (hierarchyFacts & ~excludeFacts | includeFacts) & 16383 /* AncestorFactsMask */;
83245             return ancestorFacts;
83246         }
83247         /**
83248          * Restores the `HierarchyFacts` for this node's ancestor after visiting this node's
83249          * subtree, propagating specific facts from the subtree.
83250          * @param ancestorFacts The `HierarchyFacts` of the ancestor to restore after visiting the subtree.
83251          * @param excludeFacts The existing `HierarchyFacts` of the subtree that should not be propagated.
83252          * @param includeFacts The new `HierarchyFacts` of the subtree that should be propagated.
83253          */
83254         function exitSubtree(ancestorFacts, excludeFacts, includeFacts) {
83255             hierarchyFacts = (hierarchyFacts & ~excludeFacts | includeFacts) & -16384 /* SubtreeFactsMask */ | ancestorFacts;
83256         }
83257         function isReturnVoidStatementInConstructorWithCapturedSuper(node) {
83258             return (hierarchyFacts & 8192 /* ConstructorWithCapturedSuper */) !== 0
83259                 && node.kind === 235 /* ReturnStatement */
83260                 && !node.expression;
83261         }
83262         function shouldVisitNode(node) {
83263             return (node.transformFlags & 256 /* ContainsES2015 */) !== 0
83264                 || convertedLoopState !== undefined
83265                 || (hierarchyFacts & 8192 /* ConstructorWithCapturedSuper */ && (ts.isStatement(node) || (node.kind === 223 /* Block */)))
83266                 || (ts.isIterationStatement(node, /*lookInLabeledStatements*/ false) && shouldConvertIterationStatement(node))
83267                 || (ts.getEmitFlags(node) & 33554432 /* TypeScriptClassWrapper */) !== 0;
83268         }
83269         function visitor(node) {
83270             if (shouldVisitNode(node)) {
83271                 return visitJavaScript(node);
83272             }
83273             else {
83274                 return node;
83275             }
83276         }
83277         function callExpressionVisitor(node) {
83278             if (node.kind === 102 /* SuperKeyword */) {
83279                 return visitSuperKeyword(/*isExpressionOfCall*/ true);
83280             }
83281             return visitor(node);
83282         }
83283         function visitJavaScript(node) {
83284             switch (node.kind) {
83285                 case 120 /* StaticKeyword */:
83286                     return undefined; // elide static keyword
83287                 case 245 /* ClassDeclaration */:
83288                     return visitClassDeclaration(node);
83289                 case 214 /* ClassExpression */:
83290                     return visitClassExpression(node);
83291                 case 156 /* Parameter */:
83292                     return visitParameter(node);
83293                 case 244 /* FunctionDeclaration */:
83294                     return visitFunctionDeclaration(node);
83295                 case 202 /* ArrowFunction */:
83296                     return visitArrowFunction(node);
83297                 case 201 /* FunctionExpression */:
83298                     return visitFunctionExpression(node);
83299                 case 242 /* VariableDeclaration */:
83300                     return visitVariableDeclaration(node);
83301                 case 75 /* Identifier */:
83302                     return visitIdentifier(node);
83303                 case 243 /* VariableDeclarationList */:
83304                     return visitVariableDeclarationList(node);
83305                 case 237 /* SwitchStatement */:
83306                     return visitSwitchStatement(node);
83307                 case 251 /* CaseBlock */:
83308                     return visitCaseBlock(node);
83309                 case 223 /* Block */:
83310                     return visitBlock(node, /*isFunctionBody*/ false);
83311                 case 234 /* BreakStatement */:
83312                 case 233 /* ContinueStatement */:
83313                     return visitBreakOrContinueStatement(node);
83314                 case 238 /* LabeledStatement */:
83315                     return visitLabeledStatement(node);
83316                 case 228 /* DoStatement */:
83317                 case 229 /* WhileStatement */:
83318                     return visitDoOrWhileStatement(node, /*outermostLabeledStatement*/ undefined);
83319                 case 230 /* ForStatement */:
83320                     return visitForStatement(node, /*outermostLabeledStatement*/ undefined);
83321                 case 231 /* ForInStatement */:
83322                     return visitForInStatement(node, /*outermostLabeledStatement*/ undefined);
83323                 case 232 /* ForOfStatement */:
83324                     return visitForOfStatement(node, /*outermostLabeledStatement*/ undefined);
83325                 case 226 /* ExpressionStatement */:
83326                     return visitExpressionStatement(node);
83327                 case 193 /* ObjectLiteralExpression */:
83328                     return visitObjectLiteralExpression(node);
83329                 case 280 /* CatchClause */:
83330                     return visitCatchClause(node);
83331                 case 282 /* ShorthandPropertyAssignment */:
83332                     return visitShorthandPropertyAssignment(node);
83333                 case 154 /* ComputedPropertyName */:
83334                     return visitComputedPropertyName(node);
83335                 case 192 /* ArrayLiteralExpression */:
83336                     return visitArrayLiteralExpression(node);
83337                 case 196 /* CallExpression */:
83338                     return visitCallExpression(node);
83339                 case 197 /* NewExpression */:
83340                     return visitNewExpression(node);
83341                 case 200 /* ParenthesizedExpression */:
83342                     return visitParenthesizedExpression(node, /*needsDestructuringValue*/ true);
83343                 case 209 /* BinaryExpression */:
83344                     return visitBinaryExpression(node, /*needsDestructuringValue*/ true);
83345                 case 14 /* NoSubstitutionTemplateLiteral */:
83346                 case 15 /* TemplateHead */:
83347                 case 16 /* TemplateMiddle */:
83348                 case 17 /* TemplateTail */:
83349                     return visitTemplateLiteral(node);
83350                 case 10 /* StringLiteral */:
83351                     return visitStringLiteral(node);
83352                 case 8 /* NumericLiteral */:
83353                     return visitNumericLiteral(node);
83354                 case 198 /* TaggedTemplateExpression */:
83355                     return visitTaggedTemplateExpression(node);
83356                 case 211 /* TemplateExpression */:
83357                     return visitTemplateExpression(node);
83358                 case 212 /* YieldExpression */:
83359                     return visitYieldExpression(node);
83360                 case 213 /* SpreadElement */:
83361                     return visitSpreadElement(node);
83362                 case 102 /* SuperKeyword */:
83363                     return visitSuperKeyword(/*isExpressionOfCall*/ false);
83364                 case 104 /* ThisKeyword */:
83365                     return visitThisKeyword(node);
83366                 case 219 /* MetaProperty */:
83367                     return visitMetaProperty(node);
83368                 case 161 /* MethodDeclaration */:
83369                     return visitMethodDeclaration(node);
83370                 case 163 /* GetAccessor */:
83371                 case 164 /* SetAccessor */:
83372                     return visitAccessorDeclaration(node);
83373                 case 225 /* VariableStatement */:
83374                     return visitVariableStatement(node);
83375                 case 235 /* ReturnStatement */:
83376                     return visitReturnStatement(node);
83377                 default:
83378                     return ts.visitEachChild(node, visitor, context);
83379             }
83380         }
83381         function visitSourceFile(node) {
83382             var ancestorFacts = enterSubtree(8064 /* SourceFileExcludes */, 64 /* SourceFileIncludes */);
83383             var prologue = [];
83384             var statements = [];
83385             startLexicalEnvironment();
83386             var statementOffset = ts.addStandardPrologue(prologue, node.statements, /*ensureUseStrict*/ false);
83387             statementOffset = ts.addCustomPrologue(prologue, node.statements, statementOffset, visitor);
83388             ts.addRange(statements, ts.visitNodes(node.statements, visitor, ts.isStatement, statementOffset));
83389             if (taggedTemplateStringDeclarations) {
83390                 statements.push(ts.createVariableStatement(/*modifiers*/ undefined, ts.createVariableDeclarationList(taggedTemplateStringDeclarations)));
83391             }
83392             ts.mergeLexicalEnvironment(prologue, endLexicalEnvironment());
83393             insertCaptureThisForNodeIfNeeded(prologue, node);
83394             exitSubtree(ancestorFacts, 0 /* None */, 0 /* None */);
83395             return ts.updateSourceFileNode(node, ts.setTextRange(ts.createNodeArray(ts.concatenate(prologue, statements)), node.statements));
83396         }
83397         function visitSwitchStatement(node) {
83398             if (convertedLoopState !== undefined) {
83399                 var savedAllowedNonLabeledJumps = convertedLoopState.allowedNonLabeledJumps;
83400                 // for switch statement allow only non-labeled break
83401                 convertedLoopState.allowedNonLabeledJumps |= 2 /* Break */;
83402                 var result = ts.visitEachChild(node, visitor, context);
83403                 convertedLoopState.allowedNonLabeledJumps = savedAllowedNonLabeledJumps;
83404                 return result;
83405             }
83406             return ts.visitEachChild(node, visitor, context);
83407         }
83408         function visitCaseBlock(node) {
83409             var ancestorFacts = enterSubtree(7104 /* BlockScopeExcludes */, 0 /* BlockScopeIncludes */);
83410             var updated = ts.visitEachChild(node, visitor, context);
83411             exitSubtree(ancestorFacts, 0 /* None */, 0 /* None */);
83412             return updated;
83413         }
83414         function returnCapturedThis(node) {
83415             return ts.setOriginalNode(ts.createReturn(ts.createFileLevelUniqueName("_this")), node);
83416         }
83417         function visitReturnStatement(node) {
83418             if (convertedLoopState) {
83419                 convertedLoopState.nonLocalJumps |= 8 /* Return */;
83420                 if (isReturnVoidStatementInConstructorWithCapturedSuper(node)) {
83421                     node = returnCapturedThis(node);
83422                 }
83423                 return ts.createReturn(ts.createObjectLiteral([
83424                     ts.createPropertyAssignment(ts.createIdentifier("value"), node.expression
83425                         ? ts.visitNode(node.expression, visitor, ts.isExpression)
83426                         : ts.createVoidZero())
83427                 ]));
83428             }
83429             else if (isReturnVoidStatementInConstructorWithCapturedSuper(node)) {
83430                 return returnCapturedThis(node);
83431             }
83432             return ts.visitEachChild(node, visitor, context);
83433         }
83434         function visitThisKeyword(node) {
83435             if (hierarchyFacts & 2 /* ArrowFunction */) {
83436                 hierarchyFacts |= 32768 /* CapturedLexicalThis */;
83437             }
83438             if (convertedLoopState) {
83439                 if (hierarchyFacts & 2 /* ArrowFunction */) {
83440                     // if the enclosing function is an ArrowFunction then we use the captured 'this' keyword.
83441                     convertedLoopState.containsLexicalThis = true;
83442                     return node;
83443                 }
83444                 return convertedLoopState.thisName || (convertedLoopState.thisName = ts.createUniqueName("this"));
83445             }
83446             return node;
83447         }
83448         function visitIdentifier(node) {
83449             if (!convertedLoopState) {
83450                 return node;
83451             }
83452             if (ts.isGeneratedIdentifier(node)) {
83453                 return node;
83454             }
83455             if (node.escapedText !== "arguments" || !resolver.isArgumentsLocalBinding(node)) {
83456                 return node;
83457             }
83458             return convertedLoopState.argumentsName || (convertedLoopState.argumentsName = ts.createUniqueName("arguments"));
83459         }
83460         function visitBreakOrContinueStatement(node) {
83461             if (convertedLoopState) {
83462                 // check if we can emit break/continue as is
83463                 // it is possible if either
83464                 //   - break/continue is labeled and label is located inside the converted loop
83465                 //   - break/continue is non-labeled and located in non-converted loop/switch statement
83466                 var jump = node.kind === 234 /* BreakStatement */ ? 2 /* Break */ : 4 /* Continue */;
83467                 var canUseBreakOrContinue = (node.label && convertedLoopState.labels && convertedLoopState.labels.get(ts.idText(node.label))) ||
83468                     (!node.label && (convertedLoopState.allowedNonLabeledJumps & jump));
83469                 if (!canUseBreakOrContinue) {
83470                     var labelMarker = void 0;
83471                     var label = node.label;
83472                     if (!label) {
83473                         if (node.kind === 234 /* BreakStatement */) {
83474                             convertedLoopState.nonLocalJumps |= 2 /* Break */;
83475                             labelMarker = "break";
83476                         }
83477                         else {
83478                             convertedLoopState.nonLocalJumps |= 4 /* Continue */;
83479                             // note: return value is emitted only to simplify debugging, call to converted loop body does not do any dispatching on it.
83480                             labelMarker = "continue";
83481                         }
83482                     }
83483                     else {
83484                         if (node.kind === 234 /* BreakStatement */) {
83485                             labelMarker = "break-" + label.escapedText;
83486                             setLabeledJump(convertedLoopState, /*isBreak*/ true, ts.idText(label), labelMarker);
83487                         }
83488                         else {
83489                             labelMarker = "continue-" + label.escapedText;
83490                             setLabeledJump(convertedLoopState, /*isBreak*/ false, ts.idText(label), labelMarker);
83491                         }
83492                     }
83493                     var returnExpression = ts.createLiteral(labelMarker);
83494                     if (convertedLoopState.loopOutParameters.length) {
83495                         var outParams = convertedLoopState.loopOutParameters;
83496                         var expr = void 0;
83497                         for (var i = 0; i < outParams.length; i++) {
83498                             var copyExpr = copyOutParameter(outParams[i], 1 /* ToOutParameter */);
83499                             if (i === 0) {
83500                                 expr = copyExpr;
83501                             }
83502                             else {
83503                                 expr = ts.createBinary(expr, 27 /* CommaToken */, copyExpr);
83504                             }
83505                         }
83506                         returnExpression = ts.createBinary(expr, 27 /* CommaToken */, returnExpression);
83507                     }
83508                     return ts.createReturn(returnExpression);
83509                 }
83510             }
83511             return ts.visitEachChild(node, visitor, context);
83512         }
83513         /**
83514          * Visits a ClassDeclaration and transforms it into a variable statement.
83515          *
83516          * @param node A ClassDeclaration node.
83517          */
83518         function visitClassDeclaration(node) {
83519             // [source]
83520             //      class C { }
83521             //
83522             // [output]
83523             //      var C = (function () {
83524             //          function C() {
83525             //          }
83526             //          return C;
83527             //      }());
83528             var variable = ts.createVariableDeclaration(ts.getLocalName(node, /*allowComments*/ true), 
83529             /*type*/ undefined, transformClassLikeDeclarationToExpression(node));
83530             ts.setOriginalNode(variable, node);
83531             var statements = [];
83532             var statement = ts.createVariableStatement(/*modifiers*/ undefined, ts.createVariableDeclarationList([variable]));
83533             ts.setOriginalNode(statement, node);
83534             ts.setTextRange(statement, node);
83535             ts.startOnNewLine(statement);
83536             statements.push(statement);
83537             // Add an `export default` statement for default exports (for `--target es5 --module es6`)
83538             if (ts.hasModifier(node, 1 /* Export */)) {
83539                 var exportStatement = ts.hasModifier(node, 512 /* Default */)
83540                     ? ts.createExportDefault(ts.getLocalName(node))
83541                     : ts.createExternalModuleExport(ts.getLocalName(node));
83542                 ts.setOriginalNode(exportStatement, statement);
83543                 statements.push(exportStatement);
83544             }
83545             var emitFlags = ts.getEmitFlags(node);
83546             if ((emitFlags & 4194304 /* HasEndOfDeclarationMarker */) === 0) {
83547                 // Add a DeclarationMarker as a marker for the end of the declaration
83548                 statements.push(ts.createEndOfDeclarationMarker(node));
83549                 ts.setEmitFlags(statement, emitFlags | 4194304 /* HasEndOfDeclarationMarker */);
83550             }
83551             return ts.singleOrMany(statements);
83552         }
83553         /**
83554          * Visits a ClassExpression and transforms it into an expression.
83555          *
83556          * @param node A ClassExpression node.
83557          */
83558         function visitClassExpression(node) {
83559             // [source]
83560             //      C = class { }
83561             //
83562             // [output]
83563             //      C = (function () {
83564             //          function class_1() {
83565             //          }
83566             //          return class_1;
83567             //      }())
83568             return transformClassLikeDeclarationToExpression(node);
83569         }
83570         /**
83571          * Transforms a ClassExpression or ClassDeclaration into an expression.
83572          *
83573          * @param node A ClassExpression or ClassDeclaration node.
83574          */
83575         function transformClassLikeDeclarationToExpression(node) {
83576             // [source]
83577             //      class C extends D {
83578             //          constructor() {}
83579             //          method() {}
83580             //          get prop() {}
83581             //          set prop(v) {}
83582             //      }
83583             //
83584             // [output]
83585             //      (function (_super) {
83586             //          __extends(C, _super);
83587             //          function C() {
83588             //          }
83589             //          C.prototype.method = function () {}
83590             //          Object.defineProperty(C.prototype, "prop", {
83591             //              get: function() {},
83592             //              set: function() {},
83593             //              enumerable: true,
83594             //              configurable: true
83595             //          });
83596             //          return C;
83597             //      }(D))
83598             if (node.name) {
83599                 enableSubstitutionsForBlockScopedBindings();
83600             }
83601             var extendsClauseElement = ts.getClassExtendsHeritageElement(node);
83602             var classFunction = ts.createFunctionExpression(
83603             /*modifiers*/ undefined, 
83604             /*asteriskToken*/ undefined, 
83605             /*name*/ undefined, 
83606             /*typeParameters*/ undefined, extendsClauseElement ? [ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, ts.createFileLevelUniqueName("_super"))] : [], 
83607             /*type*/ undefined, transformClassBody(node, extendsClauseElement));
83608             // To preserve the behavior of the old emitter, we explicitly indent
83609             // the body of the function here if it was requested in an earlier
83610             // transformation.
83611             ts.setEmitFlags(classFunction, (ts.getEmitFlags(node) & 65536 /* Indented */) | 524288 /* ReuseTempVariableScope */);
83612             // "inner" and "outer" below are added purely to preserve source map locations from
83613             // the old emitter
83614             var inner = ts.createPartiallyEmittedExpression(classFunction);
83615             inner.end = node.end;
83616             ts.setEmitFlags(inner, 1536 /* NoComments */);
83617             var outer = ts.createPartiallyEmittedExpression(inner);
83618             outer.end = ts.skipTrivia(currentText, node.pos);
83619             ts.setEmitFlags(outer, 1536 /* NoComments */);
83620             var result = ts.createParen(ts.createCall(outer, 
83621             /*typeArguments*/ undefined, extendsClauseElement
83622                 ? [ts.visitNode(extendsClauseElement.expression, visitor, ts.isExpression)]
83623                 : []));
83624             ts.addSyntheticLeadingComment(result, 3 /* MultiLineCommentTrivia */, "* @class ");
83625             return result;
83626         }
83627         /**
83628          * Transforms a ClassExpression or ClassDeclaration into a function body.
83629          *
83630          * @param node A ClassExpression or ClassDeclaration node.
83631          * @param extendsClauseElement The expression for the class `extends` clause.
83632          */
83633         function transformClassBody(node, extendsClauseElement) {
83634             var statements = [];
83635             startLexicalEnvironment();
83636             addExtendsHelperIfNeeded(statements, node, extendsClauseElement);
83637             addConstructor(statements, node, extendsClauseElement);
83638             addClassMembers(statements, node);
83639             // Create a synthetic text range for the return statement.
83640             var closingBraceLocation = ts.createTokenRange(ts.skipTrivia(currentText, node.members.end), 19 /* CloseBraceToken */);
83641             var localName = ts.getInternalName(node);
83642             // The following partially-emitted expression exists purely to align our sourcemap
83643             // emit with the original emitter.
83644             var outer = ts.createPartiallyEmittedExpression(localName);
83645             outer.end = closingBraceLocation.end;
83646             ts.setEmitFlags(outer, 1536 /* NoComments */);
83647             var statement = ts.createReturn(outer);
83648             statement.pos = closingBraceLocation.pos;
83649             ts.setEmitFlags(statement, 1536 /* NoComments */ | 384 /* NoTokenSourceMaps */);
83650             statements.push(statement);
83651             ts.insertStatementsAfterStandardPrologue(statements, endLexicalEnvironment());
83652             var block = ts.createBlock(ts.setTextRange(ts.createNodeArray(statements), /*location*/ node.members), /*multiLine*/ true);
83653             ts.setEmitFlags(block, 1536 /* NoComments */);
83654             return block;
83655         }
83656         /**
83657          * Adds a call to the `__extends` helper if needed for a class.
83658          *
83659          * @param statements The statements of the class body function.
83660          * @param node The ClassExpression or ClassDeclaration node.
83661          * @param extendsClauseElement The expression for the class `extends` clause.
83662          */
83663         function addExtendsHelperIfNeeded(statements, node, extendsClauseElement) {
83664             if (extendsClauseElement) {
83665                 statements.push(ts.setTextRange(ts.createExpressionStatement(createExtendsHelper(context, ts.getInternalName(node))), 
83666                 /*location*/ extendsClauseElement));
83667             }
83668         }
83669         /**
83670          * Adds the constructor of the class to a class body function.
83671          *
83672          * @param statements The statements of the class body function.
83673          * @param node The ClassExpression or ClassDeclaration node.
83674          * @param extendsClauseElement The expression for the class `extends` clause.
83675          */
83676         function addConstructor(statements, node, extendsClauseElement) {
83677             var savedConvertedLoopState = convertedLoopState;
83678             convertedLoopState = undefined;
83679             var ancestorFacts = enterSubtree(16278 /* ConstructorExcludes */, 73 /* ConstructorIncludes */);
83680             var constructor = ts.getFirstConstructorWithBody(node);
83681             var hasSynthesizedSuper = hasSynthesizedDefaultSuperCall(constructor, extendsClauseElement !== undefined);
83682             var constructorFunction = ts.createFunctionDeclaration(
83683             /*decorators*/ undefined, 
83684             /*modifiers*/ undefined, 
83685             /*asteriskToken*/ undefined, ts.getInternalName(node), 
83686             /*typeParameters*/ undefined, transformConstructorParameters(constructor, hasSynthesizedSuper), 
83687             /*type*/ undefined, transformConstructorBody(constructor, node, extendsClauseElement, hasSynthesizedSuper));
83688             ts.setTextRange(constructorFunction, constructor || node);
83689             if (extendsClauseElement) {
83690                 ts.setEmitFlags(constructorFunction, 8 /* CapturesThis */);
83691             }
83692             statements.push(constructorFunction);
83693             exitSubtree(ancestorFacts, 49152 /* FunctionSubtreeExcludes */, 0 /* None */);
83694             convertedLoopState = savedConvertedLoopState;
83695         }
83696         /**
83697          * Transforms the parameters of the constructor declaration of a class.
83698          *
83699          * @param constructor The constructor for the class.
83700          * @param hasSynthesizedSuper A value indicating whether the constructor starts with a
83701          *                            synthesized `super` call.
83702          */
83703         function transformConstructorParameters(constructor, hasSynthesizedSuper) {
83704             // If the TypeScript transformer needed to synthesize a constructor for property
83705             // initializers, it would have also added a synthetic `...args` parameter and
83706             // `super` call.
83707             // If this is the case, we do not include the synthetic `...args` parameter and
83708             // will instead use the `arguments` object in ES5/3.
83709             return ts.visitParameterList(constructor && !hasSynthesizedSuper ? constructor.parameters : undefined, visitor, context)
83710                 || [];
83711         }
83712         function createDefaultConstructorBody(node, isDerivedClass) {
83713             // We must be here because the user didn't write a constructor
83714             // but we needed to call 'super(...args)' anyway as per 14.5.14 of the ES2016 spec.
83715             // If that's the case we can just immediately return the result of a 'super()' call.
83716             var statements = [];
83717             resumeLexicalEnvironment();
83718             ts.mergeLexicalEnvironment(statements, endLexicalEnvironment());
83719             if (isDerivedClass) {
83720                 // return _super !== null && _super.apply(this, arguments) || this;
83721                 statements.push(ts.createReturn(createDefaultSuperCallOrThis()));
83722             }
83723             var statementsArray = ts.createNodeArray(statements);
83724             ts.setTextRange(statementsArray, node.members);
83725             var block = ts.createBlock(statementsArray, /*multiLine*/ true);
83726             ts.setTextRange(block, node);
83727             ts.setEmitFlags(block, 1536 /* NoComments */);
83728             return block;
83729         }
83730         /**
83731          * Transforms the body of a constructor declaration of a class.
83732          *
83733          * @param constructor The constructor for the class.
83734          * @param node The node which contains the constructor.
83735          * @param extendsClauseElement The expression for the class `extends` clause.
83736          * @param hasSynthesizedSuper A value indicating whether the constructor starts with a
83737          *                            synthesized `super` call.
83738          */
83739         function transformConstructorBody(constructor, node, extendsClauseElement, hasSynthesizedSuper) {
83740             // determine whether the class is known syntactically to be a derived class (e.g. a
83741             // class that extends a value that is not syntactically known to be `null`).
83742             var isDerivedClass = !!extendsClauseElement && ts.skipOuterExpressions(extendsClauseElement.expression).kind !== 100 /* NullKeyword */;
83743             // When the subclass does not have a constructor, we synthesize a *default* constructor using the following
83744             // representation:
83745             //
83746             // ```
83747             // // es2015 (source)
83748             // class C extends Base { }
83749             //
83750             // // es5 (transformed)
83751             // var C = (function (_super) {
83752             //     function C() {
83753             //         return _super.apply(this, arguments) || this;
83754             //     }
83755             //     return C;
83756             // })(Base);
83757             // ```
83758             if (!constructor)
83759                 return createDefaultConstructorBody(node, isDerivedClass);
83760             // The prologue will contain all leading standard and custom prologue statements added by this transform
83761             var prologue = [];
83762             var statements = [];
83763             resumeLexicalEnvironment();
83764             // If a super call has already been synthesized,
83765             // we're going to assume that we should just transform everything after that.
83766             // The assumption is that no prior step in the pipeline has added any prologue directives.
83767             var statementOffset = 0;
83768             if (!hasSynthesizedSuper)
83769                 statementOffset = ts.addStandardPrologue(prologue, constructor.body.statements, /*ensureUseStrict*/ false);
83770             addDefaultValueAssignmentsIfNeeded(statements, constructor);
83771             addRestParameterIfNeeded(statements, constructor, hasSynthesizedSuper);
83772             if (!hasSynthesizedSuper)
83773                 statementOffset = ts.addCustomPrologue(statements, constructor.body.statements, statementOffset, visitor);
83774             // If the first statement is a call to `super()`, visit the statement directly
83775             var superCallExpression;
83776             if (hasSynthesizedSuper) {
83777                 superCallExpression = createDefaultSuperCallOrThis();
83778             }
83779             else if (isDerivedClass && statementOffset < constructor.body.statements.length) {
83780                 var firstStatement = constructor.body.statements[statementOffset];
83781                 if (ts.isExpressionStatement(firstStatement) && ts.isSuperCall(firstStatement.expression)) {
83782                     superCallExpression = visitImmediateSuperCallInBody(firstStatement.expression);
83783                 }
83784             }
83785             if (superCallExpression) {
83786                 hierarchyFacts |= 8192 /* ConstructorWithCapturedSuper */;
83787                 statementOffset++; // skip this statement, we will add it after visiting the rest of the body.
83788             }
83789             // visit the remaining statements
83790             ts.addRange(statements, ts.visitNodes(constructor.body.statements, visitor, ts.isStatement, /*start*/ statementOffset));
83791             ts.mergeLexicalEnvironment(prologue, endLexicalEnvironment());
83792             insertCaptureNewTargetIfNeeded(prologue, constructor, /*copyOnWrite*/ false);
83793             if (isDerivedClass) {
83794                 if (superCallExpression && statementOffset === constructor.body.statements.length && !(constructor.body.transformFlags & 4096 /* ContainsLexicalThis */)) {
83795                     // If the subclass constructor does *not* contain `this` and *ends* with a `super()` call, we will use the
83796                     // following representation:
83797                     //
83798                     // ```
83799                     // // es2015 (source)
83800                     // class C extends Base {
83801                     //     constructor() {
83802                     //         super("foo");
83803                     //     }
83804                     // }
83805                     //
83806                     // // es5 (transformed)
83807                     // var C = (function (_super) {
83808                     //     function C() {
83809                     //         return _super.call(this, "foo") || this;
83810                     //     }
83811                     //     return C;
83812                     // })(Base);
83813                     // ```
83814                     var superCall = ts.cast(ts.cast(superCallExpression, ts.isBinaryExpression).left, ts.isCallExpression);
83815                     var returnStatement = ts.createReturn(superCallExpression);
83816                     ts.setCommentRange(returnStatement, ts.getCommentRange(superCall));
83817                     ts.setEmitFlags(superCall, 1536 /* NoComments */);
83818                     statements.push(returnStatement);
83819                 }
83820                 else {
83821                     // Otherwise, we will use the following transformed representation for calls to `super()` in a constructor:
83822                     //
83823                     // ```
83824                     // // es2015 (source)
83825                     // class C extends Base {
83826                     //     constructor() {
83827                     //         super("foo");
83828                     //         this.x = 1;
83829                     //     }
83830                     // }
83831                     //
83832                     // // es5 (transformed)
83833                     // var C = (function (_super) {
83834                     //     function C() {
83835                     //         var _this = _super.call(this, "foo") || this;
83836                     //         _this.x = 1;
83837                     //         return _this;
83838                     //     }
83839                     //     return C;
83840                     // })(Base);
83841                     // ```
83842                     // Since the `super()` call was the first statement, we insert the `this` capturing call to
83843                     // `super()` at the top of the list of `statements` (after any pre-existing custom prologues).
83844                     insertCaptureThisForNode(statements, constructor, superCallExpression || createActualThis());
83845                     if (!isSufficientlyCoveredByReturnStatements(constructor.body)) {
83846                         statements.push(ts.createReturn(ts.createFileLevelUniqueName("_this")));
83847                     }
83848                 }
83849             }
83850             else {
83851                 // If a class is not derived from a base class or does not have a call to `super()`, `this` is only
83852                 // captured when necessitated by an arrow function capturing the lexical `this`:
83853                 //
83854                 // ```
83855                 // // es2015
83856                 // class C {}
83857                 //
83858                 // // es5
83859                 // var C = (function () {
83860                 //     function C() {
83861                 //     }
83862                 //     return C;
83863                 // })();
83864                 // ```
83865                 insertCaptureThisForNodeIfNeeded(prologue, constructor);
83866             }
83867             var block = ts.createBlock(ts.setTextRange(ts.createNodeArray(ts.concatenate(prologue, statements)), 
83868             /*location*/ constructor.body.statements), 
83869             /*multiLine*/ true);
83870             ts.setTextRange(block, constructor.body);
83871             return block;
83872         }
83873         /**
83874          * We want to try to avoid emitting a return statement in certain cases if a user already returned something.
83875          * It would generate obviously dead code, so we'll try to make things a little bit prettier
83876          * by doing a minimal check on whether some common patterns always explicitly return.
83877          */
83878         function isSufficientlyCoveredByReturnStatements(statement) {
83879             // A return statement is considered covered.
83880             if (statement.kind === 235 /* ReturnStatement */) {
83881                 return true;
83882             }
83883             // An if-statement with two covered branches is covered.
83884             else if (statement.kind === 227 /* IfStatement */) {
83885                 var ifStatement = statement;
83886                 if (ifStatement.elseStatement) {
83887                     return isSufficientlyCoveredByReturnStatements(ifStatement.thenStatement) &&
83888                         isSufficientlyCoveredByReturnStatements(ifStatement.elseStatement);
83889                 }
83890             }
83891             // A block is covered if it has a last statement which is covered.
83892             else if (statement.kind === 223 /* Block */) {
83893                 var lastStatement = ts.lastOrUndefined(statement.statements);
83894                 if (lastStatement && isSufficientlyCoveredByReturnStatements(lastStatement)) {
83895                     return true;
83896                 }
83897             }
83898             return false;
83899         }
83900         function createActualThis() {
83901             return ts.setEmitFlags(ts.createThis(), 4 /* NoSubstitution */);
83902         }
83903         function createDefaultSuperCallOrThis() {
83904             return ts.createLogicalOr(ts.createLogicalAnd(ts.createStrictInequality(ts.createFileLevelUniqueName("_super"), ts.createNull()), ts.createFunctionApply(ts.createFileLevelUniqueName("_super"), createActualThis(), ts.createIdentifier("arguments"))), createActualThis());
83905         }
83906         /**
83907          * Visits a parameter declaration.
83908          *
83909          * @param node A ParameterDeclaration node.
83910          */
83911         function visitParameter(node) {
83912             if (node.dotDotDotToken) {
83913                 // rest parameters are elided
83914                 return undefined;
83915             }
83916             else if (ts.isBindingPattern(node.name)) {
83917                 // Binding patterns are converted into a generated name and are
83918                 // evaluated inside the function body.
83919                 return ts.setOriginalNode(ts.setTextRange(ts.createParameter(
83920                 /*decorators*/ undefined, 
83921                 /*modifiers*/ undefined, 
83922                 /*dotDotDotToken*/ undefined, ts.getGeneratedNameForNode(node), 
83923                 /*questionToken*/ undefined, 
83924                 /*type*/ undefined, 
83925                 /*initializer*/ undefined), 
83926                 /*location*/ node), 
83927                 /*original*/ node);
83928             }
83929             else if (node.initializer) {
83930                 // Initializers are elided
83931                 return ts.setOriginalNode(ts.setTextRange(ts.createParameter(
83932                 /*decorators*/ undefined, 
83933                 /*modifiers*/ undefined, 
83934                 /*dotDotDotToken*/ undefined, node.name, 
83935                 /*questionToken*/ undefined, 
83936                 /*type*/ undefined, 
83937                 /*initializer*/ undefined), 
83938                 /*location*/ node), 
83939                 /*original*/ node);
83940             }
83941             else {
83942                 return node;
83943             }
83944         }
83945         function hasDefaultValueOrBindingPattern(node) {
83946             return node.initializer !== undefined
83947                 || ts.isBindingPattern(node.name);
83948         }
83949         /**
83950          * Adds statements to the body of a function-like node if it contains parameters with
83951          * binding patterns or initializers.
83952          *
83953          * @param statements The statements for the new function body.
83954          * @param node A function-like node.
83955          */
83956         function addDefaultValueAssignmentsIfNeeded(statements, node) {
83957             if (!ts.some(node.parameters, hasDefaultValueOrBindingPattern)) {
83958                 return false;
83959             }
83960             var added = false;
83961             for (var _i = 0, _a = node.parameters; _i < _a.length; _i++) {
83962                 var parameter = _a[_i];
83963                 var name = parameter.name, initializer = parameter.initializer, dotDotDotToken = parameter.dotDotDotToken;
83964                 // A rest parameter cannot have a binding pattern or an initializer,
83965                 // so let's just ignore it.
83966                 if (dotDotDotToken) {
83967                     continue;
83968                 }
83969                 if (ts.isBindingPattern(name)) {
83970                     added = insertDefaultValueAssignmentForBindingPattern(statements, parameter, name, initializer) || added;
83971                 }
83972                 else if (initializer) {
83973                     insertDefaultValueAssignmentForInitializer(statements, parameter, name, initializer);
83974                     added = true;
83975                 }
83976             }
83977             return added;
83978         }
83979         /**
83980          * Adds statements to the body of a function-like node for parameters with binding patterns
83981          *
83982          * @param statements The statements for the new function body.
83983          * @param parameter The parameter for the function.
83984          * @param name The name of the parameter.
83985          * @param initializer The initializer for the parameter.
83986          */
83987         function insertDefaultValueAssignmentForBindingPattern(statements, parameter, name, initializer) {
83988             // In cases where a binding pattern is simply '[]' or '{}',
83989             // we usually don't want to emit a var declaration; however, in the presence
83990             // of an initializer, we must emit that expression to preserve side effects.
83991             if (name.elements.length > 0) {
83992                 ts.insertStatementAfterCustomPrologue(statements, ts.setEmitFlags(ts.createVariableStatement(
83993                 /*modifiers*/ undefined, ts.createVariableDeclarationList(ts.flattenDestructuringBinding(parameter, visitor, context, 0 /* All */, ts.getGeneratedNameForNode(parameter)))), 1048576 /* CustomPrologue */));
83994                 return true;
83995             }
83996             else if (initializer) {
83997                 ts.insertStatementAfterCustomPrologue(statements, ts.setEmitFlags(ts.createExpressionStatement(ts.createAssignment(ts.getGeneratedNameForNode(parameter), ts.visitNode(initializer, visitor, ts.isExpression))), 1048576 /* CustomPrologue */));
83998                 return true;
83999             }
84000             return false;
84001         }
84002         /**
84003          * Adds statements to the body of a function-like node for parameters with initializers.
84004          *
84005          * @param statements The statements for the new function body.
84006          * @param parameter The parameter for the function.
84007          * @param name The name of the parameter.
84008          * @param initializer The initializer for the parameter.
84009          */
84010         function insertDefaultValueAssignmentForInitializer(statements, parameter, name, initializer) {
84011             initializer = ts.visitNode(initializer, visitor, ts.isExpression);
84012             var statement = ts.createIf(ts.createTypeCheck(ts.getSynthesizedClone(name), "undefined"), ts.setEmitFlags(ts.setTextRange(ts.createBlock([
84013                 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 */))
84014             ]), parameter), 1 /* SingleLine */ | 32 /* NoTrailingSourceMap */ | 384 /* NoTokenSourceMaps */ | 1536 /* NoComments */));
84015             ts.startOnNewLine(statement);
84016             ts.setTextRange(statement, parameter);
84017             ts.setEmitFlags(statement, 384 /* NoTokenSourceMaps */ | 32 /* NoTrailingSourceMap */ | 1048576 /* CustomPrologue */ | 1536 /* NoComments */);
84018             ts.insertStatementAfterCustomPrologue(statements, statement);
84019         }
84020         /**
84021          * Gets a value indicating whether we need to add statements to handle a rest parameter.
84022          *
84023          * @param node A ParameterDeclaration node.
84024          * @param inConstructorWithSynthesizedSuper A value indicating whether the parameter is
84025          *                                          part of a constructor declaration with a
84026          *                                          synthesized call to `super`
84027          */
84028         function shouldAddRestParameter(node, inConstructorWithSynthesizedSuper) {
84029             return !!(node && node.dotDotDotToken && !inConstructorWithSynthesizedSuper);
84030         }
84031         /**
84032          * Adds statements to the body of a function-like node if it contains a rest parameter.
84033          *
84034          * @param statements The statements for the new function body.
84035          * @param node A function-like node.
84036          * @param inConstructorWithSynthesizedSuper A value indicating whether the parameter is
84037          *                                          part of a constructor declaration with a
84038          *                                          synthesized call to `super`
84039          */
84040         function addRestParameterIfNeeded(statements, node, inConstructorWithSynthesizedSuper) {
84041             var prologueStatements = [];
84042             var parameter = ts.lastOrUndefined(node.parameters);
84043             if (!shouldAddRestParameter(parameter, inConstructorWithSynthesizedSuper)) {
84044                 return false;
84045             }
84046             // `declarationName` is the name of the local declaration for the parameter.
84047             var declarationName = parameter.name.kind === 75 /* Identifier */ ? ts.getMutableClone(parameter.name) : ts.createTempVariable(/*recordTempVariable*/ undefined);
84048             ts.setEmitFlags(declarationName, 48 /* NoSourceMap */);
84049             // `expressionName` is the name of the parameter used in expressions.
84050             var expressionName = parameter.name.kind === 75 /* Identifier */ ? ts.getSynthesizedClone(parameter.name) : declarationName;
84051             var restIndex = node.parameters.length - 1;
84052             var temp = ts.createLoopVariable();
84053             // var param = [];
84054             prologueStatements.push(ts.setEmitFlags(ts.setTextRange(ts.createVariableStatement(
84055             /*modifiers*/ undefined, ts.createVariableDeclarationList([
84056                 ts.createVariableDeclaration(declarationName, 
84057                 /*type*/ undefined, ts.createArrayLiteral([]))
84058             ])), 
84059             /*location*/ parameter), 1048576 /* CustomPrologue */));
84060             // for (var _i = restIndex; _i < arguments.length; _i++) {
84061             //   param[_i - restIndex] = arguments[_i];
84062             // }
84063             var forStatement = ts.createFor(ts.setTextRange(ts.createVariableDeclarationList([
84064                 ts.createVariableDeclaration(temp, /*type*/ undefined, ts.createLiteral(restIndex))
84065             ]), parameter), ts.setTextRange(ts.createLessThan(temp, ts.createPropertyAccess(ts.createIdentifier("arguments"), "length")), parameter), ts.setTextRange(ts.createPostfixIncrement(temp), parameter), ts.createBlock([
84066                 ts.startOnNewLine(ts.setTextRange(ts.createExpressionStatement(ts.createAssignment(ts.createElementAccess(expressionName, restIndex === 0
84067                     ? temp
84068                     : ts.createSubtract(temp, ts.createLiteral(restIndex))), ts.createElementAccess(ts.createIdentifier("arguments"), temp))), 
84069                 /*location*/ parameter))
84070             ]));
84071             ts.setEmitFlags(forStatement, 1048576 /* CustomPrologue */);
84072             ts.startOnNewLine(forStatement);
84073             prologueStatements.push(forStatement);
84074             if (parameter.name.kind !== 75 /* Identifier */) {
84075                 // do the actual destructuring of the rest parameter if necessary
84076                 prologueStatements.push(ts.setEmitFlags(ts.setTextRange(ts.createVariableStatement(
84077                 /*modifiers*/ undefined, ts.createVariableDeclarationList(ts.flattenDestructuringBinding(parameter, visitor, context, 0 /* All */, expressionName))), parameter), 1048576 /* CustomPrologue */));
84078             }
84079             ts.insertStatementsAfterCustomPrologue(statements, prologueStatements);
84080             return true;
84081         }
84082         /**
84083          * Adds a statement to capture the `this` of a function declaration if it is needed.
84084          * NOTE: This must be executed *after* the subtree has been visited.
84085          *
84086          * @param statements The statements for the new function body.
84087          * @param node A node.
84088          */
84089         function insertCaptureThisForNodeIfNeeded(statements, node) {
84090             if (hierarchyFacts & 32768 /* CapturedLexicalThis */ && node.kind !== 202 /* ArrowFunction */) {
84091                 insertCaptureThisForNode(statements, node, ts.createThis());
84092                 return true;
84093             }
84094             return false;
84095         }
84096         function insertCaptureThisForNode(statements, node, initializer) {
84097             enableSubstitutionsForCapturedThis();
84098             var captureThisStatement = ts.createVariableStatement(
84099             /*modifiers*/ undefined, ts.createVariableDeclarationList([
84100                 ts.createVariableDeclaration(ts.createFileLevelUniqueName("_this"), 
84101                 /*type*/ undefined, initializer)
84102             ]));
84103             ts.setEmitFlags(captureThisStatement, 1536 /* NoComments */ | 1048576 /* CustomPrologue */);
84104             ts.setSourceMapRange(captureThisStatement, node);
84105             ts.insertStatementAfterCustomPrologue(statements, captureThisStatement);
84106         }
84107         function insertCaptureNewTargetIfNeeded(statements, node, copyOnWrite) {
84108             if (hierarchyFacts & 16384 /* NewTarget */) {
84109                 var newTarget = void 0;
84110                 switch (node.kind) {
84111                     case 202 /* ArrowFunction */:
84112                         return statements;
84113                     case 161 /* MethodDeclaration */:
84114                     case 163 /* GetAccessor */:
84115                     case 164 /* SetAccessor */:
84116                         // Methods and accessors cannot be constructors, so 'new.target' will
84117                         // always return 'undefined'.
84118                         newTarget = ts.createVoidZero();
84119                         break;
84120                     case 162 /* Constructor */:
84121                         // Class constructors can only be called with `new`, so `this.constructor`
84122                         // should be relatively safe to use.
84123                         newTarget = ts.createPropertyAccess(ts.setEmitFlags(ts.createThis(), 4 /* NoSubstitution */), "constructor");
84124                         break;
84125                     case 244 /* FunctionDeclaration */:
84126                     case 201 /* FunctionExpression */:
84127                         // Functions can be called or constructed, and may have a `this` due to
84128                         // being a member or when calling an imported function via `other_1.f()`.
84129                         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());
84130                         break;
84131                     default:
84132                         return ts.Debug.failBadSyntaxKind(node);
84133                 }
84134                 var captureNewTargetStatement = ts.createVariableStatement(
84135                 /*modifiers*/ undefined, ts.createVariableDeclarationList([
84136                     ts.createVariableDeclaration(ts.createFileLevelUniqueName("_newTarget"), 
84137                     /*type*/ undefined, newTarget)
84138                 ]));
84139                 ts.setEmitFlags(captureNewTargetStatement, 1536 /* NoComments */ | 1048576 /* CustomPrologue */);
84140                 if (copyOnWrite) {
84141                     statements = statements.slice();
84142                 }
84143                 ts.insertStatementAfterCustomPrologue(statements, captureNewTargetStatement);
84144             }
84145             return statements;
84146         }
84147         /**
84148          * Adds statements to the class body function for a class to define the members of the
84149          * class.
84150          *
84151          * @param statements The statements for the class body function.
84152          * @param node The ClassExpression or ClassDeclaration node.
84153          */
84154         function addClassMembers(statements, node) {
84155             for (var _i = 0, _a = node.members; _i < _a.length; _i++) {
84156                 var member = _a[_i];
84157                 switch (member.kind) {
84158                     case 222 /* SemicolonClassElement */:
84159                         statements.push(transformSemicolonClassElementToStatement(member));
84160                         break;
84161                     case 161 /* MethodDeclaration */:
84162                         statements.push(transformClassMethodDeclarationToStatement(getClassMemberPrefix(node, member), member, node));
84163                         break;
84164                     case 163 /* GetAccessor */:
84165                     case 164 /* SetAccessor */:
84166                         var accessors = ts.getAllAccessorDeclarations(node.members, member);
84167                         if (member === accessors.firstAccessor) {
84168                             statements.push(transformAccessorsToStatement(getClassMemberPrefix(node, member), accessors, node));
84169                         }
84170                         break;
84171                     case 162 /* Constructor */:
84172                         // Constructors are handled in visitClassExpression/visitClassDeclaration
84173                         break;
84174                     default:
84175                         ts.Debug.failBadSyntaxKind(member, currentSourceFile && currentSourceFile.fileName);
84176                         break;
84177                 }
84178             }
84179         }
84180         /**
84181          * Transforms a SemicolonClassElement into a statement for a class body function.
84182          *
84183          * @param member The SemicolonClassElement node.
84184          */
84185         function transformSemicolonClassElementToStatement(member) {
84186             return ts.setTextRange(ts.createEmptyStatement(), member);
84187         }
84188         /**
84189          * Transforms a MethodDeclaration into a statement for a class body function.
84190          *
84191          * @param receiver The receiver for the member.
84192          * @param member The MethodDeclaration node.
84193          */
84194         function transformClassMethodDeclarationToStatement(receiver, member, container) {
84195             var commentRange = ts.getCommentRange(member);
84196             var sourceMapRange = ts.getSourceMapRange(member);
84197             var memberFunction = transformFunctionLikeToExpression(member, /*location*/ member, /*name*/ undefined, container);
84198             var propertyName = ts.visitNode(member.name, visitor, ts.isPropertyName);
84199             var e;
84200             if (!ts.isPrivateIdentifier(propertyName) && context.getCompilerOptions().useDefineForClassFields) {
84201                 var name = ts.isComputedPropertyName(propertyName) ? propertyName.expression
84202                     : ts.isIdentifier(propertyName) ? ts.createStringLiteral(ts.unescapeLeadingUnderscores(propertyName.escapedText))
84203                         : propertyName;
84204                 e = ts.createObjectDefinePropertyCall(receiver, name, ts.createPropertyDescriptor({ value: memberFunction, enumerable: false, writable: true, configurable: true }));
84205             }
84206             else {
84207                 var memberName = ts.createMemberAccessForPropertyName(receiver, propertyName, /*location*/ member.name);
84208                 e = ts.createAssignment(memberName, memberFunction);
84209             }
84210             ts.setEmitFlags(memberFunction, 1536 /* NoComments */);
84211             ts.setSourceMapRange(memberFunction, sourceMapRange);
84212             var statement = ts.setTextRange(ts.createExpressionStatement(e), /*location*/ member);
84213             ts.setOriginalNode(statement, member);
84214             ts.setCommentRange(statement, commentRange);
84215             // The location for the statement is used to emit comments only.
84216             // No source map should be emitted for this statement to align with the
84217             // old emitter.
84218             ts.setEmitFlags(statement, 48 /* NoSourceMap */);
84219             return statement;
84220         }
84221         /**
84222          * Transforms a set of related of get/set accessors into a statement for a class body function.
84223          *
84224          * @param receiver The receiver for the member.
84225          * @param accessors The set of related get/set accessors.
84226          */
84227         function transformAccessorsToStatement(receiver, accessors, container) {
84228             var statement = ts.createExpressionStatement(transformAccessorsToExpression(receiver, accessors, container, /*startsOnNewLine*/ false));
84229             // The location for the statement is used to emit source maps only.
84230             // No comments should be emitted for this statement to align with the
84231             // old emitter.
84232             ts.setEmitFlags(statement, 1536 /* NoComments */);
84233             ts.setSourceMapRange(statement, ts.getSourceMapRange(accessors.firstAccessor));
84234             return statement;
84235         }
84236         /**
84237          * Transforms a set of related get/set accessors into an expression for either a class
84238          * body function or an ObjectLiteralExpression with computed properties.
84239          *
84240          * @param receiver The receiver for the member.
84241          */
84242         function transformAccessorsToExpression(receiver, _a, container, startsOnNewLine) {
84243             var firstAccessor = _a.firstAccessor, getAccessor = _a.getAccessor, setAccessor = _a.setAccessor;
84244             // To align with source maps in the old emitter, the receiver and property name
84245             // arguments are both mapped contiguously to the accessor name.
84246             var target = ts.getMutableClone(receiver);
84247             ts.setEmitFlags(target, 1536 /* NoComments */ | 32 /* NoTrailingSourceMap */);
84248             ts.setSourceMapRange(target, firstAccessor.name);
84249             var visitedAccessorName = ts.visitNode(firstAccessor.name, visitor, ts.isPropertyName);
84250             if (ts.isPrivateIdentifier(visitedAccessorName)) {
84251                 return ts.Debug.failBadSyntaxKind(visitedAccessorName, "Encountered unhandled private identifier while transforming ES2015.");
84252             }
84253             var propertyName = ts.createExpressionForPropertyName(visitedAccessorName);
84254             ts.setEmitFlags(propertyName, 1536 /* NoComments */ | 16 /* NoLeadingSourceMap */);
84255             ts.setSourceMapRange(propertyName, firstAccessor.name);
84256             var properties = [];
84257             if (getAccessor) {
84258                 var getterFunction = transformFunctionLikeToExpression(getAccessor, /*location*/ undefined, /*name*/ undefined, container);
84259                 ts.setSourceMapRange(getterFunction, ts.getSourceMapRange(getAccessor));
84260                 ts.setEmitFlags(getterFunction, 512 /* NoLeadingComments */);
84261                 var getter = ts.createPropertyAssignment("get", getterFunction);
84262                 ts.setCommentRange(getter, ts.getCommentRange(getAccessor));
84263                 properties.push(getter);
84264             }
84265             if (setAccessor) {
84266                 var setterFunction = transformFunctionLikeToExpression(setAccessor, /*location*/ undefined, /*name*/ undefined, container);
84267                 ts.setSourceMapRange(setterFunction, ts.getSourceMapRange(setAccessor));
84268                 ts.setEmitFlags(setterFunction, 512 /* NoLeadingComments */);
84269                 var setter = ts.createPropertyAssignment("set", setterFunction);
84270                 ts.setCommentRange(setter, ts.getCommentRange(setAccessor));
84271                 properties.push(setter);
84272             }
84273             properties.push(ts.createPropertyAssignment("enumerable", getAccessor || setAccessor ? ts.createFalse() : ts.createTrue()), ts.createPropertyAssignment("configurable", ts.createTrue()));
84274             var call = ts.createCall(ts.createPropertyAccess(ts.createIdentifier("Object"), "defineProperty"), 
84275             /*typeArguments*/ undefined, [
84276                 target,
84277                 propertyName,
84278                 ts.createObjectLiteral(properties, /*multiLine*/ true)
84279             ]);
84280             if (startsOnNewLine) {
84281                 ts.startOnNewLine(call);
84282             }
84283             return call;
84284         }
84285         /**
84286          * Visits an ArrowFunction and transforms it into a FunctionExpression.
84287          *
84288          * @param node An ArrowFunction node.
84289          */
84290         function visitArrowFunction(node) {
84291             if (node.transformFlags & 4096 /* ContainsLexicalThis */) {
84292                 hierarchyFacts |= 32768 /* CapturedLexicalThis */;
84293             }
84294             var savedConvertedLoopState = convertedLoopState;
84295             convertedLoopState = undefined;
84296             var ancestorFacts = enterSubtree(15232 /* ArrowFunctionExcludes */, 66 /* ArrowFunctionIncludes */);
84297             var func = ts.createFunctionExpression(
84298             /*modifiers*/ undefined, 
84299             /*asteriskToken*/ undefined, 
84300             /*name*/ undefined, 
84301             /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), 
84302             /*type*/ undefined, transformFunctionBody(node));
84303             ts.setTextRange(func, node);
84304             ts.setOriginalNode(func, node);
84305             ts.setEmitFlags(func, 8 /* CapturesThis */);
84306             if (hierarchyFacts & 32768 /* CapturedLexicalThis */) {
84307                 enableSubstitutionsForCapturedThis();
84308             }
84309             // If an arrow function contains
84310             exitSubtree(ancestorFacts, 0 /* ArrowFunctionSubtreeExcludes */, 0 /* None */);
84311             convertedLoopState = savedConvertedLoopState;
84312             return func;
84313         }
84314         /**
84315          * Visits a FunctionExpression node.
84316          *
84317          * @param node a FunctionExpression node.
84318          */
84319         function visitFunctionExpression(node) {
84320             var ancestorFacts = ts.getEmitFlags(node) & 262144 /* AsyncFunctionBody */
84321                 ? enterSubtree(16278 /* AsyncFunctionBodyExcludes */, 69 /* AsyncFunctionBodyIncludes */)
84322                 : enterSubtree(16286 /* FunctionExcludes */, 65 /* FunctionIncludes */);
84323             var savedConvertedLoopState = convertedLoopState;
84324             convertedLoopState = undefined;
84325             var parameters = ts.visitParameterList(node.parameters, visitor, context);
84326             var body = transformFunctionBody(node);
84327             var name = hierarchyFacts & 16384 /* NewTarget */
84328                 ? ts.getLocalName(node)
84329                 : node.name;
84330             exitSubtree(ancestorFacts, 49152 /* FunctionSubtreeExcludes */, 0 /* None */);
84331             convertedLoopState = savedConvertedLoopState;
84332             return ts.updateFunctionExpression(node, 
84333             /*modifiers*/ undefined, node.asteriskToken, name, 
84334             /*typeParameters*/ undefined, parameters, 
84335             /*type*/ undefined, body);
84336         }
84337         /**
84338          * Visits a FunctionDeclaration node.
84339          *
84340          * @param node a FunctionDeclaration node.
84341          */
84342         function visitFunctionDeclaration(node) {
84343             var savedConvertedLoopState = convertedLoopState;
84344             convertedLoopState = undefined;
84345             var ancestorFacts = enterSubtree(16286 /* FunctionExcludes */, 65 /* FunctionIncludes */);
84346             var parameters = ts.visitParameterList(node.parameters, visitor, context);
84347             var body = transformFunctionBody(node);
84348             var name = hierarchyFacts & 16384 /* NewTarget */
84349                 ? ts.getLocalName(node)
84350                 : node.name;
84351             exitSubtree(ancestorFacts, 49152 /* FunctionSubtreeExcludes */, 0 /* None */);
84352             convertedLoopState = savedConvertedLoopState;
84353             return ts.updateFunctionDeclaration(node, 
84354             /*decorators*/ undefined, ts.visitNodes(node.modifiers, visitor, ts.isModifier), node.asteriskToken, name, 
84355             /*typeParameters*/ undefined, parameters, 
84356             /*type*/ undefined, body);
84357         }
84358         /**
84359          * Transforms a function-like node into a FunctionExpression.
84360          *
84361          * @param node The function-like node to transform.
84362          * @param location The source-map location for the new FunctionExpression.
84363          * @param name The name of the new FunctionExpression.
84364          */
84365         function transformFunctionLikeToExpression(node, location, name, container) {
84366             var savedConvertedLoopState = convertedLoopState;
84367             convertedLoopState = undefined;
84368             var ancestorFacts = container && ts.isClassLike(container) && !ts.hasModifier(node, 32 /* Static */)
84369                 ? enterSubtree(16286 /* FunctionExcludes */, 65 /* FunctionIncludes */ | 8 /* NonStaticClassElement */)
84370                 : enterSubtree(16286 /* FunctionExcludes */, 65 /* FunctionIncludes */);
84371             var parameters = ts.visitParameterList(node.parameters, visitor, context);
84372             var body = transformFunctionBody(node);
84373             if (hierarchyFacts & 16384 /* NewTarget */ && !name && (node.kind === 244 /* FunctionDeclaration */ || node.kind === 201 /* FunctionExpression */)) {
84374                 name = ts.getGeneratedNameForNode(node);
84375             }
84376             exitSubtree(ancestorFacts, 49152 /* FunctionSubtreeExcludes */, 0 /* None */);
84377             convertedLoopState = savedConvertedLoopState;
84378             return ts.setOriginalNode(ts.setTextRange(ts.createFunctionExpression(
84379             /*modifiers*/ undefined, node.asteriskToken, name, 
84380             /*typeParameters*/ undefined, parameters, 
84381             /*type*/ undefined, body), location), 
84382             /*original*/ node);
84383         }
84384         /**
84385          * Transforms the body of a function-like node.
84386          *
84387          * @param node A function-like node.
84388          */
84389         function transformFunctionBody(node) {
84390             var multiLine = false; // indicates whether the block *must* be emitted as multiple lines
84391             var singleLine = false; // indicates whether the block *may* be emitted as a single line
84392             var statementsLocation;
84393             var closeBraceLocation;
84394             var prologue = [];
84395             var statements = [];
84396             var body = node.body;
84397             var statementOffset;
84398             resumeLexicalEnvironment();
84399             if (ts.isBlock(body)) {
84400                 // ensureUseStrict is false because no new prologue-directive should be added.
84401                 // addStandardPrologue will put already-existing directives at the beginning of the target statement-array
84402                 statementOffset = ts.addStandardPrologue(prologue, body.statements, /*ensureUseStrict*/ false);
84403                 statementOffset = ts.addCustomPrologue(statements, body.statements, statementOffset, visitor, ts.isHoistedFunction);
84404                 statementOffset = ts.addCustomPrologue(statements, body.statements, statementOffset, visitor, ts.isHoistedVariableStatement);
84405             }
84406             multiLine = addDefaultValueAssignmentsIfNeeded(statements, node) || multiLine;
84407             multiLine = addRestParameterIfNeeded(statements, node, /*inConstructorWithSynthesizedSuper*/ false) || multiLine;
84408             if (ts.isBlock(body)) {
84409                 // addCustomPrologue puts already-existing directives at the beginning of the target statement-array
84410                 statementOffset = ts.addCustomPrologue(statements, body.statements, statementOffset, visitor);
84411                 statementsLocation = body.statements;
84412                 ts.addRange(statements, ts.visitNodes(body.statements, visitor, ts.isStatement, statementOffset));
84413                 // If the original body was a multi-line block, this must be a multi-line block.
84414                 if (!multiLine && body.multiLine) {
84415                     multiLine = true;
84416                 }
84417             }
84418             else {
84419                 ts.Debug.assert(node.kind === 202 /* ArrowFunction */);
84420                 // To align with the old emitter, we use a synthetic end position on the location
84421                 // for the statement list we synthesize when we down-level an arrow function with
84422                 // an expression function body. This prevents both comments and source maps from
84423                 // being emitted for the end position only.
84424                 statementsLocation = ts.moveRangeEnd(body, -1);
84425                 var equalsGreaterThanToken = node.equalsGreaterThanToken;
84426                 if (!ts.nodeIsSynthesized(equalsGreaterThanToken) && !ts.nodeIsSynthesized(body)) {
84427                     if (ts.rangeEndIsOnSameLineAsRangeStart(equalsGreaterThanToken, body, currentSourceFile)) {
84428                         singleLine = true;
84429                     }
84430                     else {
84431                         multiLine = true;
84432                     }
84433                 }
84434                 var expression = ts.visitNode(body, visitor, ts.isExpression);
84435                 var returnStatement = ts.createReturn(expression);
84436                 ts.setTextRange(returnStatement, body);
84437                 ts.moveSyntheticComments(returnStatement, body);
84438                 ts.setEmitFlags(returnStatement, 384 /* NoTokenSourceMaps */ | 32 /* NoTrailingSourceMap */ | 1024 /* NoTrailingComments */);
84439                 statements.push(returnStatement);
84440                 // To align with the source map emit for the old emitter, we set a custom
84441                 // source map location for the close brace.
84442                 closeBraceLocation = body;
84443             }
84444             ts.mergeLexicalEnvironment(prologue, endLexicalEnvironment());
84445             insertCaptureNewTargetIfNeeded(prologue, node, /*copyOnWrite*/ false);
84446             insertCaptureThisForNodeIfNeeded(prologue, node);
84447             // If we added any final generated statements, this must be a multi-line block
84448             if (ts.some(prologue)) {
84449                 multiLine = true;
84450             }
84451             statements.unshift.apply(statements, prologue);
84452             if (ts.isBlock(body) && ts.arrayIsEqualTo(statements, body.statements)) {
84453                 // no changes were made, preserve the tree
84454                 return body;
84455             }
84456             var block = ts.createBlock(ts.setTextRange(ts.createNodeArray(statements), statementsLocation), multiLine);
84457             ts.setTextRange(block, node.body);
84458             if (!multiLine && singleLine) {
84459                 ts.setEmitFlags(block, 1 /* SingleLine */);
84460             }
84461             if (closeBraceLocation) {
84462                 ts.setTokenSourceMapRange(block, 19 /* CloseBraceToken */, closeBraceLocation);
84463             }
84464             ts.setOriginalNode(block, node.body);
84465             return block;
84466         }
84467         function visitBlock(node, isFunctionBody) {
84468             if (isFunctionBody) {
84469                 // A function body is not a block scope.
84470                 return ts.visitEachChild(node, visitor, context);
84471             }
84472             var ancestorFacts = hierarchyFacts & 256 /* IterationStatement */
84473                 ? enterSubtree(7104 /* IterationStatementBlockExcludes */, 512 /* IterationStatementBlockIncludes */)
84474                 : enterSubtree(6976 /* BlockExcludes */, 128 /* BlockIncludes */);
84475             var updated = ts.visitEachChild(node, visitor, context);
84476             exitSubtree(ancestorFacts, 0 /* None */, 0 /* None */);
84477             return updated;
84478         }
84479         /**
84480          * Visits an ExpressionStatement that contains a destructuring assignment.
84481          *
84482          * @param node An ExpressionStatement node.
84483          */
84484         function visitExpressionStatement(node) {
84485             // If we are here it is most likely because our expression is a destructuring assignment.
84486             switch (node.expression.kind) {
84487                 case 200 /* ParenthesizedExpression */:
84488                     return ts.updateExpressionStatement(node, visitParenthesizedExpression(node.expression, /*needsDestructuringValue*/ false));
84489                 case 209 /* BinaryExpression */:
84490                     return ts.updateExpressionStatement(node, visitBinaryExpression(node.expression, /*needsDestructuringValue*/ false));
84491             }
84492             return ts.visitEachChild(node, visitor, context);
84493         }
84494         /**
84495          * Visits a ParenthesizedExpression that may contain a destructuring assignment.
84496          *
84497          * @param node A ParenthesizedExpression node.
84498          * @param needsDestructuringValue A value indicating whether we need to hold onto the rhs
84499          *                                of a destructuring assignment.
84500          */
84501         function visitParenthesizedExpression(node, needsDestructuringValue) {
84502             // If we are here it is most likely because our expression is a destructuring assignment.
84503             if (!needsDestructuringValue) {
84504                 // By default we always emit the RHS at the end of a flattened destructuring
84505                 // expression. If we are in a state where we do not need the destructuring value,
84506                 // we pass that information along to the children that care about it.
84507                 switch (node.expression.kind) {
84508                     case 200 /* ParenthesizedExpression */:
84509                         return ts.updateParen(node, visitParenthesizedExpression(node.expression, /*needsDestructuringValue*/ false));
84510                     case 209 /* BinaryExpression */:
84511                         return ts.updateParen(node, visitBinaryExpression(node.expression, /*needsDestructuringValue*/ false));
84512                 }
84513             }
84514             return ts.visitEachChild(node, visitor, context);
84515         }
84516         /**
84517          * Visits a BinaryExpression that contains a destructuring assignment.
84518          *
84519          * @param node A BinaryExpression node.
84520          * @param needsDestructuringValue A value indicating whether we need to hold onto the rhs
84521          *                                of a destructuring assignment.
84522          */
84523         function visitBinaryExpression(node, needsDestructuringValue) {
84524             // If we are here it is because this is a destructuring assignment.
84525             if (ts.isDestructuringAssignment(node)) {
84526                 return ts.flattenDestructuringAssignment(node, visitor, context, 0 /* All */, needsDestructuringValue);
84527             }
84528             return ts.visitEachChild(node, visitor, context);
84529         }
84530         function isVariableStatementOfTypeScriptClassWrapper(node) {
84531             return node.declarationList.declarations.length === 1
84532                 && !!node.declarationList.declarations[0].initializer
84533                 && !!(ts.getEmitFlags(node.declarationList.declarations[0].initializer) & 33554432 /* TypeScriptClassWrapper */);
84534         }
84535         function visitVariableStatement(node) {
84536             var ancestorFacts = enterSubtree(0 /* None */, ts.hasModifier(node, 1 /* Export */) ? 32 /* ExportedVariableStatement */ : 0 /* None */);
84537             var updated;
84538             if (convertedLoopState && (node.declarationList.flags & 3 /* BlockScoped */) === 0 && !isVariableStatementOfTypeScriptClassWrapper(node)) {
84539                 // we are inside a converted loop - hoist variable declarations
84540                 var assignments = void 0;
84541                 for (var _i = 0, _a = node.declarationList.declarations; _i < _a.length; _i++) {
84542                     var decl = _a[_i];
84543                     hoistVariableDeclarationDeclaredInConvertedLoop(convertedLoopState, decl);
84544                     if (decl.initializer) {
84545                         var assignment = void 0;
84546                         if (ts.isBindingPattern(decl.name)) {
84547                             assignment = ts.flattenDestructuringAssignment(decl, visitor, context, 0 /* All */);
84548                         }
84549                         else {
84550                             assignment = ts.createBinary(decl.name, 62 /* EqualsToken */, ts.visitNode(decl.initializer, visitor, ts.isExpression));
84551                             ts.setTextRange(assignment, decl);
84552                         }
84553                         assignments = ts.append(assignments, assignment);
84554                     }
84555                 }
84556                 if (assignments) {
84557                     updated = ts.setTextRange(ts.createExpressionStatement(ts.inlineExpressions(assignments)), node);
84558                 }
84559                 else {
84560                     // none of declarations has initializer - the entire variable statement can be deleted
84561                     updated = undefined;
84562                 }
84563             }
84564             else {
84565                 updated = ts.visitEachChild(node, visitor, context);
84566             }
84567             exitSubtree(ancestorFacts, 0 /* None */, 0 /* None */);
84568             return updated;
84569         }
84570         /**
84571          * Visits a VariableDeclarationList that is block scoped (e.g. `let` or `const`).
84572          *
84573          * @param node A VariableDeclarationList node.
84574          */
84575         function visitVariableDeclarationList(node) {
84576             if (node.flags & 3 /* BlockScoped */ || node.transformFlags & 131072 /* ContainsBindingPattern */) {
84577                 if (node.flags & 3 /* BlockScoped */) {
84578                     enableSubstitutionsForBlockScopedBindings();
84579                 }
84580                 var declarations = ts.flatMap(node.declarations, node.flags & 1 /* Let */
84581                     ? visitVariableDeclarationInLetDeclarationList
84582                     : visitVariableDeclaration);
84583                 var declarationList = ts.createVariableDeclarationList(declarations);
84584                 ts.setOriginalNode(declarationList, node);
84585                 ts.setTextRange(declarationList, node);
84586                 ts.setCommentRange(declarationList, node);
84587                 // If the first or last declaration is a binding pattern, we need to modify
84588                 // the source map range for the declaration list.
84589                 if (node.transformFlags & 131072 /* ContainsBindingPattern */
84590                     && (ts.isBindingPattern(node.declarations[0].name) || ts.isBindingPattern(ts.last(node.declarations).name))) {
84591                     ts.setSourceMapRange(declarationList, getRangeUnion(declarations));
84592                 }
84593                 return declarationList;
84594             }
84595             return ts.visitEachChild(node, visitor, context);
84596         }
84597         function getRangeUnion(declarations) {
84598             // declarations may not be sorted by position.
84599             // pos should be the minimum* position over all nodes (that's not -1), end should be the maximum end over all nodes.
84600             var pos = -1, end = -1;
84601             for (var _i = 0, declarations_10 = declarations; _i < declarations_10.length; _i++) {
84602                 var node = declarations_10[_i];
84603                 pos = pos === -1 ? node.pos : node.pos === -1 ? pos : Math.min(pos, node.pos);
84604                 end = Math.max(end, node.end);
84605             }
84606             return ts.createRange(pos, end);
84607         }
84608         /**
84609          * Gets a value indicating whether we should emit an explicit initializer for a variable
84610          * declaration in a `let` declaration list.
84611          *
84612          * @param node A VariableDeclaration node.
84613          */
84614         function shouldEmitExplicitInitializerForLetDeclaration(node) {
84615             // Nested let bindings might need to be initialized explicitly to preserve
84616             // ES6 semantic:
84617             //
84618             //  { let x = 1; }
84619             //  { let x; } // x here should be undefined. not 1
84620             //
84621             // Top level bindings never collide with anything and thus don't require
84622             // explicit initialization. As for nested let bindings there are two cases:
84623             //
84624             // - Nested let bindings that were not renamed definitely should be
84625             //   initialized explicitly:
84626             //
84627             //    { let x = 1; }
84628             //    { let x; if (some-condition) { x = 1}; if (x) { /*1*/ } }
84629             //
84630             //   Without explicit initialization code in /*1*/ can be executed even if
84631             //   some-condition is evaluated to false.
84632             //
84633             // - Renaming introduces fresh name that should not collide with any
84634             //   existing names, however renamed bindings sometimes also should be
84635             //   explicitly initialized. One particular case: non-captured binding
84636             //   declared inside loop body (but not in loop initializer):
84637             //
84638             //    let x;
84639             //    for (;;) {
84640             //        let x;
84641             //    }
84642             //
84643             //   In downlevel codegen inner 'x' will be renamed so it won't collide
84644             //   with outer 'x' however it will should be reset on every iteration as
84645             //   if it was declared anew.
84646             //
84647             //   * Why non-captured binding?
84648             //     - Because if loop contains block scoped binding captured in some
84649             //       function then loop body will be rewritten to have a fresh scope
84650             //       on every iteration so everything will just work.
84651             //
84652             //   * Why loop initializer is excluded?
84653             //     - Since we've introduced a fresh name it already will be undefined.
84654             var flags = resolver.getNodeCheckFlags(node);
84655             var isCapturedInFunction = flags & 262144 /* CapturedBlockScopedBinding */;
84656             var isDeclaredInLoop = flags & 524288 /* BlockScopedBindingInLoop */;
84657             var emittedAsTopLevel = (hierarchyFacts & 64 /* TopLevel */) !== 0
84658                 || (isCapturedInFunction
84659                     && isDeclaredInLoop
84660                     && (hierarchyFacts & 512 /* IterationStatementBlock */) !== 0);
84661             var emitExplicitInitializer = !emittedAsTopLevel
84662                 && (hierarchyFacts & 4096 /* ForInOrForOfStatement */) === 0
84663                 && (!resolver.isDeclarationWithCollidingName(node)
84664                     || (isDeclaredInLoop
84665                         && !isCapturedInFunction
84666                         && (hierarchyFacts & (2048 /* ForStatement */ | 4096 /* ForInOrForOfStatement */)) === 0));
84667             return emitExplicitInitializer;
84668         }
84669         /**
84670          * Visits a VariableDeclaration in a `let` declaration list.
84671          *
84672          * @param node A VariableDeclaration node.
84673          */
84674         function visitVariableDeclarationInLetDeclarationList(node) {
84675             // For binding pattern names that lack initializers there is no point to emit
84676             // explicit initializer since downlevel codegen for destructuring will fail
84677             // in the absence of initializer so all binding elements will say uninitialized
84678             var name = node.name;
84679             if (ts.isBindingPattern(name)) {
84680                 return visitVariableDeclaration(node);
84681             }
84682             if (!node.initializer && shouldEmitExplicitInitializerForLetDeclaration(node)) {
84683                 var clone_3 = ts.getMutableClone(node);
84684                 clone_3.initializer = ts.createVoidZero();
84685                 return clone_3;
84686             }
84687             return ts.visitEachChild(node, visitor, context);
84688         }
84689         /**
84690          * Visits a VariableDeclaration node with a binding pattern.
84691          *
84692          * @param node A VariableDeclaration node.
84693          */
84694         function visitVariableDeclaration(node) {
84695             var ancestorFacts = enterSubtree(32 /* ExportedVariableStatement */, 0 /* None */);
84696             var updated;
84697             if (ts.isBindingPattern(node.name)) {
84698                 updated = ts.flattenDestructuringBinding(node, visitor, context, 0 /* All */, 
84699                 /*value*/ undefined, (ancestorFacts & 32 /* ExportedVariableStatement */) !== 0);
84700             }
84701             else {
84702                 updated = ts.visitEachChild(node, visitor, context);
84703             }
84704             exitSubtree(ancestorFacts, 0 /* None */, 0 /* None */);
84705             return updated;
84706         }
84707         function recordLabel(node) {
84708             convertedLoopState.labels.set(ts.idText(node.label), true);
84709         }
84710         function resetLabel(node) {
84711             convertedLoopState.labels.set(ts.idText(node.label), false);
84712         }
84713         function visitLabeledStatement(node) {
84714             if (convertedLoopState && !convertedLoopState.labels) {
84715                 convertedLoopState.labels = ts.createMap();
84716             }
84717             var statement = ts.unwrapInnermostStatementOfLabel(node, convertedLoopState && recordLabel);
84718             return ts.isIterationStatement(statement, /*lookInLabeledStatements*/ false)
84719                 ? visitIterationStatement(statement, /*outermostLabeledStatement*/ node)
84720                 : ts.restoreEnclosingLabel(ts.visitNode(statement, visitor, ts.isStatement, ts.liftToBlock), node, convertedLoopState && resetLabel);
84721         }
84722         function visitIterationStatement(node, outermostLabeledStatement) {
84723             switch (node.kind) {
84724                 case 228 /* DoStatement */:
84725                 case 229 /* WhileStatement */:
84726                     return visitDoOrWhileStatement(node, outermostLabeledStatement);
84727                 case 230 /* ForStatement */:
84728                     return visitForStatement(node, outermostLabeledStatement);
84729                 case 231 /* ForInStatement */:
84730                     return visitForInStatement(node, outermostLabeledStatement);
84731                 case 232 /* ForOfStatement */:
84732                     return visitForOfStatement(node, outermostLabeledStatement);
84733             }
84734         }
84735         function visitIterationStatementWithFacts(excludeFacts, includeFacts, node, outermostLabeledStatement, convert) {
84736             var ancestorFacts = enterSubtree(excludeFacts, includeFacts);
84737             var updated = convertIterationStatementBodyIfNecessary(node, outermostLabeledStatement, ancestorFacts, convert);
84738             exitSubtree(ancestorFacts, 0 /* None */, 0 /* None */);
84739             return updated;
84740         }
84741         function visitDoOrWhileStatement(node, outermostLabeledStatement) {
84742             return visitIterationStatementWithFacts(0 /* DoOrWhileStatementExcludes */, 1280 /* DoOrWhileStatementIncludes */, node, outermostLabeledStatement);
84743         }
84744         function visitForStatement(node, outermostLabeledStatement) {
84745             return visitIterationStatementWithFacts(5056 /* ForStatementExcludes */, 3328 /* ForStatementIncludes */, node, outermostLabeledStatement);
84746         }
84747         function visitForInStatement(node, outermostLabeledStatement) {
84748             return visitIterationStatementWithFacts(3008 /* ForInOrForOfStatementExcludes */, 5376 /* ForInOrForOfStatementIncludes */, node, outermostLabeledStatement);
84749         }
84750         function visitForOfStatement(node, outermostLabeledStatement) {
84751             return visitIterationStatementWithFacts(3008 /* ForInOrForOfStatementExcludes */, 5376 /* ForInOrForOfStatementIncludes */, node, outermostLabeledStatement, compilerOptions.downlevelIteration ? convertForOfStatementForIterable : convertForOfStatementForArray);
84752         }
84753         function convertForOfStatementHead(node, boundValue, convertedLoopBodyStatements) {
84754             var statements = [];
84755             var initializer = node.initializer;
84756             if (ts.isVariableDeclarationList(initializer)) {
84757                 if (node.initializer.flags & 3 /* BlockScoped */) {
84758                     enableSubstitutionsForBlockScopedBindings();
84759                 }
84760                 var firstOriginalDeclaration = ts.firstOrUndefined(initializer.declarations);
84761                 if (firstOriginalDeclaration && ts.isBindingPattern(firstOriginalDeclaration.name)) {
84762                     // This works whether the declaration is a var, let, or const.
84763                     // It will use rhsIterationValue _a[_i] as the initializer.
84764                     var declarations = ts.flattenDestructuringBinding(firstOriginalDeclaration, visitor, context, 0 /* All */, boundValue);
84765                     var declarationList = ts.setTextRange(ts.createVariableDeclarationList(declarations), node.initializer);
84766                     ts.setOriginalNode(declarationList, node.initializer);
84767                     // Adjust the source map range for the first declaration to align with the old
84768                     // emitter.
84769                     ts.setSourceMapRange(declarationList, ts.createRange(declarations[0].pos, ts.last(declarations).end));
84770                     statements.push(ts.createVariableStatement(
84771                     /*modifiers*/ undefined, declarationList));
84772                 }
84773                 else {
84774                     // The following call does not include the initializer, so we have
84775                     // to emit it separately.
84776                     statements.push(ts.setTextRange(ts.createVariableStatement(
84777                     /*modifiers*/ undefined, ts.setOriginalNode(ts.setTextRange(ts.createVariableDeclarationList([
84778                         ts.createVariableDeclaration(firstOriginalDeclaration ? firstOriginalDeclaration.name : ts.createTempVariable(/*recordTempVariable*/ undefined), 
84779                         /*type*/ undefined, boundValue)
84780                     ]), ts.moveRangePos(initializer, -1)), initializer)), ts.moveRangeEnd(initializer, -1)));
84781                 }
84782             }
84783             else {
84784                 // Initializer is an expression. Emit the expression in the body, so that it's
84785                 // evaluated on every iteration.
84786                 var assignment = ts.createAssignment(initializer, boundValue);
84787                 if (ts.isDestructuringAssignment(assignment)) {
84788                     ts.aggregateTransformFlags(assignment);
84789                     statements.push(ts.createExpressionStatement(visitBinaryExpression(assignment, /*needsDestructuringValue*/ false)));
84790                 }
84791                 else {
84792                     assignment.end = initializer.end;
84793                     statements.push(ts.setTextRange(ts.createExpressionStatement(ts.visitNode(assignment, visitor, ts.isExpression)), ts.moveRangeEnd(initializer, -1)));
84794                 }
84795             }
84796             if (convertedLoopBodyStatements) {
84797                 return createSyntheticBlockForConvertedStatements(ts.addRange(statements, convertedLoopBodyStatements));
84798             }
84799             else {
84800                 var statement = ts.visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock);
84801                 if (ts.isBlock(statement)) {
84802                     return ts.updateBlock(statement, ts.setTextRange(ts.createNodeArray(ts.concatenate(statements, statement.statements)), statement.statements));
84803                 }
84804                 else {
84805                     statements.push(statement);
84806                     return createSyntheticBlockForConvertedStatements(statements);
84807                 }
84808             }
84809         }
84810         function createSyntheticBlockForConvertedStatements(statements) {
84811             return ts.setEmitFlags(ts.createBlock(ts.createNodeArray(statements), 
84812             /*multiLine*/ true), 48 /* NoSourceMap */ | 384 /* NoTokenSourceMaps */);
84813         }
84814         function convertForOfStatementForArray(node, outermostLabeledStatement, convertedLoopBodyStatements) {
84815             // The following ES6 code:
84816             //
84817             //    for (let v of expr) { }
84818             //
84819             // should be emitted as
84820             //
84821             //    for (var _i = 0, _a = expr; _i < _a.length; _i++) {
84822             //        var v = _a[_i];
84823             //    }
84824             //
84825             // where _a and _i are temps emitted to capture the RHS and the counter,
84826             // respectively.
84827             // When the left hand side is an expression instead of a let declaration,
84828             // the "let v" is not emitted.
84829             // When the left hand side is a let/const, the v is renamed if there is
84830             // another v in scope.
84831             // Note that all assignments to the LHS are emitted in the body, including
84832             // all destructuring.
84833             // Note also that because an extra statement is needed to assign to the LHS,
84834             // for-of bodies are always emitted as blocks.
84835             var expression = ts.visitNode(node.expression, visitor, ts.isExpression);
84836             // In the case where the user wrote an identifier as the RHS, like this:
84837             //
84838             //     for (let v of arr) { }
84839             //
84840             // we don't want to emit a temporary variable for the RHS, just use it directly.
84841             var counter = ts.createLoopVariable();
84842             var rhsReference = ts.isIdentifier(expression) ? ts.getGeneratedNameForNode(expression) : ts.createTempVariable(/*recordTempVariable*/ undefined);
84843             // The old emitter does not emit source maps for the expression
84844             ts.setEmitFlags(expression, 48 /* NoSourceMap */ | ts.getEmitFlags(expression));
84845             var forStatement = ts.setTextRange(ts.createFor(
84846             /*initializer*/ ts.setEmitFlags(ts.setTextRange(ts.createVariableDeclarationList([
84847                 ts.setTextRange(ts.createVariableDeclaration(counter, /*type*/ undefined, ts.createLiteral(0)), ts.moveRangePos(node.expression, -1)),
84848                 ts.setTextRange(ts.createVariableDeclaration(rhsReference, /*type*/ undefined, expression), node.expression)
84849             ]), node.expression), 2097152 /* NoHoisting */), 
84850             /*condition*/ ts.setTextRange(ts.createLessThan(counter, ts.createPropertyAccess(rhsReference, "length")), node.expression), 
84851             /*incrementor*/ ts.setTextRange(ts.createPostfixIncrement(counter), node.expression), 
84852             /*statement*/ convertForOfStatementHead(node, ts.createElementAccess(rhsReference, counter), convertedLoopBodyStatements)), 
84853             /*location*/ node);
84854             // Disable trailing source maps for the OpenParenToken to align source map emit with the old emitter.
84855             ts.setEmitFlags(forStatement, 256 /* NoTokenTrailingSourceMaps */);
84856             ts.setTextRange(forStatement, node);
84857             return ts.restoreEnclosingLabel(forStatement, outermostLabeledStatement, convertedLoopState && resetLabel);
84858         }
84859         function convertForOfStatementForIterable(node, outermostLabeledStatement, convertedLoopBodyStatements, ancestorFacts) {
84860             var expression = ts.visitNode(node.expression, visitor, ts.isExpression);
84861             var iterator = ts.isIdentifier(expression) ? ts.getGeneratedNameForNode(expression) : ts.createTempVariable(/*recordTempVariable*/ undefined);
84862             var result = ts.isIdentifier(expression) ? ts.getGeneratedNameForNode(iterator) : ts.createTempVariable(/*recordTempVariable*/ undefined);
84863             var errorRecord = ts.createUniqueName("e");
84864             var catchVariable = ts.getGeneratedNameForNode(errorRecord);
84865             var returnMethod = ts.createTempVariable(/*recordTempVariable*/ undefined);
84866             var values = ts.createValuesHelper(context, expression, node.expression);
84867             var next = ts.createCall(ts.createPropertyAccess(iterator, "next"), /*typeArguments*/ undefined, []);
84868             hoistVariableDeclaration(errorRecord);
84869             hoistVariableDeclaration(returnMethod);
84870             // if we are enclosed in an outer loop ensure we reset 'errorRecord' per each iteration
84871             var initializer = ancestorFacts & 1024 /* IterationContainer */
84872                 ? ts.inlineExpressions([ts.createAssignment(errorRecord, ts.createVoidZero()), values])
84873                 : values;
84874             var forStatement = ts.setEmitFlags(ts.setTextRange(ts.createFor(
84875             /*initializer*/ ts.setEmitFlags(ts.setTextRange(ts.createVariableDeclarationList([
84876                 ts.setTextRange(ts.createVariableDeclaration(iterator, /*type*/ undefined, initializer), node.expression),
84877                 ts.createVariableDeclaration(result, /*type*/ undefined, next)
84878             ]), node.expression), 2097152 /* NoHoisting */), 
84879             /*condition*/ ts.createLogicalNot(ts.createPropertyAccess(result, "done")), 
84880             /*incrementor*/ ts.createAssignment(result, next), 
84881             /*statement*/ convertForOfStatementHead(node, ts.createPropertyAccess(result, "value"), convertedLoopBodyStatements)), 
84882             /*location*/ node), 256 /* NoTokenTrailingSourceMaps */);
84883             return ts.createTry(ts.createBlock([
84884                 ts.restoreEnclosingLabel(forStatement, outermostLabeledStatement, convertedLoopState && resetLabel)
84885             ]), ts.createCatchClause(ts.createVariableDeclaration(catchVariable), ts.setEmitFlags(ts.createBlock([
84886                 ts.createExpressionStatement(ts.createAssignment(errorRecord, ts.createObjectLiteral([
84887                     ts.createPropertyAssignment("error", catchVariable)
84888                 ])))
84889             ]), 1 /* SingleLine */)), ts.createBlock([
84890                 ts.createTry(
84891                 /*tryBlock*/ ts.createBlock([
84892                     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 */),
84893                 ]), 
84894                 /*catchClause*/ undefined, 
84895                 /*finallyBlock*/ ts.setEmitFlags(ts.createBlock([
84896                     ts.setEmitFlags(ts.createIf(errorRecord, ts.createThrow(ts.createPropertyAccess(errorRecord, "error"))), 1 /* SingleLine */)
84897                 ]), 1 /* SingleLine */))
84898             ]));
84899         }
84900         /**
84901          * Visits an ObjectLiteralExpression with computed property names.
84902          *
84903          * @param node An ObjectLiteralExpression node.
84904          */
84905         function visitObjectLiteralExpression(node) {
84906             // We are here because a ComputedPropertyName was used somewhere in the expression.
84907             var properties = node.properties;
84908             var numProperties = properties.length;
84909             // Find the first computed property.
84910             // Everything until that point can be emitted as part of the initial object literal.
84911             var numInitialProperties = numProperties;
84912             var numInitialPropertiesWithoutYield = numProperties;
84913             for (var i = 0; i < numProperties; i++) {
84914                 var property = properties[i];
84915                 if ((property.transformFlags & 262144 /* ContainsYield */ && hierarchyFacts & 4 /* AsyncFunctionBody */)
84916                     && i < numInitialPropertiesWithoutYield) {
84917                     numInitialPropertiesWithoutYield = i;
84918                 }
84919                 if (property.name.kind === 154 /* ComputedPropertyName */) {
84920                     numInitialProperties = i;
84921                     break;
84922                 }
84923             }
84924             if (numInitialProperties !== numProperties) {
84925                 if (numInitialPropertiesWithoutYield < numInitialProperties) {
84926                     numInitialProperties = numInitialPropertiesWithoutYield;
84927                 }
84928                 // For computed properties, we need to create a unique handle to the object
84929                 // literal so we can modify it without risking internal assignments tainting the object.
84930                 var temp = ts.createTempVariable(hoistVariableDeclaration);
84931                 // Write out the first non-computed properties, then emit the rest through indexing on the temp variable.
84932                 var expressions = [];
84933                 var assignment = ts.createAssignment(temp, ts.setEmitFlags(ts.createObjectLiteral(ts.visitNodes(properties, visitor, ts.isObjectLiteralElementLike, 0, numInitialProperties), node.multiLine), 65536 /* Indented */));
84934                 if (node.multiLine) {
84935                     ts.startOnNewLine(assignment);
84936                 }
84937                 expressions.push(assignment);
84938                 addObjectLiteralMembers(expressions, node, temp, numInitialProperties);
84939                 // We need to clone the temporary identifier so that we can write it on a
84940                 // new line
84941                 expressions.push(node.multiLine ? ts.startOnNewLine(ts.getMutableClone(temp)) : temp);
84942                 return ts.inlineExpressions(expressions);
84943             }
84944             return ts.visitEachChild(node, visitor, context);
84945         }
84946         function shouldConvertPartOfIterationStatement(node) {
84947             return (resolver.getNodeCheckFlags(node) & 131072 /* ContainsCapturedBlockScopeBinding */) !== 0;
84948         }
84949         function shouldConvertInitializerOfForStatement(node) {
84950             return ts.isForStatement(node) && !!node.initializer && shouldConvertPartOfIterationStatement(node.initializer);
84951         }
84952         function shouldConvertConditionOfForStatement(node) {
84953             return ts.isForStatement(node) && !!node.condition && shouldConvertPartOfIterationStatement(node.condition);
84954         }
84955         function shouldConvertIncrementorOfForStatement(node) {
84956             return ts.isForStatement(node) && !!node.incrementor && shouldConvertPartOfIterationStatement(node.incrementor);
84957         }
84958         function shouldConvertIterationStatement(node) {
84959             return shouldConvertBodyOfIterationStatement(node)
84960                 || shouldConvertInitializerOfForStatement(node);
84961         }
84962         function shouldConvertBodyOfIterationStatement(node) {
84963             return (resolver.getNodeCheckFlags(node) & 65536 /* LoopWithCapturedBlockScopedBinding */) !== 0;
84964         }
84965         /**
84966          * Records constituents of name for the given variable to be hoisted in the outer scope.
84967          */
84968         function hoistVariableDeclarationDeclaredInConvertedLoop(state, node) {
84969             if (!state.hoistedLocalVariables) {
84970                 state.hoistedLocalVariables = [];
84971             }
84972             visit(node.name);
84973             function visit(node) {
84974                 if (node.kind === 75 /* Identifier */) {
84975                     state.hoistedLocalVariables.push(node);
84976                 }
84977                 else {
84978                     for (var _i = 0, _a = node.elements; _i < _a.length; _i++) {
84979                         var element = _a[_i];
84980                         if (!ts.isOmittedExpression(element)) {
84981                             visit(element.name);
84982                         }
84983                     }
84984                 }
84985             }
84986         }
84987         function convertIterationStatementBodyIfNecessary(node, outermostLabeledStatement, ancestorFacts, convert) {
84988             if (!shouldConvertIterationStatement(node)) {
84989                 var saveAllowedNonLabeledJumps = void 0;
84990                 if (convertedLoopState) {
84991                     // we get here if we are trying to emit normal loop loop inside converted loop
84992                     // set allowedNonLabeledJumps to Break | Continue to mark that break\continue inside the loop should be emitted as is
84993                     saveAllowedNonLabeledJumps = convertedLoopState.allowedNonLabeledJumps;
84994                     convertedLoopState.allowedNonLabeledJumps = 2 /* Break */ | 4 /* Continue */;
84995                 }
84996                 var result = convert
84997                     ? convert(node, outermostLabeledStatement, /*convertedLoopBodyStatements*/ undefined, ancestorFacts)
84998                     : ts.restoreEnclosingLabel(ts.visitEachChild(node, visitor, context), outermostLabeledStatement, convertedLoopState && resetLabel);
84999                 if (convertedLoopState) {
85000                     convertedLoopState.allowedNonLabeledJumps = saveAllowedNonLabeledJumps;
85001                 }
85002                 return result;
85003             }
85004             var currentState = createConvertedLoopState(node);
85005             var statements = [];
85006             var outerConvertedLoopState = convertedLoopState;
85007             convertedLoopState = currentState;
85008             var initializerFunction = shouldConvertInitializerOfForStatement(node) ? createFunctionForInitializerOfForStatement(node, currentState) : undefined;
85009             var bodyFunction = shouldConvertBodyOfIterationStatement(node) ? createFunctionForBodyOfIterationStatement(node, currentState, outerConvertedLoopState) : undefined;
85010             convertedLoopState = outerConvertedLoopState;
85011             if (initializerFunction)
85012                 statements.push(initializerFunction.functionDeclaration);
85013             if (bodyFunction)
85014                 statements.push(bodyFunction.functionDeclaration);
85015             addExtraDeclarationsForConvertedLoop(statements, currentState, outerConvertedLoopState);
85016             if (initializerFunction) {
85017                 statements.push(generateCallToConvertedLoopInitializer(initializerFunction.functionName, initializerFunction.containsYield));
85018             }
85019             var loop;
85020             if (bodyFunction) {
85021                 if (convert) {
85022                     loop = convert(node, outermostLabeledStatement, bodyFunction.part, ancestorFacts);
85023                 }
85024                 else {
85025                     var clone_4 = convertIterationStatementCore(node, initializerFunction, ts.createBlock(bodyFunction.part, /*multiLine*/ true));
85026                     ts.aggregateTransformFlags(clone_4);
85027                     loop = ts.restoreEnclosingLabel(clone_4, outermostLabeledStatement, convertedLoopState && resetLabel);
85028                 }
85029             }
85030             else {
85031                 var clone_5 = convertIterationStatementCore(node, initializerFunction, ts.visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock));
85032                 ts.aggregateTransformFlags(clone_5);
85033                 loop = ts.restoreEnclosingLabel(clone_5, outermostLabeledStatement, convertedLoopState && resetLabel);
85034             }
85035             statements.push(loop);
85036             return statements;
85037         }
85038         function convertIterationStatementCore(node, initializerFunction, convertedLoopBody) {
85039             switch (node.kind) {
85040                 case 230 /* ForStatement */: return convertForStatement(node, initializerFunction, convertedLoopBody);
85041                 case 231 /* ForInStatement */: return convertForInStatement(node, convertedLoopBody);
85042                 case 232 /* ForOfStatement */: return convertForOfStatement(node, convertedLoopBody);
85043                 case 228 /* DoStatement */: return convertDoStatement(node, convertedLoopBody);
85044                 case 229 /* WhileStatement */: return convertWhileStatement(node, convertedLoopBody);
85045                 default: return ts.Debug.failBadSyntaxKind(node, "IterationStatement expected");
85046             }
85047         }
85048         function convertForStatement(node, initializerFunction, convertedLoopBody) {
85049             var shouldConvertCondition = node.condition && shouldConvertPartOfIterationStatement(node.condition);
85050             var shouldConvertIncrementor = shouldConvertCondition || node.incrementor && shouldConvertPartOfIterationStatement(node.incrementor);
85051             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);
85052         }
85053         function convertForOfStatement(node, convertedLoopBody) {
85054             return ts.updateForOf(node, 
85055             /*awaitModifier*/ undefined, ts.visitNode(node.initializer, visitor, ts.isForInitializer), ts.visitNode(node.expression, visitor, ts.isExpression), convertedLoopBody);
85056         }
85057         function convertForInStatement(node, convertedLoopBody) {
85058             return ts.updateForIn(node, ts.visitNode(node.initializer, visitor, ts.isForInitializer), ts.visitNode(node.expression, visitor, ts.isExpression), convertedLoopBody);
85059         }
85060         function convertDoStatement(node, convertedLoopBody) {
85061             return ts.updateDo(node, convertedLoopBody, ts.visitNode(node.expression, visitor, ts.isExpression));
85062         }
85063         function convertWhileStatement(node, convertedLoopBody) {
85064             return ts.updateWhile(node, ts.visitNode(node.expression, visitor, ts.isExpression), convertedLoopBody);
85065         }
85066         function createConvertedLoopState(node) {
85067             var loopInitializer;
85068             switch (node.kind) {
85069                 case 230 /* ForStatement */:
85070                 case 231 /* ForInStatement */:
85071                 case 232 /* ForOfStatement */:
85072                     var initializer = node.initializer;
85073                     if (initializer && initializer.kind === 243 /* VariableDeclarationList */) {
85074                         loopInitializer = initializer;
85075                     }
85076                     break;
85077             }
85078             // variables that will be passed to the loop as parameters
85079             var loopParameters = [];
85080             // variables declared in the loop initializer that will be changed inside the loop
85081             var loopOutParameters = [];
85082             if (loopInitializer && (ts.getCombinedNodeFlags(loopInitializer) & 3 /* BlockScoped */)) {
85083                 var hasCapturedBindingsInForInitializer = shouldConvertInitializerOfForStatement(node);
85084                 for (var _i = 0, _a = loopInitializer.declarations; _i < _a.length; _i++) {
85085                     var decl = _a[_i];
85086                     processLoopVariableDeclaration(node, decl, loopParameters, loopOutParameters, hasCapturedBindingsInForInitializer);
85087                 }
85088             }
85089             var currentState = { loopParameters: loopParameters, loopOutParameters: loopOutParameters };
85090             if (convertedLoopState) {
85091                 // convertedOuterLoopState !== undefined means that this converted loop is nested in another converted loop.
85092                 // if outer converted loop has already accumulated some state - pass it through
85093                 if (convertedLoopState.argumentsName) {
85094                     // outer loop has already used 'arguments' so we've already have some name to alias it
85095                     // use the same name in all nested loops
85096                     currentState.argumentsName = convertedLoopState.argumentsName;
85097                 }
85098                 if (convertedLoopState.thisName) {
85099                     // outer loop has already used 'this' so we've already have some name to alias it
85100                     // use the same name in all nested loops
85101                     currentState.thisName = convertedLoopState.thisName;
85102                 }
85103                 if (convertedLoopState.hoistedLocalVariables) {
85104                     // we've already collected some non-block scoped variable declarations in enclosing loop
85105                     // use the same storage in nested loop
85106                     currentState.hoistedLocalVariables = convertedLoopState.hoistedLocalVariables;
85107                 }
85108             }
85109             return currentState;
85110         }
85111         function addExtraDeclarationsForConvertedLoop(statements, state, outerState) {
85112             var extraVariableDeclarations;
85113             // propagate state from the inner loop to the outer loop if necessary
85114             if (state.argumentsName) {
85115                 // if alias for arguments is set
85116                 if (outerState) {
85117                     // pass it to outer converted loop
85118                     outerState.argumentsName = state.argumentsName;
85119                 }
85120                 else {
85121                     // this is top level converted loop and we need to create an alias for 'arguments' object
85122                     (extraVariableDeclarations || (extraVariableDeclarations = [])).push(ts.createVariableDeclaration(state.argumentsName, 
85123                     /*type*/ undefined, ts.createIdentifier("arguments")));
85124                 }
85125             }
85126             if (state.thisName) {
85127                 // if alias for this is set
85128                 if (outerState) {
85129                     // pass it to outer converted loop
85130                     outerState.thisName = state.thisName;
85131                 }
85132                 else {
85133                     // this is top level converted loop so we need to create an alias for 'this' here
85134                     // NOTE:
85135                     // if converted loops were all nested in arrow function then we'll always emit '_this' so convertedLoopState.thisName will not be set.
85136                     // If it is set this means that all nested loops are not nested in arrow function and it is safe to capture 'this'.
85137                     (extraVariableDeclarations || (extraVariableDeclarations = [])).push(ts.createVariableDeclaration(state.thisName, 
85138                     /*type*/ undefined, ts.createIdentifier("this")));
85139                 }
85140             }
85141             if (state.hoistedLocalVariables) {
85142                 // if hoistedLocalVariables !== undefined this means that we've possibly collected some variable declarations to be hoisted later
85143                 if (outerState) {
85144                     // pass them to outer converted loop
85145                     outerState.hoistedLocalVariables = state.hoistedLocalVariables;
85146                 }
85147                 else {
85148                     if (!extraVariableDeclarations) {
85149                         extraVariableDeclarations = [];
85150                     }
85151                     // hoist collected variable declarations
85152                     for (var _i = 0, _a = state.hoistedLocalVariables; _i < _a.length; _i++) {
85153                         var identifier = _a[_i];
85154                         extraVariableDeclarations.push(ts.createVariableDeclaration(identifier));
85155                     }
85156                 }
85157             }
85158             // add extra variables to hold out parameters if necessary
85159             if (state.loopOutParameters.length) {
85160                 if (!extraVariableDeclarations) {
85161                     extraVariableDeclarations = [];
85162                 }
85163                 for (var _b = 0, _c = state.loopOutParameters; _b < _c.length; _b++) {
85164                     var outParam = _c[_b];
85165                     extraVariableDeclarations.push(ts.createVariableDeclaration(outParam.outParamName));
85166                 }
85167             }
85168             if (state.conditionVariable) {
85169                 if (!extraVariableDeclarations) {
85170                     extraVariableDeclarations = [];
85171                 }
85172                 extraVariableDeclarations.push(ts.createVariableDeclaration(state.conditionVariable, /*type*/ undefined, ts.createFalse()));
85173             }
85174             // create variable statement to hold all introduced variable declarations
85175             if (extraVariableDeclarations) {
85176                 statements.push(ts.createVariableStatement(
85177                 /*modifiers*/ undefined, ts.createVariableDeclarationList(extraVariableDeclarations)));
85178             }
85179         }
85180         function createOutVariable(p) {
85181             return ts.createVariableDeclaration(p.originalName, /*type*/ undefined, p.outParamName);
85182         }
85183         /**
85184          * Creates a `_loop_init` function for a `ForStatement` with a block-scoped initializer
85185          * that is captured in a closure inside of the initializer. The `_loop_init` function is
85186          * used to preserve the per-iteration environment semantics of
85187          * [13.7.4.8 RS: ForBodyEvaluation](https://tc39.github.io/ecma262/#sec-forbodyevaluation).
85188          */
85189         function createFunctionForInitializerOfForStatement(node, currentState) {
85190             var functionName = ts.createUniqueName("_loop_init");
85191             var containsYield = (node.initializer.transformFlags & 262144 /* ContainsYield */) !== 0;
85192             var emitFlags = 0 /* None */;
85193             if (currentState.containsLexicalThis)
85194                 emitFlags |= 8 /* CapturesThis */;
85195             if (containsYield && hierarchyFacts & 4 /* AsyncFunctionBody */)
85196                 emitFlags |= 262144 /* AsyncFunctionBody */;
85197             var statements = [];
85198             statements.push(ts.createVariableStatement(/*modifiers*/ undefined, node.initializer));
85199             copyOutParameters(currentState.loopOutParameters, 2 /* Initializer */, 1 /* ToOutParameter */, statements);
85200             // This transforms the following ES2015 syntax:
85201             //
85202             //  for (let i = (setImmediate(() => console.log(i)), 0); i < 2; i++) {
85203             //      // loop body
85204             //  }
85205             //
85206             // Into the following ES5 syntax:
85207             //
85208             //  var _loop_init_1 = function () {
85209             //      var i = (setImmediate(() => console.log(i)), 0);
85210             //      out_i_1 = i;
85211             //  };
85212             //  var out_i_1;
85213             //  _loop_init_1();
85214             //  for (var i = out_i_1; i < 2; i++) {
85215             //      // loop body
85216             //  }
85217             //
85218             // Which prevents mutations to `i` in the per-iteration environment of the body
85219             // from affecting the initial value for `i` outside of the per-iteration environment.
85220             var functionDeclaration = ts.createVariableStatement(
85221             /*modifiers*/ undefined, ts.setEmitFlags(ts.createVariableDeclarationList([
85222                 ts.createVariableDeclaration(functionName, 
85223                 /*type*/ undefined, ts.setEmitFlags(ts.createFunctionExpression(
85224                 /*modifiers*/ undefined, containsYield ? ts.createToken(41 /* AsteriskToken */) : undefined, 
85225                 /*name*/ undefined, 
85226                 /*typeParameters*/ undefined, 
85227                 /*parameters*/ undefined, 
85228                 /*type*/ undefined, ts.visitNode(ts.createBlock(statements, /*multiLine*/ true), visitor, ts.isBlock)), emitFlags))
85229             ]), 2097152 /* NoHoisting */));
85230             var part = ts.createVariableDeclarationList(ts.map(currentState.loopOutParameters, createOutVariable));
85231             return { functionName: functionName, containsYield: containsYield, functionDeclaration: functionDeclaration, part: part };
85232         }
85233         /**
85234          * Creates a `_loop` function for an `IterationStatement` with a block-scoped initializer
85235          * that is captured in a closure inside of the loop body. The `_loop` function is used to
85236          * preserve the per-iteration environment semantics of
85237          * [13.7.4.8 RS: ForBodyEvaluation](https://tc39.github.io/ecma262/#sec-forbodyevaluation).
85238          */
85239         function createFunctionForBodyOfIterationStatement(node, currentState, outerState) {
85240             var functionName = ts.createUniqueName("_loop");
85241             startLexicalEnvironment();
85242             var statement = ts.visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock);
85243             var lexicalEnvironment = endLexicalEnvironment();
85244             var statements = [];
85245             if (shouldConvertConditionOfForStatement(node) || shouldConvertIncrementorOfForStatement(node)) {
85246                 // If a block-scoped variable declared in the initializer of `node` is captured in
85247                 // the condition or incrementor, we must move the condition and incrementor into
85248                 // the body of the for loop.
85249                 //
85250                 // This transforms the following ES2015 syntax:
85251                 //
85252                 //  for (let i = 0; setImmediate(() => console.log(i)), i < 2; setImmediate(() => console.log(i)), i++) {
85253                 //      // loop body
85254                 //  }
85255                 //
85256                 // Into the following ES5 syntax:
85257                 //
85258                 //  var _loop_1 = function (i) {
85259                 //      if (inc_1)
85260                 //          setImmediate(() => console.log(i)), i++;
85261                 //      else
85262                 //          inc_1 = true;
85263                 //      if (!(setImmediate(() => console.log(i)), i < 2))
85264                 //          return out_i_1 = i, "break";
85265                 //      // loop body
85266                 //      out_i_1 = i;
85267                 //  }
85268                 //  var out_i_1, inc_1 = false;
85269                 //  for (var i = 0;;) {
85270                 //      var state_1 = _loop_1(i);
85271                 //      i = out_i_1;
85272                 //      if (state_1 === "break")
85273                 //          break;
85274                 //  }
85275                 //
85276                 // Which prevents mutations to `i` in the per-iteration environment of the body
85277                 // from affecting the value of `i` in the previous per-iteration environment.
85278                 //
85279                 // Note that the incrementor of a `for` loop is evaluated in a *new* per-iteration
85280                 // environment that is carried over to the next iteration of the loop. As a result,
85281                 // we must indicate whether this is the first evaluation of the loop body so that
85282                 // we only evaluate the incrementor on subsequent evaluations.
85283                 currentState.conditionVariable = ts.createUniqueName("inc");
85284                 statements.push(ts.createIf(currentState.conditionVariable, ts.createStatement(ts.visitNode(node.incrementor, visitor, ts.isExpression)), ts.createStatement(ts.createAssignment(currentState.conditionVariable, ts.createTrue()))));
85285                 if (shouldConvertConditionOfForStatement(node)) {
85286                     statements.push(ts.createIf(ts.createPrefix(53 /* ExclamationToken */, ts.visitNode(node.condition, visitor, ts.isExpression)), ts.visitNode(ts.createBreak(), visitor, ts.isStatement)));
85287                 }
85288             }
85289             if (ts.isBlock(statement)) {
85290                 ts.addRange(statements, statement.statements);
85291             }
85292             else {
85293                 statements.push(statement);
85294             }
85295             copyOutParameters(currentState.loopOutParameters, 1 /* Body */, 1 /* ToOutParameter */, statements);
85296             ts.insertStatementsAfterStandardPrologue(statements, lexicalEnvironment);
85297             var loopBody = ts.createBlock(statements, /*multiLine*/ true);
85298             if (ts.isBlock(statement))
85299                 ts.setOriginalNode(loopBody, statement);
85300             var containsYield = (node.statement.transformFlags & 262144 /* ContainsYield */) !== 0;
85301             var emitFlags = 0;
85302             if (currentState.containsLexicalThis)
85303                 emitFlags |= 8 /* CapturesThis */;
85304             if (containsYield && (hierarchyFacts & 4 /* AsyncFunctionBody */) !== 0)
85305                 emitFlags |= 262144 /* AsyncFunctionBody */;
85306             // This transforms the following ES2015 syntax (in addition to other variations):
85307             //
85308             //  for (let i = 0; i < 2; i++) {
85309             //      setImmediate(() => console.log(i));
85310             //  }
85311             //
85312             // Into the following ES5 syntax:
85313             //
85314             //  var _loop_1 = function (i) {
85315             //      setImmediate(() => console.log(i));
85316             //  };
85317             //  for (var i = 0; i < 2; i++) {
85318             //      _loop_1(i);
85319             //  }
85320             var functionDeclaration = ts.createVariableStatement(
85321             /*modifiers*/ undefined, ts.setEmitFlags(ts.createVariableDeclarationList([
85322                 ts.createVariableDeclaration(functionName, 
85323                 /*type*/ undefined, ts.setEmitFlags(ts.createFunctionExpression(
85324                 /*modifiers*/ undefined, containsYield ? ts.createToken(41 /* AsteriskToken */) : undefined, 
85325                 /*name*/ undefined, 
85326                 /*typeParameters*/ undefined, currentState.loopParameters, 
85327                 /*type*/ undefined, loopBody), emitFlags))
85328             ]), 2097152 /* NoHoisting */));
85329             var part = generateCallToConvertedLoop(functionName, currentState, outerState, containsYield);
85330             return { functionName: functionName, containsYield: containsYield, functionDeclaration: functionDeclaration, part: part };
85331         }
85332         function copyOutParameter(outParam, copyDirection) {
85333             var source = copyDirection === 0 /* ToOriginal */ ? outParam.outParamName : outParam.originalName;
85334             var target = copyDirection === 0 /* ToOriginal */ ? outParam.originalName : outParam.outParamName;
85335             return ts.createBinary(target, 62 /* EqualsToken */, source);
85336         }
85337         function copyOutParameters(outParams, partFlags, copyDirection, statements) {
85338             for (var _i = 0, outParams_1 = outParams; _i < outParams_1.length; _i++) {
85339                 var outParam = outParams_1[_i];
85340                 if (outParam.flags & partFlags) {
85341                     statements.push(ts.createExpressionStatement(copyOutParameter(outParam, copyDirection)));
85342                 }
85343             }
85344         }
85345         function generateCallToConvertedLoopInitializer(initFunctionExpressionName, containsYield) {
85346             var call = ts.createCall(initFunctionExpressionName, /*typeArguments*/ undefined, []);
85347             var callResult = containsYield
85348                 ? ts.createYield(ts.createToken(41 /* AsteriskToken */), ts.setEmitFlags(call, 8388608 /* Iterator */))
85349                 : call;
85350             return ts.createStatement(callResult);
85351         }
85352         function generateCallToConvertedLoop(loopFunctionExpressionName, state, outerState, containsYield) {
85353             var statements = [];
85354             // loop is considered simple if it does not have any return statements or break\continue that transfer control outside of the loop
85355             // simple loops are emitted as just 'loop()';
85356             // NOTE: if loop uses only 'continue' it still will be emitted as simple loop
85357             var isSimpleLoop = !(state.nonLocalJumps & ~4 /* Continue */) &&
85358                 !state.labeledNonLocalBreaks &&
85359                 !state.labeledNonLocalContinues;
85360             var call = ts.createCall(loopFunctionExpressionName, /*typeArguments*/ undefined, ts.map(state.loopParameters, function (p) { return p.name; }));
85361             var callResult = containsYield
85362                 ? ts.createYield(ts.createToken(41 /* AsteriskToken */), ts.setEmitFlags(call, 8388608 /* Iterator */))
85363                 : call;
85364             if (isSimpleLoop) {
85365                 statements.push(ts.createExpressionStatement(callResult));
85366                 copyOutParameters(state.loopOutParameters, 1 /* Body */, 0 /* ToOriginal */, statements);
85367             }
85368             else {
85369                 var loopResultName = ts.createUniqueName("state");
85370                 var stateVariable = ts.createVariableStatement(
85371                 /*modifiers*/ undefined, ts.createVariableDeclarationList([ts.createVariableDeclaration(loopResultName, /*type*/ undefined, callResult)]));
85372                 statements.push(stateVariable);
85373                 copyOutParameters(state.loopOutParameters, 1 /* Body */, 0 /* ToOriginal */, statements);
85374                 if (state.nonLocalJumps & 8 /* Return */) {
85375                     var returnStatement = void 0;
85376                     if (outerState) {
85377                         outerState.nonLocalJumps |= 8 /* Return */;
85378                         returnStatement = ts.createReturn(loopResultName);
85379                     }
85380                     else {
85381                         returnStatement = ts.createReturn(ts.createPropertyAccess(loopResultName, "value"));
85382                     }
85383                     statements.push(ts.createIf(ts.createBinary(ts.createTypeOf(loopResultName), 36 /* EqualsEqualsEqualsToken */, ts.createLiteral("object")), returnStatement));
85384                 }
85385                 if (state.nonLocalJumps & 2 /* Break */) {
85386                     statements.push(ts.createIf(ts.createBinary(loopResultName, 36 /* EqualsEqualsEqualsToken */, ts.createLiteral("break")), ts.createBreak()));
85387                 }
85388                 if (state.labeledNonLocalBreaks || state.labeledNonLocalContinues) {
85389                     var caseClauses = [];
85390                     processLabeledJumps(state.labeledNonLocalBreaks, /*isBreak*/ true, loopResultName, outerState, caseClauses);
85391                     processLabeledJumps(state.labeledNonLocalContinues, /*isBreak*/ false, loopResultName, outerState, caseClauses);
85392                     statements.push(ts.createSwitch(loopResultName, ts.createCaseBlock(caseClauses)));
85393                 }
85394             }
85395             return statements;
85396         }
85397         function setLabeledJump(state, isBreak, labelText, labelMarker) {
85398             if (isBreak) {
85399                 if (!state.labeledNonLocalBreaks) {
85400                     state.labeledNonLocalBreaks = ts.createMap();
85401                 }
85402                 state.labeledNonLocalBreaks.set(labelText, labelMarker);
85403             }
85404             else {
85405                 if (!state.labeledNonLocalContinues) {
85406                     state.labeledNonLocalContinues = ts.createMap();
85407                 }
85408                 state.labeledNonLocalContinues.set(labelText, labelMarker);
85409             }
85410         }
85411         function processLabeledJumps(table, isBreak, loopResultName, outerLoop, caseClauses) {
85412             if (!table) {
85413                 return;
85414             }
85415             table.forEach(function (labelMarker, labelText) {
85416                 var statements = [];
85417                 // if there are no outer converted loop or outer label in question is located inside outer converted loop
85418                 // then emit labeled break\continue
85419                 // otherwise propagate pair 'label -> marker' to outer converted loop and emit 'return labelMarker' so outer loop can later decide what to do
85420                 if (!outerLoop || (outerLoop.labels && outerLoop.labels.get(labelText))) {
85421                     var label = ts.createIdentifier(labelText);
85422                     statements.push(isBreak ? ts.createBreak(label) : ts.createContinue(label));
85423                 }
85424                 else {
85425                     setLabeledJump(outerLoop, isBreak, labelText, labelMarker);
85426                     statements.push(ts.createReturn(loopResultName));
85427                 }
85428                 caseClauses.push(ts.createCaseClause(ts.createLiteral(labelMarker), statements));
85429             });
85430         }
85431         function processLoopVariableDeclaration(container, decl, loopParameters, loopOutParameters, hasCapturedBindingsInForInitializer) {
85432             var name = decl.name;
85433             if (ts.isBindingPattern(name)) {
85434                 for (var _i = 0, _a = name.elements; _i < _a.length; _i++) {
85435                     var element = _a[_i];
85436                     if (!ts.isOmittedExpression(element)) {
85437                         processLoopVariableDeclaration(container, element, loopParameters, loopOutParameters, hasCapturedBindingsInForInitializer);
85438                     }
85439                 }
85440             }
85441             else {
85442                 loopParameters.push(ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, name));
85443                 var checkFlags = resolver.getNodeCheckFlags(decl);
85444                 if (checkFlags & 4194304 /* NeedsLoopOutParameter */ || hasCapturedBindingsInForInitializer) {
85445                     var outParamName = ts.createUniqueName("out_" + ts.idText(name));
85446                     var flags = 0;
85447                     if (checkFlags & 4194304 /* NeedsLoopOutParameter */) {
85448                         flags |= 1 /* Body */;
85449                     }
85450                     if (ts.isForStatement(container) && container.initializer && resolver.isBindingCapturedByNode(container.initializer, decl)) {
85451                         flags |= 2 /* Initializer */;
85452                     }
85453                     loopOutParameters.push({ flags: flags, originalName: name, outParamName: outParamName });
85454                 }
85455             }
85456         }
85457         /**
85458          * Adds the members of an object literal to an array of expressions.
85459          *
85460          * @param expressions An array of expressions.
85461          * @param node An ObjectLiteralExpression node.
85462          * @param receiver The receiver for members of the ObjectLiteralExpression.
85463          * @param numInitialNonComputedProperties The number of initial properties without
85464          *                                        computed property names.
85465          */
85466         function addObjectLiteralMembers(expressions, node, receiver, start) {
85467             var properties = node.properties;
85468             var numProperties = properties.length;
85469             for (var i = start; i < numProperties; i++) {
85470                 var property = properties[i];
85471                 switch (property.kind) {
85472                     case 163 /* GetAccessor */:
85473                     case 164 /* SetAccessor */:
85474                         var accessors = ts.getAllAccessorDeclarations(node.properties, property);
85475                         if (property === accessors.firstAccessor) {
85476                             expressions.push(transformAccessorsToExpression(receiver, accessors, node, !!node.multiLine));
85477                         }
85478                         break;
85479                     case 161 /* MethodDeclaration */:
85480                         expressions.push(transformObjectLiteralMethodDeclarationToExpression(property, receiver, node, node.multiLine));
85481                         break;
85482                     case 281 /* PropertyAssignment */:
85483                         expressions.push(transformPropertyAssignmentToExpression(property, receiver, node.multiLine));
85484                         break;
85485                     case 282 /* ShorthandPropertyAssignment */:
85486                         expressions.push(transformShorthandPropertyAssignmentToExpression(property, receiver, node.multiLine));
85487                         break;
85488                     default:
85489                         ts.Debug.failBadSyntaxKind(node);
85490                         break;
85491                 }
85492             }
85493         }
85494         /**
85495          * Transforms a PropertyAssignment node into an expression.
85496          *
85497          * @param node The ObjectLiteralExpression that contains the PropertyAssignment.
85498          * @param property The PropertyAssignment node.
85499          * @param receiver The receiver for the assignment.
85500          */
85501         function transformPropertyAssignmentToExpression(property, receiver, startsOnNewLine) {
85502             var expression = ts.createAssignment(ts.createMemberAccessForPropertyName(receiver, ts.visitNode(property.name, visitor, ts.isPropertyName)), ts.visitNode(property.initializer, visitor, ts.isExpression));
85503             ts.setTextRange(expression, property);
85504             if (startsOnNewLine) {
85505                 ts.startOnNewLine(expression);
85506             }
85507             return expression;
85508         }
85509         /**
85510          * Transforms a ShorthandPropertyAssignment node into an expression.
85511          *
85512          * @param node The ObjectLiteralExpression that contains the ShorthandPropertyAssignment.
85513          * @param property The ShorthandPropertyAssignment node.
85514          * @param receiver The receiver for the assignment.
85515          */
85516         function transformShorthandPropertyAssignmentToExpression(property, receiver, startsOnNewLine) {
85517             var expression = ts.createAssignment(ts.createMemberAccessForPropertyName(receiver, ts.visitNode(property.name, visitor, ts.isPropertyName)), ts.getSynthesizedClone(property.name));
85518             ts.setTextRange(expression, property);
85519             if (startsOnNewLine) {
85520                 ts.startOnNewLine(expression);
85521             }
85522             return expression;
85523         }
85524         /**
85525          * Transforms a MethodDeclaration of an ObjectLiteralExpression into an expression.
85526          *
85527          * @param node The ObjectLiteralExpression that contains the MethodDeclaration.
85528          * @param method The MethodDeclaration node.
85529          * @param receiver The receiver for the assignment.
85530          */
85531         function transformObjectLiteralMethodDeclarationToExpression(method, receiver, container, startsOnNewLine) {
85532             var expression = ts.createAssignment(ts.createMemberAccessForPropertyName(receiver, ts.visitNode(method.name, visitor, ts.isPropertyName)), transformFunctionLikeToExpression(method, /*location*/ method, /*name*/ undefined, container));
85533             ts.setTextRange(expression, method);
85534             if (startsOnNewLine) {
85535                 ts.startOnNewLine(expression);
85536             }
85537             return expression;
85538         }
85539         function visitCatchClause(node) {
85540             var ancestorFacts = enterSubtree(7104 /* BlockScopeExcludes */, 0 /* BlockScopeIncludes */);
85541             var updated;
85542             ts.Debug.assert(!!node.variableDeclaration, "Catch clause variable should always be present when downleveling ES2015.");
85543             if (ts.isBindingPattern(node.variableDeclaration.name)) {
85544                 var temp = ts.createTempVariable(/*recordTempVariable*/ undefined);
85545                 var newVariableDeclaration = ts.createVariableDeclaration(temp);
85546                 ts.setTextRange(newVariableDeclaration, node.variableDeclaration);
85547                 var vars = ts.flattenDestructuringBinding(node.variableDeclaration, visitor, context, 0 /* All */, temp);
85548                 var list = ts.createVariableDeclarationList(vars);
85549                 ts.setTextRange(list, node.variableDeclaration);
85550                 var destructure = ts.createVariableStatement(/*modifiers*/ undefined, list);
85551                 updated = ts.updateCatchClause(node, newVariableDeclaration, addStatementToStartOfBlock(node.block, destructure));
85552             }
85553             else {
85554                 updated = ts.visitEachChild(node, visitor, context);
85555             }
85556             exitSubtree(ancestorFacts, 0 /* None */, 0 /* None */);
85557             return updated;
85558         }
85559         function addStatementToStartOfBlock(block, statement) {
85560             var transformedStatements = ts.visitNodes(block.statements, visitor, ts.isStatement);
85561             return ts.updateBlock(block, __spreadArrays([statement], transformedStatements));
85562         }
85563         /**
85564          * Visits a MethodDeclaration of an ObjectLiteralExpression and transforms it into a
85565          * PropertyAssignment.
85566          *
85567          * @param node A MethodDeclaration node.
85568          */
85569         function visitMethodDeclaration(node) {
85570             // We should only get here for methods on an object literal with regular identifier names.
85571             // Methods on classes are handled in visitClassDeclaration/visitClassExpression.
85572             // Methods with computed property names are handled in visitObjectLiteralExpression.
85573             ts.Debug.assert(!ts.isComputedPropertyName(node.name));
85574             var functionExpression = transformFunctionLikeToExpression(node, /*location*/ ts.moveRangePos(node, -1), /*name*/ undefined, /*container*/ undefined);
85575             ts.setEmitFlags(functionExpression, 512 /* NoLeadingComments */ | ts.getEmitFlags(functionExpression));
85576             return ts.setTextRange(ts.createPropertyAssignment(node.name, functionExpression), 
85577             /*location*/ node);
85578         }
85579         /**
85580          * Visits an AccessorDeclaration of an ObjectLiteralExpression.
85581          *
85582          * @param node An AccessorDeclaration node.
85583          */
85584         function visitAccessorDeclaration(node) {
85585             ts.Debug.assert(!ts.isComputedPropertyName(node.name));
85586             var savedConvertedLoopState = convertedLoopState;
85587             convertedLoopState = undefined;
85588             var ancestorFacts = enterSubtree(16286 /* FunctionExcludes */, 65 /* FunctionIncludes */);
85589             var updated;
85590             var parameters = ts.visitParameterList(node.parameters, visitor, context);
85591             var body = transformFunctionBody(node);
85592             if (node.kind === 163 /* GetAccessor */) {
85593                 updated = ts.updateGetAccessor(node, node.decorators, node.modifiers, node.name, parameters, node.type, body);
85594             }
85595             else {
85596                 updated = ts.updateSetAccessor(node, node.decorators, node.modifiers, node.name, parameters, body);
85597             }
85598             exitSubtree(ancestorFacts, 49152 /* FunctionSubtreeExcludes */, 0 /* None */);
85599             convertedLoopState = savedConvertedLoopState;
85600             return updated;
85601         }
85602         /**
85603          * Visits a ShorthandPropertyAssignment and transforms it into a PropertyAssignment.
85604          *
85605          * @param node A ShorthandPropertyAssignment node.
85606          */
85607         function visitShorthandPropertyAssignment(node) {
85608             return ts.setTextRange(ts.createPropertyAssignment(node.name, ts.getSynthesizedClone(node.name)), 
85609             /*location*/ node);
85610         }
85611         function visitComputedPropertyName(node) {
85612             return ts.visitEachChild(node, visitor, context);
85613         }
85614         /**
85615          * Visits a YieldExpression node.
85616          *
85617          * @param node A YieldExpression node.
85618          */
85619         function visitYieldExpression(node) {
85620             // `yield` expressions are transformed using the generators transformer.
85621             return ts.visitEachChild(node, visitor, context);
85622         }
85623         /**
85624          * Visits an ArrayLiteralExpression that contains a spread element.
85625          *
85626          * @param node An ArrayLiteralExpression node.
85627          */
85628         function visitArrayLiteralExpression(node) {
85629             if (ts.some(node.elements, ts.isSpreadElement)) {
85630                 // We are here because we contain a SpreadElementExpression.
85631                 return transformAndSpreadElements(node.elements, /*needsUniqueCopy*/ true, !!node.multiLine, /*hasTrailingComma*/ !!node.elements.hasTrailingComma);
85632             }
85633             return ts.visitEachChild(node, visitor, context);
85634         }
85635         /**
85636          * Visits a CallExpression that contains either a spread element or `super`.
85637          *
85638          * @param node a CallExpression.
85639          */
85640         function visitCallExpression(node) {
85641             if (ts.getEmitFlags(node) & 33554432 /* TypeScriptClassWrapper */) {
85642                 return visitTypeScriptClassWrapper(node);
85643             }
85644             var expression = ts.skipOuterExpressions(node.expression);
85645             if (expression.kind === 102 /* SuperKeyword */ ||
85646                 ts.isSuperProperty(expression) ||
85647                 ts.some(node.arguments, ts.isSpreadElement)) {
85648                 return visitCallExpressionWithPotentialCapturedThisAssignment(node, /*assignToCapturedThis*/ true);
85649             }
85650             return ts.updateCall(node, ts.visitNode(node.expression, callExpressionVisitor, ts.isExpression), 
85651             /*typeArguments*/ undefined, ts.visitNodes(node.arguments, visitor, ts.isExpression));
85652         }
85653         function visitTypeScriptClassWrapper(node) {
85654             // This is a call to a class wrapper function (an IIFE) created by the 'ts' transformer.
85655             // The wrapper has a form similar to:
85656             //
85657             //  (function() {
85658             //      class C { // 1
85659             //      }
85660             //      C.x = 1; // 2
85661             //      return C;
85662             //  }())
85663             //
85664             // When we transform the class, we end up with something like this:
85665             //
85666             //  (function () {
85667             //      var C = (function () { // 3
85668             //          function C() {
85669             //          }
85670             //          return C; // 4
85671             //      }());
85672             //      C.x = 1;
85673             //      return C;
85674             //  }())
85675             //
85676             // We want to simplify the two nested IIFEs to end up with something like this:
85677             //
85678             //  (function () {
85679             //      function C() {
85680             //      }
85681             //      C.x = 1;
85682             //      return C;
85683             //  }())
85684             // We skip any outer expressions in a number of places to get to the innermost
85685             // expression, but we will restore them later to preserve comments and source maps.
85686             var body = ts.cast(ts.cast(ts.skipOuterExpressions(node.expression), ts.isArrowFunction).body, ts.isBlock);
85687             // The class statements are the statements generated by visiting the first statement with initializer of the
85688             // body (1), while all other statements are added to remainingStatements (2)
85689             var isVariableStatementWithInitializer = function (stmt) { return ts.isVariableStatement(stmt) && !!ts.first(stmt.declarationList.declarations).initializer; };
85690             // visit the class body statements outside of any converted loop body.
85691             var savedConvertedLoopState = convertedLoopState;
85692             convertedLoopState = undefined;
85693             var bodyStatements = ts.visitNodes(body.statements, visitor, ts.isStatement);
85694             convertedLoopState = savedConvertedLoopState;
85695             var classStatements = ts.filter(bodyStatements, isVariableStatementWithInitializer);
85696             var remainingStatements = ts.filter(bodyStatements, function (stmt) { return !isVariableStatementWithInitializer(stmt); });
85697             var varStatement = ts.cast(ts.first(classStatements), ts.isVariableStatement);
85698             // We know there is only one variable declaration here as we verified this in an
85699             // earlier call to isTypeScriptClassWrapper
85700             var variable = varStatement.declarationList.declarations[0];
85701             var initializer = ts.skipOuterExpressions(variable.initializer);
85702             // Under certain conditions, the 'ts' transformer may introduce a class alias, which
85703             // we see as an assignment, for example:
85704             //
85705             //  (function () {
85706             //      var C_1;
85707             //      var C = C_1 = (function () {
85708             //          function C() {
85709             //          }
85710             //          C.x = function () { return C_1; }
85711             //          return C;
85712             //      }());
85713             //      C = C_1 = __decorate([dec], C);
85714             //      return C;
85715             //  }())
85716             //
85717             var aliasAssignment = ts.tryCast(initializer, ts.isAssignmentExpression);
85718             // The underlying call (3) is another IIFE that may contain a '_super' argument.
85719             var call = ts.cast(aliasAssignment ? ts.skipOuterExpressions(aliasAssignment.right) : initializer, ts.isCallExpression);
85720             var func = ts.cast(ts.skipOuterExpressions(call.expression), ts.isFunctionExpression);
85721             var funcStatements = func.body.statements;
85722             var classBodyStart = 0;
85723             var classBodyEnd = -1;
85724             var statements = [];
85725             if (aliasAssignment) {
85726                 // If we have a class alias assignment, we need to move it to the down-level constructor
85727                 // function we generated for the class.
85728                 var extendsCall = ts.tryCast(funcStatements[classBodyStart], ts.isExpressionStatement);
85729                 if (extendsCall) {
85730                     statements.push(extendsCall);
85731                     classBodyStart++;
85732                 }
85733                 // The next statement is the function declaration.
85734                 statements.push(funcStatements[classBodyStart]);
85735                 classBodyStart++;
85736                 // Add the class alias following the declaration.
85737                 statements.push(ts.createExpressionStatement(ts.createAssignment(aliasAssignment.left, ts.cast(variable.name, ts.isIdentifier))));
85738             }
85739             // Find the trailing 'return' statement (4)
85740             while (!ts.isReturnStatement(ts.elementAt(funcStatements, classBodyEnd))) {
85741                 classBodyEnd--;
85742             }
85743             // When we extract the statements of the inner IIFE, we exclude the 'return' statement (4)
85744             // as we already have one that has been introduced by the 'ts' transformer.
85745             ts.addRange(statements, funcStatements, classBodyStart, classBodyEnd);
85746             if (classBodyEnd < -1) {
85747                 // If there were any hoisted declarations following the return statement, we should
85748                 // append them.
85749                 ts.addRange(statements, funcStatements, classBodyEnd + 1);
85750             }
85751             // Add the remaining statements of the outer wrapper.
85752             ts.addRange(statements, remainingStatements);
85753             // The 'es2015' class transform may add an end-of-declaration marker. If so we will add it
85754             // after the remaining statements from the 'ts' transformer.
85755             ts.addRange(statements, classStatements, /*start*/ 1);
85756             // Recreate any outer parentheses or partially-emitted expressions to preserve source map
85757             // and comment locations.
85758             return ts.recreateOuterExpressions(node.expression, ts.recreateOuterExpressions(variable.initializer, ts.recreateOuterExpressions(aliasAssignment && aliasAssignment.right, ts.updateCall(call, ts.recreateOuterExpressions(call.expression, ts.updateFunctionExpression(func, 
85759             /*modifiers*/ undefined, 
85760             /*asteriskToken*/ undefined, 
85761             /*name*/ undefined, 
85762             /*typeParameters*/ undefined, func.parameters, 
85763             /*type*/ undefined, ts.updateBlock(func.body, statements))), 
85764             /*typeArguments*/ undefined, call.arguments))));
85765         }
85766         function visitImmediateSuperCallInBody(node) {
85767             return visitCallExpressionWithPotentialCapturedThisAssignment(node, /*assignToCapturedThis*/ false);
85768         }
85769         function visitCallExpressionWithPotentialCapturedThisAssignment(node, assignToCapturedThis) {
85770             // We are here either because SuperKeyword was used somewhere in the expression, or
85771             // because we contain a SpreadElementExpression.
85772             if (node.transformFlags & 8192 /* ContainsRestOrSpread */ ||
85773                 node.expression.kind === 102 /* SuperKeyword */ ||
85774                 ts.isSuperProperty(ts.skipOuterExpressions(node.expression))) {
85775                 var _a = ts.createCallBinding(node.expression, hoistVariableDeclaration), target = _a.target, thisArg = _a.thisArg;
85776                 if (node.expression.kind === 102 /* SuperKeyword */) {
85777                     ts.setEmitFlags(thisArg, 4 /* NoSubstitution */);
85778                 }
85779                 var resultingCall = void 0;
85780                 if (node.transformFlags & 8192 /* ContainsRestOrSpread */) {
85781                     // [source]
85782                     //      f(...a, b)
85783                     //      x.m(...a, b)
85784                     //      super(...a, b)
85785                     //      super.m(...a, b) // in static
85786                     //      super.m(...a, b) // in instance
85787                     //
85788                     // [output]
85789                     //      f.apply(void 0, a.concat([b]))
85790                     //      (_a = x).m.apply(_a, a.concat([b]))
85791                     //      _super.apply(this, a.concat([b]))
85792                     //      _super.m.apply(this, a.concat([b]))
85793                     //      _super.prototype.m.apply(this, a.concat([b]))
85794                     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));
85795                 }
85796                 else {
85797                     // [source]
85798                     //      super(a)
85799                     //      super.m(a) // in static
85800                     //      super.m(a) // in instance
85801                     //
85802                     // [output]
85803                     //      _super.call(this, a)
85804                     //      _super.m.call(this, a)
85805                     //      _super.prototype.m.call(this, a)
85806                     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), 
85807                     /*location*/ node);
85808                 }
85809                 if (node.expression.kind === 102 /* SuperKeyword */) {
85810                     var initializer = ts.createLogicalOr(resultingCall, createActualThis());
85811                     resultingCall = assignToCapturedThis
85812                         ? ts.createAssignment(ts.createFileLevelUniqueName("_this"), initializer)
85813                         : initializer;
85814                 }
85815                 return ts.setOriginalNode(resultingCall, node);
85816             }
85817             return ts.visitEachChild(node, visitor, context);
85818         }
85819         /**
85820          * Visits a NewExpression that contains a spread element.
85821          *
85822          * @param node A NewExpression node.
85823          */
85824         function visitNewExpression(node) {
85825             if (ts.some(node.arguments, ts.isSpreadElement)) {
85826                 // We are here because we contain a SpreadElementExpression.
85827                 // [source]
85828                 //      new C(...a)
85829                 //
85830                 // [output]
85831                 //      new ((_a = C).bind.apply(_a, [void 0].concat(a)))()
85832                 var _a = ts.createCallBinding(ts.createPropertyAccess(node.expression, "bind"), hoistVariableDeclaration), target = _a.target, thisArg = _a.thisArg;
85833                 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)), 
85834                 /*typeArguments*/ undefined, []);
85835             }
85836             return ts.visitEachChild(node, visitor, context);
85837         }
85838         /**
85839          * Transforms an array of Expression nodes that contains a SpreadExpression.
85840          *
85841          * @param elements The array of Expression nodes.
85842          * @param needsUniqueCopy A value indicating whether to ensure that the result is a fresh array.
85843          * @param multiLine A value indicating whether the result should be emitted on multiple lines.
85844          */
85845         function transformAndSpreadElements(elements, needsUniqueCopy, multiLine, hasTrailingComma) {
85846             // [source]
85847             //      [a, ...b, c]
85848             //
85849             // [output (downlevelIteration)]
85850             //      __spread([a], b, [c])
85851             //
85852             // [output]
85853             //      __spreadArrays([a], b, [c])
85854             // Map spans of spread expressions into their expressions and spans of other
85855             // expressions into an array literal.
85856             var numElements = elements.length;
85857             var segments = ts.flatten(ts.spanMap(elements, partitionSpread, function (partition, visitPartition, _start, end) {
85858                 return visitPartition(partition, multiLine, hasTrailingComma && end === numElements);
85859             }));
85860             if (compilerOptions.downlevelIteration) {
85861                 if (segments.length === 1) {
85862                     var firstSegment = segments[0];
85863                     if (isCallToHelper(firstSegment, "___spread")) {
85864                         return segments[0];
85865                     }
85866                 }
85867                 return ts.createSpreadHelper(context, segments);
85868             }
85869             else {
85870                 if (segments.length === 1) {
85871                     var firstSegment = segments[0];
85872                     if (!needsUniqueCopy
85873                         || isPackedArrayLiteral(firstSegment)
85874                         || isCallToHelper(firstSegment, "___spreadArrays")) {
85875                         return segments[0];
85876                     }
85877                 }
85878                 return ts.createSpreadArraysHelper(context, segments);
85879             }
85880         }
85881         function isPackedElement(node) {
85882             return !ts.isOmittedExpression(node);
85883         }
85884         function isPackedArrayLiteral(node) {
85885             return ts.isArrayLiteralExpression(node) && ts.every(node.elements, isPackedElement);
85886         }
85887         function isCallToHelper(firstSegment, helperName) {
85888             return ts.isCallExpression(firstSegment)
85889                 && ts.isIdentifier(firstSegment.expression)
85890                 && (ts.getEmitFlags(firstSegment.expression) & 4096 /* HelperName */)
85891                 && firstSegment.expression.escapedText === helperName;
85892         }
85893         function partitionSpread(node) {
85894             return ts.isSpreadElement(node)
85895                 ? visitSpanOfSpreads
85896                 : visitSpanOfNonSpreads;
85897         }
85898         function visitSpanOfSpreads(chunk) {
85899             return ts.map(chunk, visitExpressionOfSpread);
85900         }
85901         function visitSpanOfNonSpreads(chunk, multiLine, hasTrailingComma) {
85902             return ts.createArrayLiteral(ts.visitNodes(ts.createNodeArray(chunk, hasTrailingComma), visitor, ts.isExpression), multiLine);
85903         }
85904         function visitSpreadElement(node) {
85905             return ts.visitNode(node.expression, visitor, ts.isExpression);
85906         }
85907         /**
85908          * Transforms the expression of a SpreadExpression node.
85909          *
85910          * @param node A SpreadExpression node.
85911          */
85912         function visitExpressionOfSpread(node) {
85913             return ts.visitNode(node.expression, visitor, ts.isExpression);
85914         }
85915         /**
85916          * Visits a template literal.
85917          *
85918          * @param node A template literal.
85919          */
85920         function visitTemplateLiteral(node) {
85921             return ts.setTextRange(ts.createLiteral(node.text), node);
85922         }
85923         /**
85924          * Visits a string literal with an extended unicode escape.
85925          *
85926          * @param node A string literal.
85927          */
85928         function visitStringLiteral(node) {
85929             if (node.hasExtendedUnicodeEscape) {
85930                 return ts.setTextRange(ts.createLiteral(node.text), node);
85931             }
85932             return node;
85933         }
85934         /**
85935          * Visits a binary or octal (ES6) numeric literal.
85936          *
85937          * @param node A string literal.
85938          */
85939         function visitNumericLiteral(node) {
85940             if (node.numericLiteralFlags & 384 /* BinaryOrOctalSpecifier */) {
85941                 return ts.setTextRange(ts.createNumericLiteral(node.text), node);
85942             }
85943             return node;
85944         }
85945         /**
85946          * Visits a TaggedTemplateExpression node.
85947          *
85948          * @param node A TaggedTemplateExpression node.
85949          */
85950         function visitTaggedTemplateExpression(node) {
85951             return ts.processTaggedTemplateExpression(context, node, visitor, currentSourceFile, recordTaggedTemplateString, ts.ProcessLevel.All);
85952         }
85953         /**
85954          * Visits a TemplateExpression node.
85955          *
85956          * @param node A TemplateExpression node.
85957          */
85958         function visitTemplateExpression(node) {
85959             var expressions = [];
85960             addTemplateHead(expressions, node);
85961             addTemplateSpans(expressions, node);
85962             // createAdd will check if each expression binds less closely than binary '+'.
85963             // If it does, it wraps the expression in parentheses. Otherwise, something like
85964             //    `abc${ 1 << 2 }`
85965             // becomes
85966             //    "abc" + 1 << 2 + ""
85967             // which is really
85968             //    ("abc" + 1) << (2 + "")
85969             // rather than
85970             //    "abc" + (1 << 2) + ""
85971             var expression = ts.reduceLeft(expressions, ts.createAdd);
85972             if (ts.nodeIsSynthesized(expression)) {
85973                 expression.pos = node.pos;
85974                 expression.end = node.end;
85975             }
85976             return expression;
85977         }
85978         /**
85979          * Gets a value indicating whether we need to include the head of a TemplateExpression.
85980          *
85981          * @param node A TemplateExpression node.
85982          */
85983         function shouldAddTemplateHead(node) {
85984             // If this expression has an empty head literal and the first template span has a non-empty
85985             // literal, then emitting the empty head literal is not necessary.
85986             //     `${ foo } and ${ bar }`
85987             // can be emitted as
85988             //     foo + " and " + bar
85989             // This is because it is only required that one of the first two operands in the emit
85990             // output must be a string literal, so that the other operand and all following operands
85991             // are forced into strings.
85992             //
85993             // If the first template span has an empty literal, then the head must still be emitted.
85994             //     `${ foo }${ bar }`
85995             // must still be emitted as
85996             //     "" + foo + bar
85997             // There is always atleast one templateSpan in this code path, since
85998             // NoSubstitutionTemplateLiterals are directly emitted via emitLiteral()
85999             ts.Debug.assert(node.templateSpans.length !== 0);
86000             return node.head.text.length !== 0 || node.templateSpans[0].literal.text.length === 0;
86001         }
86002         /**
86003          * Adds the head of a TemplateExpression to an array of expressions.
86004          *
86005          * @param expressions An array of expressions.
86006          * @param node A TemplateExpression node.
86007          */
86008         function addTemplateHead(expressions, node) {
86009             if (!shouldAddTemplateHead(node)) {
86010                 return;
86011             }
86012             expressions.push(ts.createLiteral(node.head.text));
86013         }
86014         /**
86015          * Visits and adds the template spans of a TemplateExpression to an array of expressions.
86016          *
86017          * @param expressions An array of expressions.
86018          * @param node A TemplateExpression node.
86019          */
86020         function addTemplateSpans(expressions, node) {
86021             for (var _i = 0, _a = node.templateSpans; _i < _a.length; _i++) {
86022                 var span = _a[_i];
86023                 expressions.push(ts.visitNode(span.expression, visitor, ts.isExpression));
86024                 // Only emit if the literal is non-empty.
86025                 // The binary '+' operator is left-associative, so the first string concatenation
86026                 // with the head will force the result up to this point to be a string.
86027                 // Emitting a '+ ""' has no semantic effect for middles and tails.
86028                 if (span.literal.text.length !== 0) {
86029                     expressions.push(ts.createLiteral(span.literal.text));
86030                 }
86031             }
86032         }
86033         /**
86034          * Visits the `super` keyword
86035          */
86036         function visitSuperKeyword(isExpressionOfCall) {
86037             return hierarchyFacts & 8 /* NonStaticClassElement */ && !isExpressionOfCall ? ts.createPropertyAccess(ts.createFileLevelUniqueName("_super"), "prototype") :
86038                 ts.createFileLevelUniqueName("_super");
86039         }
86040         function visitMetaProperty(node) {
86041             if (node.keywordToken === 99 /* NewKeyword */ && node.name.escapedText === "target") {
86042                 hierarchyFacts |= 16384 /* NewTarget */;
86043                 return ts.createFileLevelUniqueName("_newTarget");
86044             }
86045             return node;
86046         }
86047         /**
86048          * Called by the printer just before a node is printed.
86049          *
86050          * @param hint A hint as to the intended usage of the node.
86051          * @param node The node to be printed.
86052          * @param emitCallback The callback used to emit the node.
86053          */
86054         function onEmitNode(hint, node, emitCallback) {
86055             if (enabledSubstitutions & 1 /* CapturedThis */ && ts.isFunctionLike(node)) {
86056                 // If we are tracking a captured `this`, keep track of the enclosing function.
86057                 var ancestorFacts = enterSubtree(16286 /* FunctionExcludes */, ts.getEmitFlags(node) & 8 /* CapturesThis */
86058                     ? 65 /* FunctionIncludes */ | 16 /* CapturesThis */
86059                     : 65 /* FunctionIncludes */);
86060                 previousOnEmitNode(hint, node, emitCallback);
86061                 exitSubtree(ancestorFacts, 0 /* None */, 0 /* None */);
86062                 return;
86063             }
86064             previousOnEmitNode(hint, node, emitCallback);
86065         }
86066         /**
86067          * Enables a more costly code path for substitutions when we determine a source file
86068          * contains block-scoped bindings (e.g. `let` or `const`).
86069          */
86070         function enableSubstitutionsForBlockScopedBindings() {
86071             if ((enabledSubstitutions & 2 /* BlockScopedBindings */) === 0) {
86072                 enabledSubstitutions |= 2 /* BlockScopedBindings */;
86073                 context.enableSubstitution(75 /* Identifier */);
86074             }
86075         }
86076         /**
86077          * Enables a more costly code path for substitutions when we determine a source file
86078          * contains a captured `this`.
86079          */
86080         function enableSubstitutionsForCapturedThis() {
86081             if ((enabledSubstitutions & 1 /* CapturedThis */) === 0) {
86082                 enabledSubstitutions |= 1 /* CapturedThis */;
86083                 context.enableSubstitution(104 /* ThisKeyword */);
86084                 context.enableEmitNotification(162 /* Constructor */);
86085                 context.enableEmitNotification(161 /* MethodDeclaration */);
86086                 context.enableEmitNotification(163 /* GetAccessor */);
86087                 context.enableEmitNotification(164 /* SetAccessor */);
86088                 context.enableEmitNotification(202 /* ArrowFunction */);
86089                 context.enableEmitNotification(201 /* FunctionExpression */);
86090                 context.enableEmitNotification(244 /* FunctionDeclaration */);
86091             }
86092         }
86093         /**
86094          * Hooks node substitutions.
86095          *
86096          * @param hint The context for the emitter.
86097          * @param node The node to substitute.
86098          */
86099         function onSubstituteNode(hint, node) {
86100             node = previousOnSubstituteNode(hint, node);
86101             if (hint === 1 /* Expression */) {
86102                 return substituteExpression(node);
86103             }
86104             if (ts.isIdentifier(node)) {
86105                 return substituteIdentifier(node);
86106             }
86107             return node;
86108         }
86109         /**
86110          * Hooks substitutions for non-expression identifiers.
86111          */
86112         function substituteIdentifier(node) {
86113             // Only substitute the identifier if we have enabled substitutions for block-scoped
86114             // bindings.
86115             if (enabledSubstitutions & 2 /* BlockScopedBindings */ && !ts.isInternalName(node)) {
86116                 var original = ts.getParseTreeNode(node, ts.isIdentifier);
86117                 if (original && isNameOfDeclarationWithCollidingName(original)) {
86118                     return ts.setTextRange(ts.getGeneratedNameForNode(original), node);
86119                 }
86120             }
86121             return node;
86122         }
86123         /**
86124          * Determines whether a name is the name of a declaration with a colliding name.
86125          * NOTE: This function expects to be called with an original source tree node.
86126          *
86127          * @param node An original source tree node.
86128          */
86129         function isNameOfDeclarationWithCollidingName(node) {
86130             switch (node.parent.kind) {
86131                 case 191 /* BindingElement */:
86132                 case 245 /* ClassDeclaration */:
86133                 case 248 /* EnumDeclaration */:
86134                 case 242 /* VariableDeclaration */:
86135                     return node.parent.name === node
86136                         && resolver.isDeclarationWithCollidingName(node.parent);
86137             }
86138             return false;
86139         }
86140         /**
86141          * Substitutes an expression.
86142          *
86143          * @param node An Expression node.
86144          */
86145         function substituteExpression(node) {
86146             switch (node.kind) {
86147                 case 75 /* Identifier */:
86148                     return substituteExpressionIdentifier(node);
86149                 case 104 /* ThisKeyword */:
86150                     return substituteThisKeyword(node);
86151             }
86152             return node;
86153         }
86154         /**
86155          * Substitutes an expression identifier.
86156          *
86157          * @param node An Identifier node.
86158          */
86159         function substituteExpressionIdentifier(node) {
86160             if (enabledSubstitutions & 2 /* BlockScopedBindings */ && !ts.isInternalName(node)) {
86161                 var declaration = resolver.getReferencedDeclarationWithCollidingName(node);
86162                 if (declaration && !(ts.isClassLike(declaration) && isPartOfClassBody(declaration, node))) {
86163                     return ts.setTextRange(ts.getGeneratedNameForNode(ts.getNameOfDeclaration(declaration)), node);
86164                 }
86165             }
86166             return node;
86167         }
86168         function isPartOfClassBody(declaration, node) {
86169             var currentNode = ts.getParseTreeNode(node);
86170             if (!currentNode || currentNode === declaration || currentNode.end <= declaration.pos || currentNode.pos >= declaration.end) {
86171                 // if the node has no correlation to a parse tree node, its definitely not
86172                 // part of the body.
86173                 // if the node is outside of the document range of the declaration, its
86174                 // definitely not part of the body.
86175                 return false;
86176             }
86177             var blockScope = ts.getEnclosingBlockScopeContainer(declaration);
86178             while (currentNode) {
86179                 if (currentNode === blockScope || currentNode === declaration) {
86180                     // if we are in the enclosing block scope of the declaration, we are definitely
86181                     // not inside the class body.
86182                     return false;
86183                 }
86184                 if (ts.isClassElement(currentNode) && currentNode.parent === declaration) {
86185                     return true;
86186                 }
86187                 currentNode = currentNode.parent;
86188             }
86189             return false;
86190         }
86191         /**
86192          * Substitutes `this` when contained within an arrow function.
86193          *
86194          * @param node The ThisKeyword node.
86195          */
86196         function substituteThisKeyword(node) {
86197             if (enabledSubstitutions & 1 /* CapturedThis */
86198                 && hierarchyFacts & 16 /* CapturesThis */) {
86199                 return ts.setTextRange(ts.createFileLevelUniqueName("_this"), node);
86200             }
86201             return node;
86202         }
86203         function getClassMemberPrefix(node, member) {
86204             return ts.hasModifier(member, 32 /* Static */)
86205                 ? ts.getInternalName(node)
86206                 : ts.createPropertyAccess(ts.getInternalName(node), "prototype");
86207         }
86208         function hasSynthesizedDefaultSuperCall(constructor, hasExtendsClause) {
86209             if (!constructor || !hasExtendsClause) {
86210                 return false;
86211             }
86212             if (ts.some(constructor.parameters)) {
86213                 return false;
86214             }
86215             var statement = ts.firstOrUndefined(constructor.body.statements);
86216             if (!statement || !ts.nodeIsSynthesized(statement) || statement.kind !== 226 /* ExpressionStatement */) {
86217                 return false;
86218             }
86219             var statementExpression = statement.expression;
86220             if (!ts.nodeIsSynthesized(statementExpression) || statementExpression.kind !== 196 /* CallExpression */) {
86221                 return false;
86222             }
86223             var callTarget = statementExpression.expression;
86224             if (!ts.nodeIsSynthesized(callTarget) || callTarget.kind !== 102 /* SuperKeyword */) {
86225                 return false;
86226             }
86227             var callArgument = ts.singleOrUndefined(statementExpression.arguments);
86228             if (!callArgument || !ts.nodeIsSynthesized(callArgument) || callArgument.kind !== 213 /* SpreadElement */) {
86229                 return false;
86230             }
86231             var expression = callArgument.expression;
86232             return ts.isIdentifier(expression) && expression.escapedText === "arguments";
86233         }
86234     }
86235     ts.transformES2015 = transformES2015;
86236     function createExtendsHelper(context, name) {
86237         context.requestEmitHelper(ts.extendsHelper);
86238         return ts.createCall(ts.getUnscopedHelperName("__extends"), 
86239         /*typeArguments*/ undefined, [
86240             name,
86241             ts.createFileLevelUniqueName("_super")
86242         ]);
86243     }
86244     ts.extendsHelper = {
86245         name: "typescript:extends",
86246         importName: "__extends",
86247         scoped: false,
86248         priority: 0,
86249         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            })();"
86250     };
86251 })(ts || (ts = {}));
86252 /*@internal*/
86253 var ts;
86254 (function (ts) {
86255     /**
86256      * Transforms ES5 syntax into ES3 syntax.
86257      *
86258      * @param context Context and state information for the transformation.
86259      */
86260     function transformES5(context) {
86261         var compilerOptions = context.getCompilerOptions();
86262         // enable emit notification only if using --jsx preserve or react-native
86263         var previousOnEmitNode;
86264         var noSubstitution;
86265         if (compilerOptions.jsx === 1 /* Preserve */ || compilerOptions.jsx === 3 /* ReactNative */) {
86266             previousOnEmitNode = context.onEmitNode;
86267             context.onEmitNode = onEmitNode;
86268             context.enableEmitNotification(268 /* JsxOpeningElement */);
86269             context.enableEmitNotification(269 /* JsxClosingElement */);
86270             context.enableEmitNotification(267 /* JsxSelfClosingElement */);
86271             noSubstitution = [];
86272         }
86273         var previousOnSubstituteNode = context.onSubstituteNode;
86274         context.onSubstituteNode = onSubstituteNode;
86275         context.enableSubstitution(194 /* PropertyAccessExpression */);
86276         context.enableSubstitution(281 /* PropertyAssignment */);
86277         return ts.chainBundle(transformSourceFile);
86278         /**
86279          * Transforms an ES5 source file to ES3.
86280          *
86281          * @param node A SourceFile
86282          */
86283         function transformSourceFile(node) {
86284             return node;
86285         }
86286         /**
86287          * Called by the printer just before a node is printed.
86288          *
86289          * @param hint A hint as to the intended usage of the node.
86290          * @param node The node to emit.
86291          * @param emitCallback A callback used to emit the node.
86292          */
86293         function onEmitNode(hint, node, emitCallback) {
86294             switch (node.kind) {
86295                 case 268 /* JsxOpeningElement */:
86296                 case 269 /* JsxClosingElement */:
86297                 case 267 /* JsxSelfClosingElement */:
86298                     var tagName = node.tagName;
86299                     noSubstitution[ts.getOriginalNodeId(tagName)] = true;
86300                     break;
86301             }
86302             previousOnEmitNode(hint, node, emitCallback);
86303         }
86304         /**
86305          * Hooks node substitutions.
86306          *
86307          * @param hint A hint as to the intended usage of the node.
86308          * @param node The node to substitute.
86309          */
86310         function onSubstituteNode(hint, node) {
86311             if (node.id && noSubstitution && noSubstitution[node.id]) {
86312                 return previousOnSubstituteNode(hint, node);
86313             }
86314             node = previousOnSubstituteNode(hint, node);
86315             if (ts.isPropertyAccessExpression(node)) {
86316                 return substitutePropertyAccessExpression(node);
86317             }
86318             else if (ts.isPropertyAssignment(node)) {
86319                 return substitutePropertyAssignment(node);
86320             }
86321             return node;
86322         }
86323         /**
86324          * Substitutes a PropertyAccessExpression whose name is a reserved word.
86325          *
86326          * @param node A PropertyAccessExpression
86327          */
86328         function substitutePropertyAccessExpression(node) {
86329             if (ts.isPrivateIdentifier(node.name)) {
86330                 return node;
86331             }
86332             var literalName = trySubstituteReservedName(node.name);
86333             if (literalName) {
86334                 return ts.setTextRange(ts.createElementAccess(node.expression, literalName), node);
86335             }
86336             return node;
86337         }
86338         /**
86339          * Substitutes a PropertyAssignment whose name is a reserved word.
86340          *
86341          * @param node A PropertyAssignment
86342          */
86343         function substitutePropertyAssignment(node) {
86344             var literalName = ts.isIdentifier(node.name) && trySubstituteReservedName(node.name);
86345             if (literalName) {
86346                 return ts.updatePropertyAssignment(node, literalName, node.initializer);
86347             }
86348             return node;
86349         }
86350         /**
86351          * If an identifier name is a reserved word, returns a string literal for the name.
86352          *
86353          * @param name An Identifier
86354          */
86355         function trySubstituteReservedName(name) {
86356             var token = name.originalKeywordKind || (ts.nodeIsSynthesized(name) ? ts.stringToToken(ts.idText(name)) : undefined);
86357             if (token !== undefined && token >= 77 /* FirstReservedWord */ && token <= 112 /* LastReservedWord */) {
86358                 return ts.setTextRange(ts.createLiteral(name), name);
86359             }
86360             return undefined;
86361         }
86362     }
86363     ts.transformES5 = transformES5;
86364 })(ts || (ts = {}));
86365 // Transforms generator functions into a compatible ES5 representation with similar runtime
86366 // semantics. This is accomplished by first transforming the body of each generator
86367 // function into an intermediate representation that is the compiled into a JavaScript
86368 // switch statement.
86369 //
86370 // Many functions in this transformer will contain comments indicating the expected
86371 // intermediate representation. For illustrative purposes, the following intermediate
86372 // language is used to define this intermediate representation:
86373 //
86374 //  .nop                            - Performs no operation.
86375 //  .local NAME, ...                - Define local variable declarations.
86376 //  .mark LABEL                     - Mark the location of a label.
86377 //  .br LABEL                       - Jump to a label. If jumping out of a protected
86378 //                                    region, all .finally blocks are executed.
86379 //  .brtrue LABEL, (x)              - Jump to a label IIF the expression `x` is truthy.
86380 //                                    If jumping out of a protected region, all .finally
86381 //                                    blocks are executed.
86382 //  .brfalse LABEL, (x)             - Jump to a label IIF the expression `x` is falsey.
86383 //                                    If jumping out of a protected region, all .finally
86384 //                                    blocks are executed.
86385 //  .yield (x)                      - Yield the value of the optional expression `x`.
86386 //                                    Resume at the next label.
86387 //  .yieldstar (x)                  - Delegate yield to the value of the optional
86388 //                                    expression `x`. Resume at the next label.
86389 //                                    NOTE: `x` must be an Iterator, not an Iterable.
86390 //  .loop CONTINUE, BREAK           - Marks the beginning of a loop. Any "continue" or
86391 //                                    "break" abrupt completions jump to the CONTINUE or
86392 //                                    BREAK labels, respectively.
86393 //  .endloop                        - Marks the end of a loop.
86394 //  .with (x)                       - Marks the beginning of a WithStatement block, using
86395 //                                    the supplied expression.
86396 //  .endwith                        - Marks the end of a WithStatement.
86397 //  .switch                         - Marks the beginning of a SwitchStatement.
86398 //  .endswitch                      - Marks the end of a SwitchStatement.
86399 //  .labeled NAME                   - Marks the beginning of a LabeledStatement with the
86400 //                                    supplied name.
86401 //  .endlabeled                     - Marks the end of a LabeledStatement.
86402 //  .try TRY, CATCH, FINALLY, END   - Marks the beginning of a protected region, and the
86403 //                                    labels for each block.
86404 //  .catch (x)                      - Marks the beginning of a catch block.
86405 //  .finally                        - Marks the beginning of a finally block.
86406 //  .endfinally                     - Marks the end of a finally block.
86407 //  .endtry                         - Marks the end of a protected region.
86408 //  .throw (x)                      - Throws the value of the expression `x`.
86409 //  .return (x)                     - Returns the value of the expression `x`.
86410 //
86411 // In addition, the illustrative intermediate representation introduces some special
86412 // variables:
86413 //
86414 //  %sent%                          - Either returns the next value sent to the generator,
86415 //                                    returns the result of a delegated yield, or throws
86416 //                                    the exception sent to the generator.
86417 //  %error%                         - Returns the value of the current exception in a
86418 //                                    catch block.
86419 //
86420 // This intermediate representation is then compiled into JavaScript syntax. The resulting
86421 // compilation output looks something like the following:
86422 //
86423 //  function f() {
86424 //      var /*locals*/;
86425 //      /*functions*/
86426 //      return __generator(function (state) {
86427 //          switch (state.label) {
86428 //              /*cases per label*/
86429 //          }
86430 //      });
86431 //  }
86432 //
86433 // Each of the above instructions corresponds to JavaScript emit similar to the following:
86434 //
86435 //  .local NAME                   | var NAME;
86436 // -------------------------------|----------------------------------------------
86437 //  .mark LABEL                   | case LABEL:
86438 // -------------------------------|----------------------------------------------
86439 //  .br LABEL                     |     return [3 /*break*/, LABEL];
86440 // -------------------------------|----------------------------------------------
86441 //  .brtrue LABEL, (x)            |     if (x) return [3 /*break*/, LABEL];
86442 // -------------------------------|----------------------------------------------
86443 //  .brfalse LABEL, (x)           |     if (!(x)) return [3, /*break*/, LABEL];
86444 // -------------------------------|----------------------------------------------
86445 //  .yield (x)                    |     return [4 /*yield*/, x];
86446 //  .mark RESUME                  | case RESUME:
86447 //      a = %sent%;               |     a = state.sent();
86448 // -------------------------------|----------------------------------------------
86449 //  .yieldstar (x)                |     return [5 /*yield**/, x];
86450 //  .mark RESUME                  | case RESUME:
86451 //      a = %sent%;               |     a = state.sent();
86452 // -------------------------------|----------------------------------------------
86453 //  .with (_a)                    |     with (_a) {
86454 //      a();                      |         a();
86455 //                                |     }
86456 //                                |     state.label = LABEL;
86457 //  .mark LABEL                   | case LABEL:
86458 //                                |     with (_a) {
86459 //      b();                      |         b();
86460 //                                |     }
86461 //  .endwith                      |
86462 // -------------------------------|----------------------------------------------
86463 //                                | case 0:
86464 //                                |     state.trys = [];
86465 //                                | ...
86466 //  .try TRY, CATCH, FINALLY, END |
86467 //  .mark TRY                     | case TRY:
86468 //                                |     state.trys.push([TRY, CATCH, FINALLY, END]);
86469 //  .nop                          |
86470 //      a();                      |     a();
86471 //  .br END                       |     return [3 /*break*/, END];
86472 //  .catch (e)                    |
86473 //  .mark CATCH                   | case CATCH:
86474 //                                |     e = state.sent();
86475 //      b();                      |     b();
86476 //  .br END                       |     return [3 /*break*/, END];
86477 //  .finally                      |
86478 //  .mark FINALLY                 | case FINALLY:
86479 //      c();                      |     c();
86480 //  .endfinally                   |     return [7 /*endfinally*/];
86481 //  .endtry                       |
86482 //  .mark END                     | case END:
86483 /*@internal*/
86484 var ts;
86485 (function (ts) {
86486     var OpCode;
86487     (function (OpCode) {
86488         OpCode[OpCode["Nop"] = 0] = "Nop";
86489         OpCode[OpCode["Statement"] = 1] = "Statement";
86490         OpCode[OpCode["Assign"] = 2] = "Assign";
86491         OpCode[OpCode["Break"] = 3] = "Break";
86492         OpCode[OpCode["BreakWhenTrue"] = 4] = "BreakWhenTrue";
86493         OpCode[OpCode["BreakWhenFalse"] = 5] = "BreakWhenFalse";
86494         OpCode[OpCode["Yield"] = 6] = "Yield";
86495         OpCode[OpCode["YieldStar"] = 7] = "YieldStar";
86496         OpCode[OpCode["Return"] = 8] = "Return";
86497         OpCode[OpCode["Throw"] = 9] = "Throw";
86498         OpCode[OpCode["Endfinally"] = 10] = "Endfinally"; // Marks the end of a `finally` block
86499     })(OpCode || (OpCode = {}));
86500     // whether a generated code block is opening or closing at the current operation for a FunctionBuilder
86501     var BlockAction;
86502     (function (BlockAction) {
86503         BlockAction[BlockAction["Open"] = 0] = "Open";
86504         BlockAction[BlockAction["Close"] = 1] = "Close";
86505     })(BlockAction || (BlockAction = {}));
86506     // the kind for a generated code block in a FunctionBuilder
86507     var CodeBlockKind;
86508     (function (CodeBlockKind) {
86509         CodeBlockKind[CodeBlockKind["Exception"] = 0] = "Exception";
86510         CodeBlockKind[CodeBlockKind["With"] = 1] = "With";
86511         CodeBlockKind[CodeBlockKind["Switch"] = 2] = "Switch";
86512         CodeBlockKind[CodeBlockKind["Loop"] = 3] = "Loop";
86513         CodeBlockKind[CodeBlockKind["Labeled"] = 4] = "Labeled";
86514     })(CodeBlockKind || (CodeBlockKind = {}));
86515     // the state for a generated code exception block
86516     var ExceptionBlockState;
86517     (function (ExceptionBlockState) {
86518         ExceptionBlockState[ExceptionBlockState["Try"] = 0] = "Try";
86519         ExceptionBlockState[ExceptionBlockState["Catch"] = 1] = "Catch";
86520         ExceptionBlockState[ExceptionBlockState["Finally"] = 2] = "Finally";
86521         ExceptionBlockState[ExceptionBlockState["Done"] = 3] = "Done";
86522     })(ExceptionBlockState || (ExceptionBlockState = {}));
86523     // NOTE: changes to this enum should be reflected in the __generator helper.
86524     var Instruction;
86525     (function (Instruction) {
86526         Instruction[Instruction["Next"] = 0] = "Next";
86527         Instruction[Instruction["Throw"] = 1] = "Throw";
86528         Instruction[Instruction["Return"] = 2] = "Return";
86529         Instruction[Instruction["Break"] = 3] = "Break";
86530         Instruction[Instruction["Yield"] = 4] = "Yield";
86531         Instruction[Instruction["YieldStar"] = 5] = "YieldStar";
86532         Instruction[Instruction["Catch"] = 6] = "Catch";
86533         Instruction[Instruction["Endfinally"] = 7] = "Endfinally";
86534     })(Instruction || (Instruction = {}));
86535     function getInstructionName(instruction) {
86536         switch (instruction) {
86537             case 2 /* Return */: return "return";
86538             case 3 /* Break */: return "break";
86539             case 4 /* Yield */: return "yield";
86540             case 5 /* YieldStar */: return "yield*";
86541             case 7 /* Endfinally */: return "endfinally";
86542             default: return undefined; // TODO: GH#18217
86543         }
86544     }
86545     function transformGenerators(context) {
86546         var resumeLexicalEnvironment = context.resumeLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistFunctionDeclaration = context.hoistFunctionDeclaration, hoistVariableDeclaration = context.hoistVariableDeclaration;
86547         var compilerOptions = context.getCompilerOptions();
86548         var languageVersion = ts.getEmitScriptTarget(compilerOptions);
86549         var resolver = context.getEmitResolver();
86550         var previousOnSubstituteNode = context.onSubstituteNode;
86551         context.onSubstituteNode = onSubstituteNode;
86552         var renamedCatchVariables;
86553         var renamedCatchVariableDeclarations;
86554         var inGeneratorFunctionBody;
86555         var inStatementContainingYield;
86556         // The following three arrays store information about generated code blocks.
86557         // All three arrays are correlated by their index. This approach is used over allocating
86558         // objects to store the same information to avoid GC overhead.
86559         //
86560         var blocks; // Information about the code block
86561         var blockOffsets; // The operation offset at which a code block begins or ends
86562         var blockActions; // Whether the code block is opened or closed
86563         var blockStack; // A stack of currently open code blocks
86564         // Labels are used to mark locations in the code that can be the target of a Break (jump)
86565         // operation. These are translated into case clauses in a switch statement.
86566         // The following two arrays are correlated by their index. This approach is used over
86567         // allocating objects to store the same information to avoid GC overhead.
86568         //
86569         var labelOffsets; // The operation offset at which the label is defined.
86570         var labelExpressions; // The NumericLiteral nodes bound to each label.
86571         var nextLabelId = 1; // The next label id to use.
86572         // Operations store information about generated code for the function body. This
86573         // Includes things like statements, assignments, breaks (jumps), and yields.
86574         // The following three arrays are correlated by their index. This approach is used over
86575         // allocating objects to store the same information to avoid GC overhead.
86576         //
86577         var operations; // The operation to perform.
86578         var operationArguments; // The arguments to the operation.
86579         var operationLocations; // The source map location for the operation.
86580         var state; // The name of the state object used by the generator at runtime.
86581         // The following variables store information used by the `build` function:
86582         //
86583         var blockIndex = 0; // The index of the current block.
86584         var labelNumber = 0; // The current label number.
86585         var labelNumbers;
86586         var lastOperationWasAbrupt; // Indicates whether the last operation was abrupt (break/continue).
86587         var lastOperationWasCompletion; // Indicates whether the last operation was a completion (return/throw).
86588         var clauses; // The case clauses generated for labels.
86589         var statements; // The statements for the current label.
86590         var exceptionBlockStack; // A stack of containing exception blocks.
86591         var currentExceptionBlock; // The current exception block.
86592         var withBlockStack; // A stack containing `with` blocks.
86593         return ts.chainBundle(transformSourceFile);
86594         function transformSourceFile(node) {
86595             if (node.isDeclarationFile || (node.transformFlags & 512 /* ContainsGenerator */) === 0) {
86596                 return node;
86597             }
86598             var visited = ts.visitEachChild(node, visitor, context);
86599             ts.addEmitHelpers(visited, context.readEmitHelpers());
86600             return visited;
86601         }
86602         /**
86603          * Visits a node.
86604          *
86605          * @param node The node to visit.
86606          */
86607         function visitor(node) {
86608             var transformFlags = node.transformFlags;
86609             if (inStatementContainingYield) {
86610                 return visitJavaScriptInStatementContainingYield(node);
86611             }
86612             else if (inGeneratorFunctionBody) {
86613                 return visitJavaScriptInGeneratorFunctionBody(node);
86614             }
86615             else if (ts.isFunctionLikeDeclaration(node) && node.asteriskToken) {
86616                 return visitGenerator(node);
86617             }
86618             else if (transformFlags & 512 /* ContainsGenerator */) {
86619                 return ts.visitEachChild(node, visitor, context);
86620             }
86621             else {
86622                 return node;
86623             }
86624         }
86625         /**
86626          * Visits a node that is contained within a statement that contains yield.
86627          *
86628          * @param node The node to visit.
86629          */
86630         function visitJavaScriptInStatementContainingYield(node) {
86631             switch (node.kind) {
86632                 case 228 /* DoStatement */:
86633                     return visitDoStatement(node);
86634                 case 229 /* WhileStatement */:
86635                     return visitWhileStatement(node);
86636                 case 237 /* SwitchStatement */:
86637                     return visitSwitchStatement(node);
86638                 case 238 /* LabeledStatement */:
86639                     return visitLabeledStatement(node);
86640                 default:
86641                     return visitJavaScriptInGeneratorFunctionBody(node);
86642             }
86643         }
86644         /**
86645          * Visits a node that is contained within a generator function.
86646          *
86647          * @param node The node to visit.
86648          */
86649         function visitJavaScriptInGeneratorFunctionBody(node) {
86650             switch (node.kind) {
86651                 case 244 /* FunctionDeclaration */:
86652                     return visitFunctionDeclaration(node);
86653                 case 201 /* FunctionExpression */:
86654                     return visitFunctionExpression(node);
86655                 case 163 /* GetAccessor */:
86656                 case 164 /* SetAccessor */:
86657                     return visitAccessorDeclaration(node);
86658                 case 225 /* VariableStatement */:
86659                     return visitVariableStatement(node);
86660                 case 230 /* ForStatement */:
86661                     return visitForStatement(node);
86662                 case 231 /* ForInStatement */:
86663                     return visitForInStatement(node);
86664                 case 234 /* BreakStatement */:
86665                     return visitBreakStatement(node);
86666                 case 233 /* ContinueStatement */:
86667                     return visitContinueStatement(node);
86668                 case 235 /* ReturnStatement */:
86669                     return visitReturnStatement(node);
86670                 default:
86671                     if (node.transformFlags & 262144 /* ContainsYield */) {
86672                         return visitJavaScriptContainingYield(node);
86673                     }
86674                     else if (node.transformFlags & (512 /* ContainsGenerator */ | 1048576 /* ContainsHoistedDeclarationOrCompletion */)) {
86675                         return ts.visitEachChild(node, visitor, context);
86676                     }
86677                     else {
86678                         return node;
86679                     }
86680             }
86681         }
86682         /**
86683          * Visits a node that contains a YieldExpression.
86684          *
86685          * @param node The node to visit.
86686          */
86687         function visitJavaScriptContainingYield(node) {
86688             switch (node.kind) {
86689                 case 209 /* BinaryExpression */:
86690                     return visitBinaryExpression(node);
86691                 case 210 /* ConditionalExpression */:
86692                     return visitConditionalExpression(node);
86693                 case 212 /* YieldExpression */:
86694                     return visitYieldExpression(node);
86695                 case 192 /* ArrayLiteralExpression */:
86696                     return visitArrayLiteralExpression(node);
86697                 case 193 /* ObjectLiteralExpression */:
86698                     return visitObjectLiteralExpression(node);
86699                 case 195 /* ElementAccessExpression */:
86700                     return visitElementAccessExpression(node);
86701                 case 196 /* CallExpression */:
86702                     return visitCallExpression(node);
86703                 case 197 /* NewExpression */:
86704                     return visitNewExpression(node);
86705                 default:
86706                     return ts.visitEachChild(node, visitor, context);
86707             }
86708         }
86709         /**
86710          * Visits a generator function.
86711          *
86712          * @param node The node to visit.
86713          */
86714         function visitGenerator(node) {
86715             switch (node.kind) {
86716                 case 244 /* FunctionDeclaration */:
86717                     return visitFunctionDeclaration(node);
86718                 case 201 /* FunctionExpression */:
86719                     return visitFunctionExpression(node);
86720                 default:
86721                     return ts.Debug.failBadSyntaxKind(node);
86722             }
86723         }
86724         /**
86725          * Visits a function declaration.
86726          *
86727          * This will be called when one of the following conditions are met:
86728          * - The function declaration is a generator function.
86729          * - The function declaration is contained within the body of a generator function.
86730          *
86731          * @param node The node to visit.
86732          */
86733         function visitFunctionDeclaration(node) {
86734             // Currently, we only support generators that were originally async functions.
86735             if (node.asteriskToken) {
86736                 node = ts.setOriginalNode(ts.setTextRange(ts.createFunctionDeclaration(
86737                 /*decorators*/ undefined, node.modifiers, 
86738                 /*asteriskToken*/ undefined, node.name, 
86739                 /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), 
86740                 /*type*/ undefined, transformGeneratorFunctionBody(node.body)), 
86741                 /*location*/ node), node);
86742             }
86743             else {
86744                 var savedInGeneratorFunctionBody = inGeneratorFunctionBody;
86745                 var savedInStatementContainingYield = inStatementContainingYield;
86746                 inGeneratorFunctionBody = false;
86747                 inStatementContainingYield = false;
86748                 node = ts.visitEachChild(node, visitor, context);
86749                 inGeneratorFunctionBody = savedInGeneratorFunctionBody;
86750                 inStatementContainingYield = savedInStatementContainingYield;
86751             }
86752             if (inGeneratorFunctionBody) {
86753                 // Function declarations in a generator function body are hoisted
86754                 // to the top of the lexical scope and elided from the current statement.
86755                 hoistFunctionDeclaration(node);
86756                 return undefined;
86757             }
86758             else {
86759                 return node;
86760             }
86761         }
86762         /**
86763          * Visits a function expression.
86764          *
86765          * This will be called when one of the following conditions are met:
86766          * - The function expression is a generator function.
86767          * - The function expression is contained within the body of a generator function.
86768          *
86769          * @param node The node to visit.
86770          */
86771         function visitFunctionExpression(node) {
86772             // Currently, we only support generators that were originally async functions.
86773             if (node.asteriskToken) {
86774                 node = ts.setOriginalNode(ts.setTextRange(ts.createFunctionExpression(
86775                 /*modifiers*/ undefined, 
86776                 /*asteriskToken*/ undefined, node.name, 
86777                 /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), 
86778                 /*type*/ undefined, transformGeneratorFunctionBody(node.body)), 
86779                 /*location*/ node), node);
86780             }
86781             else {
86782                 var savedInGeneratorFunctionBody = inGeneratorFunctionBody;
86783                 var savedInStatementContainingYield = inStatementContainingYield;
86784                 inGeneratorFunctionBody = false;
86785                 inStatementContainingYield = false;
86786                 node = ts.visitEachChild(node, visitor, context);
86787                 inGeneratorFunctionBody = savedInGeneratorFunctionBody;
86788                 inStatementContainingYield = savedInStatementContainingYield;
86789             }
86790             return node;
86791         }
86792         /**
86793          * Visits a get or set accessor declaration.
86794          *
86795          * This will be called when one of the following conditions are met:
86796          * - The accessor is contained within the body of a generator function.
86797          *
86798          * @param node The node to visit.
86799          */
86800         function visitAccessorDeclaration(node) {
86801             var savedInGeneratorFunctionBody = inGeneratorFunctionBody;
86802             var savedInStatementContainingYield = inStatementContainingYield;
86803             inGeneratorFunctionBody = false;
86804             inStatementContainingYield = false;
86805             node = ts.visitEachChild(node, visitor, context);
86806             inGeneratorFunctionBody = savedInGeneratorFunctionBody;
86807             inStatementContainingYield = savedInStatementContainingYield;
86808             return node;
86809         }
86810         /**
86811          * Transforms the body of a generator function declaration.
86812          *
86813          * @param node The function body to transform.
86814          */
86815         function transformGeneratorFunctionBody(body) {
86816             // Save existing generator state
86817             var statements = [];
86818             var savedInGeneratorFunctionBody = inGeneratorFunctionBody;
86819             var savedInStatementContainingYield = inStatementContainingYield;
86820             var savedBlocks = blocks;
86821             var savedBlockOffsets = blockOffsets;
86822             var savedBlockActions = blockActions;
86823             var savedBlockStack = blockStack;
86824             var savedLabelOffsets = labelOffsets;
86825             var savedLabelExpressions = labelExpressions;
86826             var savedNextLabelId = nextLabelId;
86827             var savedOperations = operations;
86828             var savedOperationArguments = operationArguments;
86829             var savedOperationLocations = operationLocations;
86830             var savedState = state;
86831             // Initialize generator state
86832             inGeneratorFunctionBody = true;
86833             inStatementContainingYield = false;
86834             blocks = undefined;
86835             blockOffsets = undefined;
86836             blockActions = undefined;
86837             blockStack = undefined;
86838             labelOffsets = undefined;
86839             labelExpressions = undefined;
86840             nextLabelId = 1;
86841             operations = undefined;
86842             operationArguments = undefined;
86843             operationLocations = undefined;
86844             state = ts.createTempVariable(/*recordTempVariable*/ undefined);
86845             // Build the generator
86846             resumeLexicalEnvironment();
86847             var statementOffset = ts.addPrologue(statements, body.statements, /*ensureUseStrict*/ false, visitor);
86848             transformAndEmitStatements(body.statements, statementOffset);
86849             var buildResult = build();
86850             ts.insertStatementsAfterStandardPrologue(statements, endLexicalEnvironment());
86851             statements.push(ts.createReturn(buildResult));
86852             // Restore previous generator state
86853             inGeneratorFunctionBody = savedInGeneratorFunctionBody;
86854             inStatementContainingYield = savedInStatementContainingYield;
86855             blocks = savedBlocks;
86856             blockOffsets = savedBlockOffsets;
86857             blockActions = savedBlockActions;
86858             blockStack = savedBlockStack;
86859             labelOffsets = savedLabelOffsets;
86860             labelExpressions = savedLabelExpressions;
86861             nextLabelId = savedNextLabelId;
86862             operations = savedOperations;
86863             operationArguments = savedOperationArguments;
86864             operationLocations = savedOperationLocations;
86865             state = savedState;
86866             return ts.setTextRange(ts.createBlock(statements, body.multiLine), body);
86867         }
86868         /**
86869          * Visits a variable statement.
86870          *
86871          * This will be called when one of the following conditions are met:
86872          * - The variable statement is contained within the body of a generator function.
86873          *
86874          * @param node The node to visit.
86875          */
86876         function visitVariableStatement(node) {
86877             if (node.transformFlags & 262144 /* ContainsYield */) {
86878                 transformAndEmitVariableDeclarationList(node.declarationList);
86879                 return undefined;
86880             }
86881             else {
86882                 // Do not hoist custom prologues.
86883                 if (ts.getEmitFlags(node) & 1048576 /* CustomPrologue */) {
86884                     return node;
86885                 }
86886                 for (var _i = 0, _a = node.declarationList.declarations; _i < _a.length; _i++) {
86887                     var variable = _a[_i];
86888                     hoistVariableDeclaration(variable.name);
86889                 }
86890                 var variables = ts.getInitializedVariables(node.declarationList);
86891                 if (variables.length === 0) {
86892                     return undefined;
86893                 }
86894                 return ts.setSourceMapRange(ts.createExpressionStatement(ts.inlineExpressions(ts.map(variables, transformInitializedVariable))), node);
86895             }
86896         }
86897         /**
86898          * Visits a binary expression.
86899          *
86900          * This will be called when one of the following conditions are met:
86901          * - The node contains a YieldExpression.
86902          *
86903          * @param node The node to visit.
86904          */
86905         function visitBinaryExpression(node) {
86906             var assoc = ts.getExpressionAssociativity(node);
86907             switch (assoc) {
86908                 case 0 /* Left */:
86909                     return visitLeftAssociativeBinaryExpression(node);
86910                 case 1 /* Right */:
86911                     return visitRightAssociativeBinaryExpression(node);
86912                 default:
86913                     return ts.Debug.assertNever(assoc);
86914             }
86915         }
86916         /**
86917          * Visits a right-associative binary expression containing `yield`.
86918          *
86919          * @param node The node to visit.
86920          */
86921         function visitRightAssociativeBinaryExpression(node) {
86922             var left = node.left, right = node.right;
86923             if (containsYield(right)) {
86924                 var target = void 0;
86925                 switch (left.kind) {
86926                     case 194 /* PropertyAccessExpression */:
86927                         // [source]
86928                         //      a.b = yield;
86929                         //
86930                         // [intermediate]
86931                         //  .local _a
86932                         //      _a = a;
86933                         //  .yield resumeLabel
86934                         //  .mark resumeLabel
86935                         //      _a.b = %sent%;
86936                         target = ts.updatePropertyAccess(left, cacheExpression(ts.visitNode(left.expression, visitor, ts.isLeftHandSideExpression)), left.name);
86937                         break;
86938                     case 195 /* ElementAccessExpression */:
86939                         // [source]
86940                         //      a[b] = yield;
86941                         //
86942                         // [intermediate]
86943                         //  .local _a, _b
86944                         //      _a = a;
86945                         //      _b = b;
86946                         //  .yield resumeLabel
86947                         //  .mark resumeLabel
86948                         //      _a[_b] = %sent%;
86949                         target = ts.updateElementAccess(left, cacheExpression(ts.visitNode(left.expression, visitor, ts.isLeftHandSideExpression)), cacheExpression(ts.visitNode(left.argumentExpression, visitor, ts.isExpression)));
86950                         break;
86951                     default:
86952                         target = ts.visitNode(left, visitor, ts.isExpression);
86953                         break;
86954                 }
86955                 var operator = node.operatorToken.kind;
86956                 if (ts.isCompoundAssignment(operator)) {
86957                     return ts.setTextRange(ts.createAssignment(target, ts.setTextRange(ts.createBinary(cacheExpression(target), ts.getNonAssignmentOperatorForCompoundAssignment(operator), ts.visitNode(right, visitor, ts.isExpression)), node)), node);
86958                 }
86959                 else {
86960                     return ts.updateBinary(node, target, ts.visitNode(right, visitor, ts.isExpression));
86961                 }
86962             }
86963             return ts.visitEachChild(node, visitor, context);
86964         }
86965         function visitLeftAssociativeBinaryExpression(node) {
86966             if (containsYield(node.right)) {
86967                 if (ts.isLogicalOperator(node.operatorToken.kind)) {
86968                     return visitLogicalBinaryExpression(node);
86969                 }
86970                 else if (node.operatorToken.kind === 27 /* CommaToken */) {
86971                     return visitCommaExpression(node);
86972                 }
86973                 // [source]
86974                 //      a() + (yield) + c()
86975                 //
86976                 // [intermediate]
86977                 //  .local _a
86978                 //      _a = a();
86979                 //  .yield resumeLabel
86980                 //      _a + %sent% + c()
86981                 var clone_6 = ts.getMutableClone(node);
86982                 clone_6.left = cacheExpression(ts.visitNode(node.left, visitor, ts.isExpression));
86983                 clone_6.right = ts.visitNode(node.right, visitor, ts.isExpression);
86984                 return clone_6;
86985             }
86986             return ts.visitEachChild(node, visitor, context);
86987         }
86988         /**
86989          * Visits a logical binary expression containing `yield`.
86990          *
86991          * @param node A node to visit.
86992          */
86993         function visitLogicalBinaryExpression(node) {
86994             // Logical binary expressions (`&&` and `||`) are shortcutting expressions and need
86995             // to be transformed as such:
86996             //
86997             // [source]
86998             //      x = a() && yield;
86999             //
87000             // [intermediate]
87001             //  .local _a
87002             //      _a = a();
87003             //  .brfalse resultLabel, (_a)
87004             //  .yield resumeLabel
87005             //  .mark resumeLabel
87006             //      _a = %sent%;
87007             //  .mark resultLabel
87008             //      x = _a;
87009             //
87010             // [source]
87011             //      x = a() || yield;
87012             //
87013             // [intermediate]
87014             //  .local _a
87015             //      _a = a();
87016             //  .brtrue resultLabel, (_a)
87017             //  .yield resumeLabel
87018             //  .mark resumeLabel
87019             //      _a = %sent%;
87020             //  .mark resultLabel
87021             //      x = _a;
87022             var resultLabel = defineLabel();
87023             var resultLocal = declareLocal();
87024             emitAssignment(resultLocal, ts.visitNode(node.left, visitor, ts.isExpression), /*location*/ node.left);
87025             if (node.operatorToken.kind === 55 /* AmpersandAmpersandToken */) {
87026                 // Logical `&&` shortcuts when the left-hand operand is falsey.
87027                 emitBreakWhenFalse(resultLabel, resultLocal, /*location*/ node.left);
87028             }
87029             else {
87030                 // Logical `||` shortcuts when the left-hand operand is truthy.
87031                 emitBreakWhenTrue(resultLabel, resultLocal, /*location*/ node.left);
87032             }
87033             emitAssignment(resultLocal, ts.visitNode(node.right, visitor, ts.isExpression), /*location*/ node.right);
87034             markLabel(resultLabel);
87035             return resultLocal;
87036         }
87037         /**
87038          * Visits a comma expression containing `yield`.
87039          *
87040          * @param node The node to visit.
87041          */
87042         function visitCommaExpression(node) {
87043             // [source]
87044             //      x = a(), yield, b();
87045             //
87046             // [intermediate]
87047             //      a();
87048             //  .yield resumeLabel
87049             //  .mark resumeLabel
87050             //      x = %sent%, b();
87051             var pendingExpressions = [];
87052             visit(node.left);
87053             visit(node.right);
87054             return ts.inlineExpressions(pendingExpressions);
87055             function visit(node) {
87056                 if (ts.isBinaryExpression(node) && node.operatorToken.kind === 27 /* CommaToken */) {
87057                     visit(node.left);
87058                     visit(node.right);
87059                 }
87060                 else {
87061                     if (containsYield(node) && pendingExpressions.length > 0) {
87062                         emitWorker(1 /* Statement */, [ts.createExpressionStatement(ts.inlineExpressions(pendingExpressions))]);
87063                         pendingExpressions = [];
87064                     }
87065                     pendingExpressions.push(ts.visitNode(node, visitor, ts.isExpression));
87066                 }
87067             }
87068         }
87069         /**
87070          * Visits a conditional expression containing `yield`.
87071          *
87072          * @param node The node to visit.
87073          */
87074         function visitConditionalExpression(node) {
87075             // [source]
87076             //      x = a() ? yield : b();
87077             //
87078             // [intermediate]
87079             //  .local _a
87080             //  .brfalse whenFalseLabel, (a())
87081             //  .yield resumeLabel
87082             //  .mark resumeLabel
87083             //      _a = %sent%;
87084             //  .br resultLabel
87085             //  .mark whenFalseLabel
87086             //      _a = b();
87087             //  .mark resultLabel
87088             //      x = _a;
87089             // We only need to perform a specific transformation if a `yield` expression exists
87090             // in either the `whenTrue` or `whenFalse` branches.
87091             // A `yield` in the condition will be handled by the normal visitor.
87092             if (containsYield(node.whenTrue) || containsYield(node.whenFalse)) {
87093                 var whenFalseLabel = defineLabel();
87094                 var resultLabel = defineLabel();
87095                 var resultLocal = declareLocal();
87096                 emitBreakWhenFalse(whenFalseLabel, ts.visitNode(node.condition, visitor, ts.isExpression), /*location*/ node.condition);
87097                 emitAssignment(resultLocal, ts.visitNode(node.whenTrue, visitor, ts.isExpression), /*location*/ node.whenTrue);
87098                 emitBreak(resultLabel);
87099                 markLabel(whenFalseLabel);
87100                 emitAssignment(resultLocal, ts.visitNode(node.whenFalse, visitor, ts.isExpression), /*location*/ node.whenFalse);
87101                 markLabel(resultLabel);
87102                 return resultLocal;
87103             }
87104             return ts.visitEachChild(node, visitor, context);
87105         }
87106         /**
87107          * Visits a `yield` expression.
87108          *
87109          * @param node The node to visit.
87110          */
87111         function visitYieldExpression(node) {
87112             // [source]
87113             //      x = yield a();
87114             //
87115             // [intermediate]
87116             //  .yield resumeLabel, (a())
87117             //  .mark resumeLabel
87118             //      x = %sent%;
87119             var resumeLabel = defineLabel();
87120             var expression = ts.visitNode(node.expression, visitor, ts.isExpression);
87121             if (node.asteriskToken) {
87122                 var iterator = (ts.getEmitFlags(node.expression) & 8388608 /* Iterator */) === 0
87123                     ? ts.createValuesHelper(context, expression, /*location*/ node)
87124                     : expression;
87125                 emitYieldStar(iterator, /*location*/ node);
87126             }
87127             else {
87128                 emitYield(expression, /*location*/ node);
87129             }
87130             markLabel(resumeLabel);
87131             return createGeneratorResume(/*location*/ node);
87132         }
87133         /**
87134          * Visits an ArrayLiteralExpression that contains a YieldExpression.
87135          *
87136          * @param node The node to visit.
87137          */
87138         function visitArrayLiteralExpression(node) {
87139             return visitElements(node.elements, /*leadingElement*/ undefined, /*location*/ undefined, node.multiLine);
87140         }
87141         /**
87142          * Visits an array of expressions containing one or more YieldExpression nodes
87143          * and returns an expression for the resulting value.
87144          *
87145          * @param elements The elements to visit.
87146          * @param multiLine Whether array literals created should be emitted on multiple lines.
87147          */
87148         function visitElements(elements, leadingElement, location, multiLine) {
87149             // [source]
87150             //      ar = [1, yield, 2];
87151             //
87152             // [intermediate]
87153             //  .local _a
87154             //      _a = [1];
87155             //  .yield resumeLabel
87156             //  .mark resumeLabel
87157             //      ar = _a.concat([%sent%, 2]);
87158             var numInitialElements = countInitialNodesWithoutYield(elements);
87159             var temp;
87160             if (numInitialElements > 0) {
87161                 temp = declareLocal();
87162                 var initialElements = ts.visitNodes(elements, visitor, ts.isExpression, 0, numInitialElements);
87163                 emitAssignment(temp, ts.createArrayLiteral(leadingElement
87164                     ? __spreadArrays([leadingElement], initialElements) : initialElements));
87165                 leadingElement = undefined;
87166             }
87167             var expressions = ts.reduceLeft(elements, reduceElement, [], numInitialElements);
87168             return temp
87169                 ? ts.createArrayConcat(temp, [ts.createArrayLiteral(expressions, multiLine)])
87170                 : ts.setTextRange(ts.createArrayLiteral(leadingElement ? __spreadArrays([leadingElement], expressions) : expressions, multiLine), location);
87171             function reduceElement(expressions, element) {
87172                 if (containsYield(element) && expressions.length > 0) {
87173                     var hasAssignedTemp = temp !== undefined;
87174                     if (!temp) {
87175                         temp = declareLocal();
87176                     }
87177                     emitAssignment(temp, hasAssignedTemp
87178                         ? ts.createArrayConcat(temp, [ts.createArrayLiteral(expressions, multiLine)])
87179                         : ts.createArrayLiteral(leadingElement ? __spreadArrays([leadingElement], expressions) : expressions, multiLine));
87180                     leadingElement = undefined;
87181                     expressions = [];
87182                 }
87183                 expressions.push(ts.visitNode(element, visitor, ts.isExpression));
87184                 return expressions;
87185             }
87186         }
87187         function visitObjectLiteralExpression(node) {
87188             // [source]
87189             //      o = {
87190             //          a: 1,
87191             //          b: yield,
87192             //          c: 2
87193             //      };
87194             //
87195             // [intermediate]
87196             //  .local _a
87197             //      _a = {
87198             //          a: 1
87199             //      };
87200             //  .yield resumeLabel
87201             //  .mark resumeLabel
87202             //      o = (_a.b = %sent%,
87203             //          _a.c = 2,
87204             //          _a);
87205             var properties = node.properties;
87206             var multiLine = node.multiLine;
87207             var numInitialProperties = countInitialNodesWithoutYield(properties);
87208             var temp = declareLocal();
87209             emitAssignment(temp, ts.createObjectLiteral(ts.visitNodes(properties, visitor, ts.isObjectLiteralElementLike, 0, numInitialProperties), multiLine));
87210             var expressions = ts.reduceLeft(properties, reduceProperty, [], numInitialProperties);
87211             expressions.push(multiLine ? ts.startOnNewLine(ts.getMutableClone(temp)) : temp);
87212             return ts.inlineExpressions(expressions);
87213             function reduceProperty(expressions, property) {
87214                 if (containsYield(property) && expressions.length > 0) {
87215                     emitStatement(ts.createExpressionStatement(ts.inlineExpressions(expressions)));
87216                     expressions = [];
87217                 }
87218                 var expression = ts.createExpressionForObjectLiteralElementLike(node, property, temp);
87219                 var visited = ts.visitNode(expression, visitor, ts.isExpression);
87220                 if (visited) {
87221                     if (multiLine) {
87222                         ts.startOnNewLine(visited);
87223                     }
87224                     expressions.push(visited);
87225                 }
87226                 return expressions;
87227             }
87228         }
87229         /**
87230          * Visits an ElementAccessExpression that contains a YieldExpression.
87231          *
87232          * @param node The node to visit.
87233          */
87234         function visitElementAccessExpression(node) {
87235             if (containsYield(node.argumentExpression)) {
87236                 // [source]
87237                 //      a = x[yield];
87238                 //
87239                 // [intermediate]
87240                 //  .local _a
87241                 //      _a = x;
87242                 //  .yield resumeLabel
87243                 //  .mark resumeLabel
87244                 //      a = _a[%sent%]
87245                 var clone_7 = ts.getMutableClone(node);
87246                 clone_7.expression = cacheExpression(ts.visitNode(node.expression, visitor, ts.isLeftHandSideExpression));
87247                 clone_7.argumentExpression = ts.visitNode(node.argumentExpression, visitor, ts.isExpression);
87248                 return clone_7;
87249             }
87250             return ts.visitEachChild(node, visitor, context);
87251         }
87252         function visitCallExpression(node) {
87253             if (!ts.isImportCall(node) && ts.forEach(node.arguments, containsYield)) {
87254                 // [source]
87255                 //      a.b(1, yield, 2);
87256                 //
87257                 // [intermediate]
87258                 //  .local _a, _b, _c
87259                 //      _b = (_a = a).b;
87260                 //      _c = [1];
87261                 //  .yield resumeLabel
87262                 //  .mark resumeLabel
87263                 //      _b.apply(_a, _c.concat([%sent%, 2]));
87264                 var _a = ts.createCallBinding(node.expression, hoistVariableDeclaration, languageVersion, /*cacheIdentifiers*/ true), target = _a.target, thisArg = _a.thisArg;
87265                 return ts.setOriginalNode(ts.createFunctionApply(cacheExpression(ts.visitNode(target, visitor, ts.isLeftHandSideExpression)), thisArg, visitElements(node.arguments), 
87266                 /*location*/ node), node);
87267             }
87268             return ts.visitEachChild(node, visitor, context);
87269         }
87270         function visitNewExpression(node) {
87271             if (ts.forEach(node.arguments, containsYield)) {
87272                 // [source]
87273                 //      new a.b(1, yield, 2);
87274                 //
87275                 // [intermediate]
87276                 //  .local _a, _b, _c
87277                 //      _b = (_a = a.b).bind;
87278                 //      _c = [1];
87279                 //  .yield resumeLabel
87280                 //  .mark resumeLabel
87281                 //      new (_b.apply(_a, _c.concat([%sent%, 2])));
87282                 var _a = ts.createCallBinding(ts.createPropertyAccess(node.expression, "bind"), hoistVariableDeclaration), target = _a.target, thisArg = _a.thisArg;
87283                 return ts.setOriginalNode(ts.setTextRange(ts.createNew(ts.createFunctionApply(cacheExpression(ts.visitNode(target, visitor, ts.isExpression)), thisArg, visitElements(node.arguments, 
87284                 /*leadingElement*/ ts.createVoidZero())), 
87285                 /*typeArguments*/ undefined, []), node), node);
87286             }
87287             return ts.visitEachChild(node, visitor, context);
87288         }
87289         function transformAndEmitStatements(statements, start) {
87290             if (start === void 0) { start = 0; }
87291             var numStatements = statements.length;
87292             for (var i = start; i < numStatements; i++) {
87293                 transformAndEmitStatement(statements[i]);
87294             }
87295         }
87296         function transformAndEmitEmbeddedStatement(node) {
87297             if (ts.isBlock(node)) {
87298                 transformAndEmitStatements(node.statements);
87299             }
87300             else {
87301                 transformAndEmitStatement(node);
87302             }
87303         }
87304         function transformAndEmitStatement(node) {
87305             var savedInStatementContainingYield = inStatementContainingYield;
87306             if (!inStatementContainingYield) {
87307                 inStatementContainingYield = containsYield(node);
87308             }
87309             transformAndEmitStatementWorker(node);
87310             inStatementContainingYield = savedInStatementContainingYield;
87311         }
87312         function transformAndEmitStatementWorker(node) {
87313             switch (node.kind) {
87314                 case 223 /* Block */:
87315                     return transformAndEmitBlock(node);
87316                 case 226 /* ExpressionStatement */:
87317                     return transformAndEmitExpressionStatement(node);
87318                 case 227 /* IfStatement */:
87319                     return transformAndEmitIfStatement(node);
87320                 case 228 /* DoStatement */:
87321                     return transformAndEmitDoStatement(node);
87322                 case 229 /* WhileStatement */:
87323                     return transformAndEmitWhileStatement(node);
87324                 case 230 /* ForStatement */:
87325                     return transformAndEmitForStatement(node);
87326                 case 231 /* ForInStatement */:
87327                     return transformAndEmitForInStatement(node);
87328                 case 233 /* ContinueStatement */:
87329                     return transformAndEmitContinueStatement(node);
87330                 case 234 /* BreakStatement */:
87331                     return transformAndEmitBreakStatement(node);
87332                 case 235 /* ReturnStatement */:
87333                     return transformAndEmitReturnStatement(node);
87334                 case 236 /* WithStatement */:
87335                     return transformAndEmitWithStatement(node);
87336                 case 237 /* SwitchStatement */:
87337                     return transformAndEmitSwitchStatement(node);
87338                 case 238 /* LabeledStatement */:
87339                     return transformAndEmitLabeledStatement(node);
87340                 case 239 /* ThrowStatement */:
87341                     return transformAndEmitThrowStatement(node);
87342                 case 240 /* TryStatement */:
87343                     return transformAndEmitTryStatement(node);
87344                 default:
87345                     return emitStatement(ts.visitNode(node, visitor, ts.isStatement));
87346             }
87347         }
87348         function transformAndEmitBlock(node) {
87349             if (containsYield(node)) {
87350                 transformAndEmitStatements(node.statements);
87351             }
87352             else {
87353                 emitStatement(ts.visitNode(node, visitor, ts.isStatement));
87354             }
87355         }
87356         function transformAndEmitExpressionStatement(node) {
87357             emitStatement(ts.visitNode(node, visitor, ts.isStatement));
87358         }
87359         function transformAndEmitVariableDeclarationList(node) {
87360             for (var _i = 0, _a = node.declarations; _i < _a.length; _i++) {
87361                 var variable = _a[_i];
87362                 var name = ts.getSynthesizedClone(variable.name);
87363                 ts.setCommentRange(name, variable.name);
87364                 hoistVariableDeclaration(name);
87365             }
87366             var variables = ts.getInitializedVariables(node);
87367             var numVariables = variables.length;
87368             var variablesWritten = 0;
87369             var pendingExpressions = [];
87370             while (variablesWritten < numVariables) {
87371                 for (var i = variablesWritten; i < numVariables; i++) {
87372                     var variable = variables[i];
87373                     if (containsYield(variable.initializer) && pendingExpressions.length > 0) {
87374                         break;
87375                     }
87376                     pendingExpressions.push(transformInitializedVariable(variable));
87377                 }
87378                 if (pendingExpressions.length) {
87379                     emitStatement(ts.createExpressionStatement(ts.inlineExpressions(pendingExpressions)));
87380                     variablesWritten += pendingExpressions.length;
87381                     pendingExpressions = [];
87382                 }
87383             }
87384             return undefined;
87385         }
87386         function transformInitializedVariable(node) {
87387             return ts.setSourceMapRange(ts.createAssignment(ts.setSourceMapRange(ts.getSynthesizedClone(node.name), node.name), ts.visitNode(node.initializer, visitor, ts.isExpression)), node);
87388         }
87389         function transformAndEmitIfStatement(node) {
87390             if (containsYield(node)) {
87391                 // [source]
87392                 //      if (x)
87393                 //          /*thenStatement*/
87394                 //      else
87395                 //          /*elseStatement*/
87396                 //
87397                 // [intermediate]
87398                 //  .brfalse elseLabel, (x)
87399                 //      /*thenStatement*/
87400                 //  .br endLabel
87401                 //  .mark elseLabel
87402                 //      /*elseStatement*/
87403                 //  .mark endLabel
87404                 if (containsYield(node.thenStatement) || containsYield(node.elseStatement)) {
87405                     var endLabel = defineLabel();
87406                     var elseLabel = node.elseStatement ? defineLabel() : undefined;
87407                     emitBreakWhenFalse(node.elseStatement ? elseLabel : endLabel, ts.visitNode(node.expression, visitor, ts.isExpression), /*location*/ node.expression);
87408                     transformAndEmitEmbeddedStatement(node.thenStatement);
87409                     if (node.elseStatement) {
87410                         emitBreak(endLabel);
87411                         markLabel(elseLabel);
87412                         transformAndEmitEmbeddedStatement(node.elseStatement);
87413                     }
87414                     markLabel(endLabel);
87415                 }
87416                 else {
87417                     emitStatement(ts.visitNode(node, visitor, ts.isStatement));
87418                 }
87419             }
87420             else {
87421                 emitStatement(ts.visitNode(node, visitor, ts.isStatement));
87422             }
87423         }
87424         function transformAndEmitDoStatement(node) {
87425             if (containsYield(node)) {
87426                 // [source]
87427                 //      do {
87428                 //          /*body*/
87429                 //      }
87430                 //      while (i < 10);
87431                 //
87432                 // [intermediate]
87433                 //  .loop conditionLabel, endLabel
87434                 //  .mark loopLabel
87435                 //      /*body*/
87436                 //  .mark conditionLabel
87437                 //  .brtrue loopLabel, (i < 10)
87438                 //  .endloop
87439                 //  .mark endLabel
87440                 var conditionLabel = defineLabel();
87441                 var loopLabel = defineLabel();
87442                 beginLoopBlock(/*continueLabel*/ conditionLabel);
87443                 markLabel(loopLabel);
87444                 transformAndEmitEmbeddedStatement(node.statement);
87445                 markLabel(conditionLabel);
87446                 emitBreakWhenTrue(loopLabel, ts.visitNode(node.expression, visitor, ts.isExpression));
87447                 endLoopBlock();
87448             }
87449             else {
87450                 emitStatement(ts.visitNode(node, visitor, ts.isStatement));
87451             }
87452         }
87453         function visitDoStatement(node) {
87454             if (inStatementContainingYield) {
87455                 beginScriptLoopBlock();
87456                 node = ts.visitEachChild(node, visitor, context);
87457                 endLoopBlock();
87458                 return node;
87459             }
87460             else {
87461                 return ts.visitEachChild(node, visitor, context);
87462             }
87463         }
87464         function transformAndEmitWhileStatement(node) {
87465             if (containsYield(node)) {
87466                 // [source]
87467                 //      while (i < 10) {
87468                 //          /*body*/
87469                 //      }
87470                 //
87471                 // [intermediate]
87472                 //  .loop loopLabel, endLabel
87473                 //  .mark loopLabel
87474                 //  .brfalse endLabel, (i < 10)
87475                 //      /*body*/
87476                 //  .br loopLabel
87477                 //  .endloop
87478                 //  .mark endLabel
87479                 var loopLabel = defineLabel();
87480                 var endLabel = beginLoopBlock(loopLabel);
87481                 markLabel(loopLabel);
87482                 emitBreakWhenFalse(endLabel, ts.visitNode(node.expression, visitor, ts.isExpression));
87483                 transformAndEmitEmbeddedStatement(node.statement);
87484                 emitBreak(loopLabel);
87485                 endLoopBlock();
87486             }
87487             else {
87488                 emitStatement(ts.visitNode(node, visitor, ts.isStatement));
87489             }
87490         }
87491         function visitWhileStatement(node) {
87492             if (inStatementContainingYield) {
87493                 beginScriptLoopBlock();
87494                 node = ts.visitEachChild(node, visitor, context);
87495                 endLoopBlock();
87496                 return node;
87497             }
87498             else {
87499                 return ts.visitEachChild(node, visitor, context);
87500             }
87501         }
87502         function transformAndEmitForStatement(node) {
87503             if (containsYield(node)) {
87504                 // [source]
87505                 //      for (var i = 0; i < 10; i++) {
87506                 //          /*body*/
87507                 //      }
87508                 //
87509                 // [intermediate]
87510                 //  .local i
87511                 //      i = 0;
87512                 //  .loop incrementLabel, endLoopLabel
87513                 //  .mark conditionLabel
87514                 //  .brfalse endLoopLabel, (i < 10)
87515                 //      /*body*/
87516                 //  .mark incrementLabel
87517                 //      i++;
87518                 //  .br conditionLabel
87519                 //  .endloop
87520                 //  .mark endLoopLabel
87521                 var conditionLabel = defineLabel();
87522                 var incrementLabel = defineLabel();
87523                 var endLabel = beginLoopBlock(incrementLabel);
87524                 if (node.initializer) {
87525                     var initializer = node.initializer;
87526                     if (ts.isVariableDeclarationList(initializer)) {
87527                         transformAndEmitVariableDeclarationList(initializer);
87528                     }
87529                     else {
87530                         emitStatement(ts.setTextRange(ts.createExpressionStatement(ts.visitNode(initializer, visitor, ts.isExpression)), initializer));
87531                     }
87532                 }
87533                 markLabel(conditionLabel);
87534                 if (node.condition) {
87535                     emitBreakWhenFalse(endLabel, ts.visitNode(node.condition, visitor, ts.isExpression));
87536                 }
87537                 transformAndEmitEmbeddedStatement(node.statement);
87538                 markLabel(incrementLabel);
87539                 if (node.incrementor) {
87540                     emitStatement(ts.setTextRange(ts.createExpressionStatement(ts.visitNode(node.incrementor, visitor, ts.isExpression)), node.incrementor));
87541                 }
87542                 emitBreak(conditionLabel);
87543                 endLoopBlock();
87544             }
87545             else {
87546                 emitStatement(ts.visitNode(node, visitor, ts.isStatement));
87547             }
87548         }
87549         function visitForStatement(node) {
87550             if (inStatementContainingYield) {
87551                 beginScriptLoopBlock();
87552             }
87553             var initializer = node.initializer;
87554             if (initializer && ts.isVariableDeclarationList(initializer)) {
87555                 for (var _i = 0, _a = initializer.declarations; _i < _a.length; _i++) {
87556                     var variable = _a[_i];
87557                     hoistVariableDeclaration(variable.name);
87558                 }
87559                 var variables = ts.getInitializedVariables(initializer);
87560                 node = ts.updateFor(node, variables.length > 0
87561                     ? ts.inlineExpressions(ts.map(variables, transformInitializedVariable))
87562                     : undefined, ts.visitNode(node.condition, visitor, ts.isExpression), ts.visitNode(node.incrementor, visitor, ts.isExpression), ts.visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock));
87563             }
87564             else {
87565                 node = ts.visitEachChild(node, visitor, context);
87566             }
87567             if (inStatementContainingYield) {
87568                 endLoopBlock();
87569             }
87570             return node;
87571         }
87572         function transformAndEmitForInStatement(node) {
87573             // TODO(rbuckton): Source map locations
87574             if (containsYield(node)) {
87575                 // [source]
87576                 //      for (var p in o) {
87577                 //          /*body*/
87578                 //      }
87579                 //
87580                 // [intermediate]
87581                 //  .local _a, _b, _i
87582                 //      _a = [];
87583                 //      for (_b in o) _a.push(_b);
87584                 //      _i = 0;
87585                 //  .loop incrementLabel, endLoopLabel
87586                 //  .mark conditionLabel
87587                 //  .brfalse endLoopLabel, (_i < _a.length)
87588                 //      p = _a[_i];
87589                 //      /*body*/
87590                 //  .mark incrementLabel
87591                 //      _b++;
87592                 //  .br conditionLabel
87593                 //  .endloop
87594                 //  .mark endLoopLabel
87595                 var keysArray = declareLocal(); // _a
87596                 var key = declareLocal(); // _b
87597                 var keysIndex = ts.createLoopVariable(); // _i
87598                 var initializer = node.initializer;
87599                 hoistVariableDeclaration(keysIndex);
87600                 emitAssignment(keysArray, ts.createArrayLiteral());
87601                 emitStatement(ts.createForIn(key, ts.visitNode(node.expression, visitor, ts.isExpression), ts.createExpressionStatement(ts.createCall(ts.createPropertyAccess(keysArray, "push"), 
87602                 /*typeArguments*/ undefined, [key]))));
87603                 emitAssignment(keysIndex, ts.createLiteral(0));
87604                 var conditionLabel = defineLabel();
87605                 var incrementLabel = defineLabel();
87606                 var endLabel = beginLoopBlock(incrementLabel);
87607                 markLabel(conditionLabel);
87608                 emitBreakWhenFalse(endLabel, ts.createLessThan(keysIndex, ts.createPropertyAccess(keysArray, "length")));
87609                 var variable = void 0;
87610                 if (ts.isVariableDeclarationList(initializer)) {
87611                     for (var _i = 0, _a = initializer.declarations; _i < _a.length; _i++) {
87612                         var variable_1 = _a[_i];
87613                         hoistVariableDeclaration(variable_1.name);
87614                     }
87615                     variable = ts.getSynthesizedClone(initializer.declarations[0].name);
87616                 }
87617                 else {
87618                     variable = ts.visitNode(initializer, visitor, ts.isExpression);
87619                     ts.Debug.assert(ts.isLeftHandSideExpression(variable));
87620                 }
87621                 emitAssignment(variable, ts.createElementAccess(keysArray, keysIndex));
87622                 transformAndEmitEmbeddedStatement(node.statement);
87623                 markLabel(incrementLabel);
87624                 emitStatement(ts.createExpressionStatement(ts.createPostfixIncrement(keysIndex)));
87625                 emitBreak(conditionLabel);
87626                 endLoopBlock();
87627             }
87628             else {
87629                 emitStatement(ts.visitNode(node, visitor, ts.isStatement));
87630             }
87631         }
87632         function visitForInStatement(node) {
87633             // [source]
87634             //      for (var x in a) {
87635             //          /*body*/
87636             //      }
87637             //
87638             // [intermediate]
87639             //  .local x
87640             //  .loop
87641             //      for (x in a) {
87642             //          /*body*/
87643             //      }
87644             //  .endloop
87645             if (inStatementContainingYield) {
87646                 beginScriptLoopBlock();
87647             }
87648             var initializer = node.initializer;
87649             if (ts.isVariableDeclarationList(initializer)) {
87650                 for (var _i = 0, _a = initializer.declarations; _i < _a.length; _i++) {
87651                     var variable = _a[_i];
87652                     hoistVariableDeclaration(variable.name);
87653                 }
87654                 node = ts.updateForIn(node, initializer.declarations[0].name, ts.visitNode(node.expression, visitor, ts.isExpression), ts.visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock));
87655             }
87656             else {
87657                 node = ts.visitEachChild(node, visitor, context);
87658             }
87659             if (inStatementContainingYield) {
87660                 endLoopBlock();
87661             }
87662             return node;
87663         }
87664         function transformAndEmitContinueStatement(node) {
87665             var label = findContinueTarget(node.label ? ts.idText(node.label) : undefined);
87666             if (label > 0) {
87667                 emitBreak(label, /*location*/ node);
87668             }
87669             else {
87670                 // invalid continue without a containing loop. Leave the node as is, per #17875.
87671                 emitStatement(node);
87672             }
87673         }
87674         function visitContinueStatement(node) {
87675             if (inStatementContainingYield) {
87676                 var label = findContinueTarget(node.label && ts.idText(node.label));
87677                 if (label > 0) {
87678                     return createInlineBreak(label, /*location*/ node);
87679                 }
87680             }
87681             return ts.visitEachChild(node, visitor, context);
87682         }
87683         function transformAndEmitBreakStatement(node) {
87684             var label = findBreakTarget(node.label ? ts.idText(node.label) : undefined);
87685             if (label > 0) {
87686                 emitBreak(label, /*location*/ node);
87687             }
87688             else {
87689                 // invalid break without a containing loop, switch, or labeled statement. Leave the node as is, per #17875.
87690                 emitStatement(node);
87691             }
87692         }
87693         function visitBreakStatement(node) {
87694             if (inStatementContainingYield) {
87695                 var label = findBreakTarget(node.label && ts.idText(node.label));
87696                 if (label > 0) {
87697                     return createInlineBreak(label, /*location*/ node);
87698                 }
87699             }
87700             return ts.visitEachChild(node, visitor, context);
87701         }
87702         function transformAndEmitReturnStatement(node) {
87703             emitReturn(ts.visitNode(node.expression, visitor, ts.isExpression), 
87704             /*location*/ node);
87705         }
87706         function visitReturnStatement(node) {
87707             return createInlineReturn(ts.visitNode(node.expression, visitor, ts.isExpression), 
87708             /*location*/ node);
87709         }
87710         function transformAndEmitWithStatement(node) {
87711             if (containsYield(node)) {
87712                 // [source]
87713                 //      with (x) {
87714                 //          /*body*/
87715                 //      }
87716                 //
87717                 // [intermediate]
87718                 //  .with (x)
87719                 //      /*body*/
87720                 //  .endwith
87721                 beginWithBlock(cacheExpression(ts.visitNode(node.expression, visitor, ts.isExpression)));
87722                 transformAndEmitEmbeddedStatement(node.statement);
87723                 endWithBlock();
87724             }
87725             else {
87726                 emitStatement(ts.visitNode(node, visitor, ts.isStatement));
87727             }
87728         }
87729         function transformAndEmitSwitchStatement(node) {
87730             if (containsYield(node.caseBlock)) {
87731                 // [source]
87732                 //      switch (x) {
87733                 //          case a:
87734                 //              /*caseStatements*/
87735                 //          case b:
87736                 //              /*caseStatements*/
87737                 //          default:
87738                 //              /*defaultStatements*/
87739                 //      }
87740                 //
87741                 // [intermediate]
87742                 //  .local _a
87743                 //  .switch endLabel
87744                 //      _a = x;
87745                 //      switch (_a) {
87746                 //          case a:
87747                 //  .br clauseLabels[0]
87748                 //      }
87749                 //      switch (_a) {
87750                 //          case b:
87751                 //  .br clauseLabels[1]
87752                 //      }
87753                 //  .br clauseLabels[2]
87754                 //  .mark clauseLabels[0]
87755                 //      /*caseStatements*/
87756                 //  .mark clauseLabels[1]
87757                 //      /*caseStatements*/
87758                 //  .mark clauseLabels[2]
87759                 //      /*caseStatements*/
87760                 //  .endswitch
87761                 //  .mark endLabel
87762                 var caseBlock = node.caseBlock;
87763                 var numClauses = caseBlock.clauses.length;
87764                 var endLabel = beginSwitchBlock();
87765                 var expression = cacheExpression(ts.visitNode(node.expression, visitor, ts.isExpression));
87766                 // Create labels for each clause and find the index of the first default clause.
87767                 var clauseLabels = [];
87768                 var defaultClauseIndex = -1;
87769                 for (var i = 0; i < numClauses; i++) {
87770                     var clause = caseBlock.clauses[i];
87771                     clauseLabels.push(defineLabel());
87772                     if (clause.kind === 278 /* DefaultClause */ && defaultClauseIndex === -1) {
87773                         defaultClauseIndex = i;
87774                     }
87775                 }
87776                 // Emit switch statements for each run of case clauses either from the first case
87777                 // clause or the next case clause with a `yield` in its expression, up to the next
87778                 // case clause with a `yield` in its expression.
87779                 var clausesWritten = 0;
87780                 var pendingClauses = [];
87781                 while (clausesWritten < numClauses) {
87782                     var defaultClausesSkipped = 0;
87783                     for (var i = clausesWritten; i < numClauses; i++) {
87784                         var clause = caseBlock.clauses[i];
87785                         if (clause.kind === 277 /* CaseClause */) {
87786                             if (containsYield(clause.expression) && pendingClauses.length > 0) {
87787                                 break;
87788                             }
87789                             pendingClauses.push(ts.createCaseClause(ts.visitNode(clause.expression, visitor, ts.isExpression), [
87790                                 createInlineBreak(clauseLabels[i], /*location*/ clause.expression)
87791                             ]));
87792                         }
87793                         else {
87794                             defaultClausesSkipped++;
87795                         }
87796                     }
87797                     if (pendingClauses.length) {
87798                         emitStatement(ts.createSwitch(expression, ts.createCaseBlock(pendingClauses)));
87799                         clausesWritten += pendingClauses.length;
87800                         pendingClauses = [];
87801                     }
87802                     if (defaultClausesSkipped > 0) {
87803                         clausesWritten += defaultClausesSkipped;
87804                         defaultClausesSkipped = 0;
87805                     }
87806                 }
87807                 if (defaultClauseIndex >= 0) {
87808                     emitBreak(clauseLabels[defaultClauseIndex]);
87809                 }
87810                 else {
87811                     emitBreak(endLabel);
87812                 }
87813                 for (var i = 0; i < numClauses; i++) {
87814                     markLabel(clauseLabels[i]);
87815                     transformAndEmitStatements(caseBlock.clauses[i].statements);
87816                 }
87817                 endSwitchBlock();
87818             }
87819             else {
87820                 emitStatement(ts.visitNode(node, visitor, ts.isStatement));
87821             }
87822         }
87823         function visitSwitchStatement(node) {
87824             if (inStatementContainingYield) {
87825                 beginScriptSwitchBlock();
87826             }
87827             node = ts.visitEachChild(node, visitor, context);
87828             if (inStatementContainingYield) {
87829                 endSwitchBlock();
87830             }
87831             return node;
87832         }
87833         function transformAndEmitLabeledStatement(node) {
87834             if (containsYield(node)) {
87835                 // [source]
87836                 //      x: {
87837                 //          /*body*/
87838                 //      }
87839                 //
87840                 // [intermediate]
87841                 //  .labeled "x", endLabel
87842                 //      /*body*/
87843                 //  .endlabeled
87844                 //  .mark endLabel
87845                 beginLabeledBlock(ts.idText(node.label));
87846                 transformAndEmitEmbeddedStatement(node.statement);
87847                 endLabeledBlock();
87848             }
87849             else {
87850                 emitStatement(ts.visitNode(node, visitor, ts.isStatement));
87851             }
87852         }
87853         function visitLabeledStatement(node) {
87854             if (inStatementContainingYield) {
87855                 beginScriptLabeledBlock(ts.idText(node.label));
87856             }
87857             node = ts.visitEachChild(node, visitor, context);
87858             if (inStatementContainingYield) {
87859                 endLabeledBlock();
87860             }
87861             return node;
87862         }
87863         function transformAndEmitThrowStatement(node) {
87864             emitThrow(ts.visitNode(node.expression, visitor, ts.isExpression), 
87865             /*location*/ node);
87866         }
87867         function transformAndEmitTryStatement(node) {
87868             if (containsYield(node)) {
87869                 // [source]
87870                 //      try {
87871                 //          /*tryBlock*/
87872                 //      }
87873                 //      catch (e) {
87874                 //          /*catchBlock*/
87875                 //      }
87876                 //      finally {
87877                 //          /*finallyBlock*/
87878                 //      }
87879                 //
87880                 // [intermediate]
87881                 //  .local _a
87882                 //  .try tryLabel, catchLabel, finallyLabel, endLabel
87883                 //  .mark tryLabel
87884                 //  .nop
87885                 //      /*tryBlock*/
87886                 //  .br endLabel
87887                 //  .catch
87888                 //  .mark catchLabel
87889                 //      _a = %error%;
87890                 //      /*catchBlock*/
87891                 //  .br endLabel
87892                 //  .finally
87893                 //  .mark finallyLabel
87894                 //      /*finallyBlock*/
87895                 //  .endfinally
87896                 //  .endtry
87897                 //  .mark endLabel
87898                 beginExceptionBlock();
87899                 transformAndEmitEmbeddedStatement(node.tryBlock);
87900                 if (node.catchClause) {
87901                     beginCatchBlock(node.catchClause.variableDeclaration); // TODO: GH#18217
87902                     transformAndEmitEmbeddedStatement(node.catchClause.block);
87903                 }
87904                 if (node.finallyBlock) {
87905                     beginFinallyBlock();
87906                     transformAndEmitEmbeddedStatement(node.finallyBlock);
87907                 }
87908                 endExceptionBlock();
87909             }
87910             else {
87911                 emitStatement(ts.visitEachChild(node, visitor, context));
87912             }
87913         }
87914         function containsYield(node) {
87915             return !!node && (node.transformFlags & 262144 /* ContainsYield */) !== 0;
87916         }
87917         function countInitialNodesWithoutYield(nodes) {
87918             var numNodes = nodes.length;
87919             for (var i = 0; i < numNodes; i++) {
87920                 if (containsYield(nodes[i])) {
87921                     return i;
87922                 }
87923             }
87924             return -1;
87925         }
87926         function onSubstituteNode(hint, node) {
87927             node = previousOnSubstituteNode(hint, node);
87928             if (hint === 1 /* Expression */) {
87929                 return substituteExpression(node);
87930             }
87931             return node;
87932         }
87933         function substituteExpression(node) {
87934             if (ts.isIdentifier(node)) {
87935                 return substituteExpressionIdentifier(node);
87936             }
87937             return node;
87938         }
87939         function substituteExpressionIdentifier(node) {
87940             if (!ts.isGeneratedIdentifier(node) && renamedCatchVariables && renamedCatchVariables.has(ts.idText(node))) {
87941                 var original = ts.getOriginalNode(node);
87942                 if (ts.isIdentifier(original) && original.parent) {
87943                     var declaration = resolver.getReferencedValueDeclaration(original);
87944                     if (declaration) {
87945                         var name = renamedCatchVariableDeclarations[ts.getOriginalNodeId(declaration)];
87946                         if (name) {
87947                             var clone_8 = ts.getMutableClone(name);
87948                             ts.setSourceMapRange(clone_8, node);
87949                             ts.setCommentRange(clone_8, node);
87950                             return clone_8;
87951                         }
87952                     }
87953                 }
87954             }
87955             return node;
87956         }
87957         function cacheExpression(node) {
87958             if (ts.isGeneratedIdentifier(node) || ts.getEmitFlags(node) & 4096 /* HelperName */) {
87959                 return node;
87960             }
87961             var temp = ts.createTempVariable(hoistVariableDeclaration);
87962             emitAssignment(temp, node, /*location*/ node);
87963             return temp;
87964         }
87965         function declareLocal(name) {
87966             var temp = name
87967                 ? ts.createUniqueName(name)
87968                 : ts.createTempVariable(/*recordTempVariable*/ undefined);
87969             hoistVariableDeclaration(temp);
87970             return temp;
87971         }
87972         /**
87973          * Defines a label, uses as the target of a Break operation.
87974          */
87975         function defineLabel() {
87976             if (!labelOffsets) {
87977                 labelOffsets = [];
87978             }
87979             var label = nextLabelId;
87980             nextLabelId++;
87981             labelOffsets[label] = -1;
87982             return label;
87983         }
87984         /**
87985          * Marks the current operation with the specified label.
87986          */
87987         function markLabel(label) {
87988             ts.Debug.assert(labelOffsets !== undefined, "No labels were defined.");
87989             labelOffsets[label] = operations ? operations.length : 0;
87990         }
87991         /**
87992          * Begins a block operation (With, Break/Continue, Try/Catch/Finally)
87993          *
87994          * @param block Information about the block.
87995          */
87996         function beginBlock(block) {
87997             if (!blocks) {
87998                 blocks = [];
87999                 blockActions = [];
88000                 blockOffsets = [];
88001                 blockStack = [];
88002             }
88003             var index = blockActions.length;
88004             blockActions[index] = 0 /* Open */;
88005             blockOffsets[index] = operations ? operations.length : 0;
88006             blocks[index] = block;
88007             blockStack.push(block);
88008             return index;
88009         }
88010         /**
88011          * Ends the current block operation.
88012          */
88013         function endBlock() {
88014             var block = peekBlock();
88015             if (block === undefined)
88016                 return ts.Debug.fail("beginBlock was never called.");
88017             var index = blockActions.length;
88018             blockActions[index] = 1 /* Close */;
88019             blockOffsets[index] = operations ? operations.length : 0;
88020             blocks[index] = block;
88021             blockStack.pop();
88022             return block;
88023         }
88024         /**
88025          * Gets the current open block.
88026          */
88027         function peekBlock() {
88028             return ts.lastOrUndefined(blockStack);
88029         }
88030         /**
88031          * Gets the kind of the current open block.
88032          */
88033         function peekBlockKind() {
88034             var block = peekBlock();
88035             return block && block.kind;
88036         }
88037         /**
88038          * Begins a code block for a generated `with` statement.
88039          *
88040          * @param expression An identifier representing expression for the `with` block.
88041          */
88042         function beginWithBlock(expression) {
88043             var startLabel = defineLabel();
88044             var endLabel = defineLabel();
88045             markLabel(startLabel);
88046             beginBlock({
88047                 kind: 1 /* With */,
88048                 expression: expression,
88049                 startLabel: startLabel,
88050                 endLabel: endLabel
88051             });
88052         }
88053         /**
88054          * Ends a code block for a generated `with` statement.
88055          */
88056         function endWithBlock() {
88057             ts.Debug.assert(peekBlockKind() === 1 /* With */);
88058             var block = endBlock();
88059             markLabel(block.endLabel);
88060         }
88061         /**
88062          * Begins a code block for a generated `try` statement.
88063          */
88064         function beginExceptionBlock() {
88065             var startLabel = defineLabel();
88066             var endLabel = defineLabel();
88067             markLabel(startLabel);
88068             beginBlock({
88069                 kind: 0 /* Exception */,
88070                 state: 0 /* Try */,
88071                 startLabel: startLabel,
88072                 endLabel: endLabel
88073             });
88074             emitNop();
88075             return endLabel;
88076         }
88077         /**
88078          * Enters the `catch` clause of a generated `try` statement.
88079          *
88080          * @param variable The catch variable.
88081          */
88082         function beginCatchBlock(variable) {
88083             ts.Debug.assert(peekBlockKind() === 0 /* Exception */);
88084             // generated identifiers should already be unique within a file
88085             var name;
88086             if (ts.isGeneratedIdentifier(variable.name)) {
88087                 name = variable.name;
88088                 hoistVariableDeclaration(variable.name);
88089             }
88090             else {
88091                 var text = ts.idText(variable.name);
88092                 name = declareLocal(text);
88093                 if (!renamedCatchVariables) {
88094                     renamedCatchVariables = ts.createMap();
88095                     renamedCatchVariableDeclarations = [];
88096                     context.enableSubstitution(75 /* Identifier */);
88097                 }
88098                 renamedCatchVariables.set(text, true);
88099                 renamedCatchVariableDeclarations[ts.getOriginalNodeId(variable)] = name;
88100             }
88101             var exception = peekBlock();
88102             ts.Debug.assert(exception.state < 1 /* Catch */);
88103             var endLabel = exception.endLabel;
88104             emitBreak(endLabel);
88105             var catchLabel = defineLabel();
88106             markLabel(catchLabel);
88107             exception.state = 1 /* Catch */;
88108             exception.catchVariable = name;
88109             exception.catchLabel = catchLabel;
88110             emitAssignment(name, ts.createCall(ts.createPropertyAccess(state, "sent"), /*typeArguments*/ undefined, []));
88111             emitNop();
88112         }
88113         /**
88114          * Enters the `finally` block of a generated `try` statement.
88115          */
88116         function beginFinallyBlock() {
88117             ts.Debug.assert(peekBlockKind() === 0 /* Exception */);
88118             var exception = peekBlock();
88119             ts.Debug.assert(exception.state < 2 /* Finally */);
88120             var endLabel = exception.endLabel;
88121             emitBreak(endLabel);
88122             var finallyLabel = defineLabel();
88123             markLabel(finallyLabel);
88124             exception.state = 2 /* Finally */;
88125             exception.finallyLabel = finallyLabel;
88126         }
88127         /**
88128          * Ends the code block for a generated `try` statement.
88129          */
88130         function endExceptionBlock() {
88131             ts.Debug.assert(peekBlockKind() === 0 /* Exception */);
88132             var exception = endBlock();
88133             var state = exception.state;
88134             if (state < 2 /* Finally */) {
88135                 emitBreak(exception.endLabel);
88136             }
88137             else {
88138                 emitEndfinally();
88139             }
88140             markLabel(exception.endLabel);
88141             emitNop();
88142             exception.state = 3 /* Done */;
88143         }
88144         /**
88145          * Begins a code block that supports `break` or `continue` statements that are defined in
88146          * the source tree and not from generated code.
88147          *
88148          * @param labelText Names from containing labeled statements.
88149          */
88150         function beginScriptLoopBlock() {
88151             beginBlock({
88152                 kind: 3 /* Loop */,
88153                 isScript: true,
88154                 breakLabel: -1,
88155                 continueLabel: -1
88156             });
88157         }
88158         /**
88159          * Begins a code block that supports `break` or `continue` statements that are defined in
88160          * generated code. Returns a label used to mark the operation to which to jump when a
88161          * `break` statement targets this block.
88162          *
88163          * @param continueLabel A Label used to mark the operation to which to jump when a
88164          *                      `continue` statement targets this block.
88165          */
88166         function beginLoopBlock(continueLabel) {
88167             var breakLabel = defineLabel();
88168             beginBlock({
88169                 kind: 3 /* Loop */,
88170                 isScript: false,
88171                 breakLabel: breakLabel,
88172                 continueLabel: continueLabel,
88173             });
88174             return breakLabel;
88175         }
88176         /**
88177          * Ends a code block that supports `break` or `continue` statements that are defined in
88178          * generated code or in the source tree.
88179          */
88180         function endLoopBlock() {
88181             ts.Debug.assert(peekBlockKind() === 3 /* Loop */);
88182             var block = endBlock();
88183             var breakLabel = block.breakLabel;
88184             if (!block.isScript) {
88185                 markLabel(breakLabel);
88186             }
88187         }
88188         /**
88189          * Begins a code block that supports `break` statements that are defined in the source
88190          * tree and not from generated code.
88191          *
88192          */
88193         function beginScriptSwitchBlock() {
88194             beginBlock({
88195                 kind: 2 /* Switch */,
88196                 isScript: true,
88197                 breakLabel: -1
88198             });
88199         }
88200         /**
88201          * Begins a code block that supports `break` statements that are defined in generated code.
88202          * Returns a label used to mark the operation to which to jump when a `break` statement
88203          * targets this block.
88204          */
88205         function beginSwitchBlock() {
88206             var breakLabel = defineLabel();
88207             beginBlock({
88208                 kind: 2 /* Switch */,
88209                 isScript: false,
88210                 breakLabel: breakLabel,
88211             });
88212             return breakLabel;
88213         }
88214         /**
88215          * Ends a code block that supports `break` statements that are defined in generated code.
88216          */
88217         function endSwitchBlock() {
88218             ts.Debug.assert(peekBlockKind() === 2 /* Switch */);
88219             var block = endBlock();
88220             var breakLabel = block.breakLabel;
88221             if (!block.isScript) {
88222                 markLabel(breakLabel);
88223             }
88224         }
88225         function beginScriptLabeledBlock(labelText) {
88226             beginBlock({
88227                 kind: 4 /* Labeled */,
88228                 isScript: true,
88229                 labelText: labelText,
88230                 breakLabel: -1
88231             });
88232         }
88233         function beginLabeledBlock(labelText) {
88234             var breakLabel = defineLabel();
88235             beginBlock({
88236                 kind: 4 /* Labeled */,
88237                 isScript: false,
88238                 labelText: labelText,
88239                 breakLabel: breakLabel
88240             });
88241         }
88242         function endLabeledBlock() {
88243             ts.Debug.assert(peekBlockKind() === 4 /* Labeled */);
88244             var block = endBlock();
88245             if (!block.isScript) {
88246                 markLabel(block.breakLabel);
88247             }
88248         }
88249         /**
88250          * Indicates whether the provided block supports `break` statements.
88251          *
88252          * @param block A code block.
88253          */
88254         function supportsUnlabeledBreak(block) {
88255             return block.kind === 2 /* Switch */
88256                 || block.kind === 3 /* Loop */;
88257         }
88258         /**
88259          * Indicates whether the provided block supports `break` statements with labels.
88260          *
88261          * @param block A code block.
88262          */
88263         function supportsLabeledBreakOrContinue(block) {
88264             return block.kind === 4 /* Labeled */;
88265         }
88266         /**
88267          * Indicates whether the provided block supports `continue` statements.
88268          *
88269          * @param block A code block.
88270          */
88271         function supportsUnlabeledContinue(block) {
88272             return block.kind === 3 /* Loop */;
88273         }
88274         function hasImmediateContainingLabeledBlock(labelText, start) {
88275             for (var j = start; j >= 0; j--) {
88276                 var containingBlock = blockStack[j];
88277                 if (supportsLabeledBreakOrContinue(containingBlock)) {
88278                     if (containingBlock.labelText === labelText) {
88279                         return true;
88280                     }
88281                 }
88282                 else {
88283                     break;
88284                 }
88285             }
88286             return false;
88287         }
88288         /**
88289          * Finds the label that is the target for a `break` statement.
88290          *
88291          * @param labelText An optional name of a containing labeled statement.
88292          */
88293         function findBreakTarget(labelText) {
88294             if (blockStack) {
88295                 if (labelText) {
88296                     for (var i = blockStack.length - 1; i >= 0; i--) {
88297                         var block = blockStack[i];
88298                         if (supportsLabeledBreakOrContinue(block) && block.labelText === labelText) {
88299                             return block.breakLabel;
88300                         }
88301                         else if (supportsUnlabeledBreak(block) && hasImmediateContainingLabeledBlock(labelText, i - 1)) {
88302                             return block.breakLabel;
88303                         }
88304                     }
88305                 }
88306                 else {
88307                     for (var i = blockStack.length - 1; i >= 0; i--) {
88308                         var block = blockStack[i];
88309                         if (supportsUnlabeledBreak(block)) {
88310                             return block.breakLabel;
88311                         }
88312                     }
88313                 }
88314             }
88315             return 0;
88316         }
88317         /**
88318          * Finds the label that is the target for a `continue` statement.
88319          *
88320          * @param labelText An optional name of a containing labeled statement.
88321          */
88322         function findContinueTarget(labelText) {
88323             if (blockStack) {
88324                 if (labelText) {
88325                     for (var i = blockStack.length - 1; i >= 0; i--) {
88326                         var block = blockStack[i];
88327                         if (supportsUnlabeledContinue(block) && hasImmediateContainingLabeledBlock(labelText, i - 1)) {
88328                             return block.continueLabel;
88329                         }
88330                     }
88331                 }
88332                 else {
88333                     for (var i = blockStack.length - 1; i >= 0; i--) {
88334                         var block = blockStack[i];
88335                         if (supportsUnlabeledContinue(block)) {
88336                             return block.continueLabel;
88337                         }
88338                     }
88339                 }
88340             }
88341             return 0;
88342         }
88343         /**
88344          * Creates an expression that can be used to indicate the value for a label.
88345          *
88346          * @param label A label.
88347          */
88348         function createLabel(label) {
88349             if (label !== undefined && label > 0) {
88350                 if (labelExpressions === undefined) {
88351                     labelExpressions = [];
88352                 }
88353                 var expression = ts.createLiteral(-1);
88354                 if (labelExpressions[label] === undefined) {
88355                     labelExpressions[label] = [expression];
88356                 }
88357                 else {
88358                     labelExpressions[label].push(expression);
88359                 }
88360                 return expression;
88361             }
88362             return ts.createOmittedExpression();
88363         }
88364         /**
88365          * Creates a numeric literal for the provided instruction.
88366          */
88367         function createInstruction(instruction) {
88368             var literal = ts.createLiteral(instruction);
88369             ts.addSyntheticTrailingComment(literal, 3 /* MultiLineCommentTrivia */, getInstructionName(instruction));
88370             return literal;
88371         }
88372         /**
88373          * Creates a statement that can be used indicate a Break operation to the provided label.
88374          *
88375          * @param label A label.
88376          * @param location An optional source map location for the statement.
88377          */
88378         function createInlineBreak(label, location) {
88379             ts.Debug.assertLessThan(0, label, "Invalid label");
88380             return ts.setTextRange(ts.createReturn(ts.createArrayLiteral([
88381                 createInstruction(3 /* Break */),
88382                 createLabel(label)
88383             ])), location);
88384         }
88385         /**
88386          * Creates a statement that can be used indicate a Return operation.
88387          *
88388          * @param expression The expression for the return statement.
88389          * @param location An optional source map location for the statement.
88390          */
88391         function createInlineReturn(expression, location) {
88392             return ts.setTextRange(ts.createReturn(ts.createArrayLiteral(expression
88393                 ? [createInstruction(2 /* Return */), expression]
88394                 : [createInstruction(2 /* Return */)])), location);
88395         }
88396         /**
88397          * Creates an expression that can be used to resume from a Yield operation.
88398          */
88399         function createGeneratorResume(location) {
88400             return ts.setTextRange(ts.createCall(ts.createPropertyAccess(state, "sent"), 
88401             /*typeArguments*/ undefined, []), location);
88402         }
88403         /**
88404          * Emits an empty instruction.
88405          */
88406         function emitNop() {
88407             emitWorker(0 /* Nop */);
88408         }
88409         /**
88410          * Emits a Statement.
88411          *
88412          * @param node A statement.
88413          */
88414         function emitStatement(node) {
88415             if (node) {
88416                 emitWorker(1 /* Statement */, [node]);
88417             }
88418             else {
88419                 emitNop();
88420             }
88421         }
88422         /**
88423          * Emits an Assignment operation.
88424          *
88425          * @param left The left-hand side of the assignment.
88426          * @param right The right-hand side of the assignment.
88427          * @param location An optional source map location for the assignment.
88428          */
88429         function emitAssignment(left, right, location) {
88430             emitWorker(2 /* Assign */, [left, right], location);
88431         }
88432         /**
88433          * Emits a Break operation to the specified label.
88434          *
88435          * @param label A label.
88436          * @param location An optional source map location for the assignment.
88437          */
88438         function emitBreak(label, location) {
88439             emitWorker(3 /* Break */, [label], location);
88440         }
88441         /**
88442          * Emits a Break operation to the specified label when a condition evaluates to a truthy
88443          * value at runtime.
88444          *
88445          * @param label A label.
88446          * @param condition The condition.
88447          * @param location An optional source map location for the assignment.
88448          */
88449         function emitBreakWhenTrue(label, condition, location) {
88450             emitWorker(4 /* BreakWhenTrue */, [label, condition], location);
88451         }
88452         /**
88453          * Emits a Break to the specified label when a condition evaluates to a falsey value at
88454          * runtime.
88455          *
88456          * @param label A label.
88457          * @param condition The condition.
88458          * @param location An optional source map location for the assignment.
88459          */
88460         function emitBreakWhenFalse(label, condition, location) {
88461             emitWorker(5 /* BreakWhenFalse */, [label, condition], location);
88462         }
88463         /**
88464          * Emits a YieldStar operation for the provided expression.
88465          *
88466          * @param expression An optional value for the yield operation.
88467          * @param location An optional source map location for the assignment.
88468          */
88469         function emitYieldStar(expression, location) {
88470             emitWorker(7 /* YieldStar */, [expression], location);
88471         }
88472         /**
88473          * Emits a Yield operation for the provided expression.
88474          *
88475          * @param expression An optional value for the yield operation.
88476          * @param location An optional source map location for the assignment.
88477          */
88478         function emitYield(expression, location) {
88479             emitWorker(6 /* Yield */, [expression], location);
88480         }
88481         /**
88482          * Emits a Return operation for the provided expression.
88483          *
88484          * @param expression An optional value for the operation.
88485          * @param location An optional source map location for the assignment.
88486          */
88487         function emitReturn(expression, location) {
88488             emitWorker(8 /* Return */, [expression], location);
88489         }
88490         /**
88491          * Emits a Throw operation for the provided expression.
88492          *
88493          * @param expression A value for the operation.
88494          * @param location An optional source map location for the assignment.
88495          */
88496         function emitThrow(expression, location) {
88497             emitWorker(9 /* Throw */, [expression], location);
88498         }
88499         /**
88500          * Emits an Endfinally operation. This is used to handle `finally` block semantics.
88501          */
88502         function emitEndfinally() {
88503             emitWorker(10 /* Endfinally */);
88504         }
88505         /**
88506          * Emits an operation.
88507          *
88508          * @param code The OpCode for the operation.
88509          * @param args The optional arguments for the operation.
88510          */
88511         function emitWorker(code, args, location) {
88512             if (operations === undefined) {
88513                 operations = [];
88514                 operationArguments = [];
88515                 operationLocations = [];
88516             }
88517             if (labelOffsets === undefined) {
88518                 // mark entry point
88519                 markLabel(defineLabel());
88520             }
88521             var operationIndex = operations.length;
88522             operations[operationIndex] = code;
88523             operationArguments[operationIndex] = args;
88524             operationLocations[operationIndex] = location;
88525         }
88526         /**
88527          * Builds the generator function body.
88528          */
88529         function build() {
88530             blockIndex = 0;
88531             labelNumber = 0;
88532             labelNumbers = undefined;
88533             lastOperationWasAbrupt = false;
88534             lastOperationWasCompletion = false;
88535             clauses = undefined;
88536             statements = undefined;
88537             exceptionBlockStack = undefined;
88538             currentExceptionBlock = undefined;
88539             withBlockStack = undefined;
88540             var buildResult = buildStatements();
88541             return createGeneratorHelper(context, ts.setEmitFlags(ts.createFunctionExpression(
88542             /*modifiers*/ undefined, 
88543             /*asteriskToken*/ undefined, 
88544             /*name*/ undefined, 
88545             /*typeParameters*/ undefined, [ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, state)], 
88546             /*type*/ undefined, ts.createBlock(buildResult, 
88547             /*multiLine*/ buildResult.length > 0)), 524288 /* ReuseTempVariableScope */));
88548         }
88549         /**
88550          * Builds the statements for the generator function body.
88551          */
88552         function buildStatements() {
88553             if (operations) {
88554                 for (var operationIndex = 0; operationIndex < operations.length; operationIndex++) {
88555                     writeOperation(operationIndex);
88556                 }
88557                 flushFinalLabel(operations.length);
88558             }
88559             else {
88560                 flushFinalLabel(0);
88561             }
88562             if (clauses) {
88563                 var labelExpression = ts.createPropertyAccess(state, "label");
88564                 var switchStatement = ts.createSwitch(labelExpression, ts.createCaseBlock(clauses));
88565                 return [ts.startOnNewLine(switchStatement)];
88566             }
88567             if (statements) {
88568                 return statements;
88569             }
88570             return [];
88571         }
88572         /**
88573          * Flush the current label and advance to a new label.
88574          */
88575         function flushLabel() {
88576             if (!statements) {
88577                 return;
88578             }
88579             appendLabel(/*markLabelEnd*/ !lastOperationWasAbrupt);
88580             lastOperationWasAbrupt = false;
88581             lastOperationWasCompletion = false;
88582             labelNumber++;
88583         }
88584         /**
88585          * Flush the final label of the generator function body.
88586          */
88587         function flushFinalLabel(operationIndex) {
88588             if (isFinalLabelReachable(operationIndex)) {
88589                 tryEnterLabel(operationIndex);
88590                 withBlockStack = undefined;
88591                 writeReturn(/*expression*/ undefined, /*operationLocation*/ undefined);
88592             }
88593             if (statements && clauses) {
88594                 appendLabel(/*markLabelEnd*/ false);
88595             }
88596             updateLabelExpressions();
88597         }
88598         /**
88599          * Tests whether the final label of the generator function body
88600          * is reachable by user code.
88601          */
88602         function isFinalLabelReachable(operationIndex) {
88603             // if the last operation was *not* a completion (return/throw) then
88604             // the final label is reachable.
88605             if (!lastOperationWasCompletion) {
88606                 return true;
88607             }
88608             // if there are no labels defined or referenced, then the final label is
88609             // not reachable.
88610             if (!labelOffsets || !labelExpressions) {
88611                 return false;
88612             }
88613             // if the label for this offset is referenced, then the final label
88614             // is reachable.
88615             for (var label = 0; label < labelOffsets.length; label++) {
88616                 if (labelOffsets[label] === operationIndex && labelExpressions[label]) {
88617                     return true;
88618                 }
88619             }
88620             return false;
88621         }
88622         /**
88623          * Appends a case clause for the last label and sets the new label.
88624          *
88625          * @param markLabelEnd Indicates that the transition between labels was a fall-through
88626          *                     from a previous case clause and the change in labels should be
88627          *                     reflected on the `state` object.
88628          */
88629         function appendLabel(markLabelEnd) {
88630             if (!clauses) {
88631                 clauses = [];
88632             }
88633             if (statements) {
88634                 if (withBlockStack) {
88635                     // The previous label was nested inside one or more `with` blocks, so we
88636                     // surround the statements in generated `with` blocks to create the same environment.
88637                     for (var i = withBlockStack.length - 1; i >= 0; i--) {
88638                         var withBlock = withBlockStack[i];
88639                         statements = [ts.createWith(withBlock.expression, ts.createBlock(statements))];
88640                     }
88641                 }
88642                 if (currentExceptionBlock) {
88643                     // The previous label was nested inside of an exception block, so we must
88644                     // indicate entry into a protected region by pushing the label numbers
88645                     // for each block in the protected region.
88646                     var startLabel = currentExceptionBlock.startLabel, catchLabel = currentExceptionBlock.catchLabel, finallyLabel = currentExceptionBlock.finallyLabel, endLabel = currentExceptionBlock.endLabel;
88647                     statements.unshift(ts.createExpressionStatement(ts.createCall(ts.createPropertyAccess(ts.createPropertyAccess(state, "trys"), "push"), 
88648                     /*typeArguments*/ undefined, [
88649                         ts.createArrayLiteral([
88650                             createLabel(startLabel),
88651                             createLabel(catchLabel),
88652                             createLabel(finallyLabel),
88653                             createLabel(endLabel)
88654                         ])
88655                     ])));
88656                     currentExceptionBlock = undefined;
88657                 }
88658                 if (markLabelEnd) {
88659                     // The case clause for the last label falls through to this label, so we
88660                     // add an assignment statement to reflect the change in labels.
88661                     statements.push(ts.createExpressionStatement(ts.createAssignment(ts.createPropertyAccess(state, "label"), ts.createLiteral(labelNumber + 1))));
88662                 }
88663             }
88664             clauses.push(ts.createCaseClause(ts.createLiteral(labelNumber), statements || []));
88665             statements = undefined;
88666         }
88667         /**
88668          * Tries to enter into a new label at the current operation index.
88669          */
88670         function tryEnterLabel(operationIndex) {
88671             if (!labelOffsets) {
88672                 return;
88673             }
88674             for (var label = 0; label < labelOffsets.length; label++) {
88675                 if (labelOffsets[label] === operationIndex) {
88676                     flushLabel();
88677                     if (labelNumbers === undefined) {
88678                         labelNumbers = [];
88679                     }
88680                     if (labelNumbers[labelNumber] === undefined) {
88681                         labelNumbers[labelNumber] = [label];
88682                     }
88683                     else {
88684                         labelNumbers[labelNumber].push(label);
88685                     }
88686                 }
88687             }
88688         }
88689         /**
88690          * Updates literal expressions for labels with actual label numbers.
88691          */
88692         function updateLabelExpressions() {
88693             if (labelExpressions !== undefined && labelNumbers !== undefined) {
88694                 for (var labelNumber_1 = 0; labelNumber_1 < labelNumbers.length; labelNumber_1++) {
88695                     var labels = labelNumbers[labelNumber_1];
88696                     if (labels !== undefined) {
88697                         for (var _i = 0, labels_1 = labels; _i < labels_1.length; _i++) {
88698                             var label = labels_1[_i];
88699                             var expressions = labelExpressions[label];
88700                             if (expressions !== undefined) {
88701                                 for (var _a = 0, expressions_1 = expressions; _a < expressions_1.length; _a++) {
88702                                     var expression = expressions_1[_a];
88703                                     expression.text = String(labelNumber_1);
88704                                 }
88705                             }
88706                         }
88707                     }
88708                 }
88709             }
88710         }
88711         /**
88712          * Tries to enter or leave a code block.
88713          */
88714         function tryEnterOrLeaveBlock(operationIndex) {
88715             if (blocks) {
88716                 for (; blockIndex < blockActions.length && blockOffsets[blockIndex] <= operationIndex; blockIndex++) {
88717                     var block = blocks[blockIndex];
88718                     var blockAction = blockActions[blockIndex];
88719                     switch (block.kind) {
88720                         case 0 /* Exception */:
88721                             if (blockAction === 0 /* Open */) {
88722                                 if (!exceptionBlockStack) {
88723                                     exceptionBlockStack = [];
88724                                 }
88725                                 if (!statements) {
88726                                     statements = [];
88727                                 }
88728                                 exceptionBlockStack.push(currentExceptionBlock);
88729                                 currentExceptionBlock = block;
88730                             }
88731                             else if (blockAction === 1 /* Close */) {
88732                                 currentExceptionBlock = exceptionBlockStack.pop();
88733                             }
88734                             break;
88735                         case 1 /* With */:
88736                             if (blockAction === 0 /* Open */) {
88737                                 if (!withBlockStack) {
88738                                     withBlockStack = [];
88739                                 }
88740                                 withBlockStack.push(block);
88741                             }
88742                             else if (blockAction === 1 /* Close */) {
88743                                 withBlockStack.pop();
88744                             }
88745                             break;
88746                         // default: do nothing
88747                     }
88748                 }
88749             }
88750         }
88751         /**
88752          * Writes an operation as a statement to the current label's statement list.
88753          *
88754          * @param operation The OpCode of the operation
88755          */
88756         function writeOperation(operationIndex) {
88757             tryEnterLabel(operationIndex);
88758             tryEnterOrLeaveBlock(operationIndex);
88759             // early termination, nothing else to process in this label
88760             if (lastOperationWasAbrupt) {
88761                 return;
88762             }
88763             lastOperationWasAbrupt = false;
88764             lastOperationWasCompletion = false;
88765             var opcode = operations[operationIndex];
88766             if (opcode === 0 /* Nop */) {
88767                 return;
88768             }
88769             else if (opcode === 10 /* Endfinally */) {
88770                 return writeEndfinally();
88771             }
88772             var args = operationArguments[operationIndex];
88773             if (opcode === 1 /* Statement */) {
88774                 return writeStatement(args[0]);
88775             }
88776             var location = operationLocations[operationIndex];
88777             switch (opcode) {
88778                 case 2 /* Assign */:
88779                     return writeAssign(args[0], args[1], location);
88780                 case 3 /* Break */:
88781                     return writeBreak(args[0], location);
88782                 case 4 /* BreakWhenTrue */:
88783                     return writeBreakWhenTrue(args[0], args[1], location);
88784                 case 5 /* BreakWhenFalse */:
88785                     return writeBreakWhenFalse(args[0], args[1], location);
88786                 case 6 /* Yield */:
88787                     return writeYield(args[0], location);
88788                 case 7 /* YieldStar */:
88789                     return writeYieldStar(args[0], location);
88790                 case 8 /* Return */:
88791                     return writeReturn(args[0], location);
88792                 case 9 /* Throw */:
88793                     return writeThrow(args[0], location);
88794             }
88795         }
88796         /**
88797          * Writes a statement to the current label's statement list.
88798          *
88799          * @param statement A statement to write.
88800          */
88801         function writeStatement(statement) {
88802             if (statement) {
88803                 if (!statements) {
88804                     statements = [statement];
88805                 }
88806                 else {
88807                     statements.push(statement);
88808                 }
88809             }
88810         }
88811         /**
88812          * Writes an Assign operation to the current label's statement list.
88813          *
88814          * @param left The left-hand side of the assignment.
88815          * @param right The right-hand side of the assignment.
88816          * @param operationLocation The source map location for the operation.
88817          */
88818         function writeAssign(left, right, operationLocation) {
88819             writeStatement(ts.setTextRange(ts.createExpressionStatement(ts.createAssignment(left, right)), operationLocation));
88820         }
88821         /**
88822          * Writes a Throw operation to the current label's statement list.
88823          *
88824          * @param expression The value to throw.
88825          * @param operationLocation The source map location for the operation.
88826          */
88827         function writeThrow(expression, operationLocation) {
88828             lastOperationWasAbrupt = true;
88829             lastOperationWasCompletion = true;
88830             writeStatement(ts.setTextRange(ts.createThrow(expression), operationLocation));
88831         }
88832         /**
88833          * Writes a Return operation to the current label's statement list.
88834          *
88835          * @param expression The value to return.
88836          * @param operationLocation The source map location for the operation.
88837          */
88838         function writeReturn(expression, operationLocation) {
88839             lastOperationWasAbrupt = true;
88840             lastOperationWasCompletion = true;
88841             writeStatement(ts.setEmitFlags(ts.setTextRange(ts.createReturn(ts.createArrayLiteral(expression
88842                 ? [createInstruction(2 /* Return */), expression]
88843                 : [createInstruction(2 /* Return */)])), operationLocation), 384 /* NoTokenSourceMaps */));
88844         }
88845         /**
88846          * Writes a Break operation to the current label's statement list.
88847          *
88848          * @param label The label for the Break.
88849          * @param operationLocation The source map location for the operation.
88850          */
88851         function writeBreak(label, operationLocation) {
88852             lastOperationWasAbrupt = true;
88853             writeStatement(ts.setEmitFlags(ts.setTextRange(ts.createReturn(ts.createArrayLiteral([
88854                 createInstruction(3 /* Break */),
88855                 createLabel(label)
88856             ])), operationLocation), 384 /* NoTokenSourceMaps */));
88857         }
88858         /**
88859          * Writes a BreakWhenTrue operation to the current label's statement list.
88860          *
88861          * @param label The label for the Break.
88862          * @param condition The condition for the Break.
88863          * @param operationLocation The source map location for the operation.
88864          */
88865         function writeBreakWhenTrue(label, condition, operationLocation) {
88866             writeStatement(ts.setEmitFlags(ts.createIf(condition, ts.setEmitFlags(ts.setTextRange(ts.createReturn(ts.createArrayLiteral([
88867                 createInstruction(3 /* Break */),
88868                 createLabel(label)
88869             ])), operationLocation), 384 /* NoTokenSourceMaps */)), 1 /* SingleLine */));
88870         }
88871         /**
88872          * Writes a BreakWhenFalse operation to the current label's statement list.
88873          *
88874          * @param label The label for the Break.
88875          * @param condition The condition for the Break.
88876          * @param operationLocation The source map location for the operation.
88877          */
88878         function writeBreakWhenFalse(label, condition, operationLocation) {
88879             writeStatement(ts.setEmitFlags(ts.createIf(ts.createLogicalNot(condition), ts.setEmitFlags(ts.setTextRange(ts.createReturn(ts.createArrayLiteral([
88880                 createInstruction(3 /* Break */),
88881                 createLabel(label)
88882             ])), operationLocation), 384 /* NoTokenSourceMaps */)), 1 /* SingleLine */));
88883         }
88884         /**
88885          * Writes a Yield operation to the current label's statement list.
88886          *
88887          * @param expression The expression to yield.
88888          * @param operationLocation The source map location for the operation.
88889          */
88890         function writeYield(expression, operationLocation) {
88891             lastOperationWasAbrupt = true;
88892             writeStatement(ts.setEmitFlags(ts.setTextRange(ts.createReturn(ts.createArrayLiteral(expression
88893                 ? [createInstruction(4 /* Yield */), expression]
88894                 : [createInstruction(4 /* Yield */)])), operationLocation), 384 /* NoTokenSourceMaps */));
88895         }
88896         /**
88897          * Writes a YieldStar instruction to the current label's statement list.
88898          *
88899          * @param expression The expression to yield.
88900          * @param operationLocation The source map location for the operation.
88901          */
88902         function writeYieldStar(expression, operationLocation) {
88903             lastOperationWasAbrupt = true;
88904             writeStatement(ts.setEmitFlags(ts.setTextRange(ts.createReturn(ts.createArrayLiteral([
88905                 createInstruction(5 /* YieldStar */),
88906                 expression
88907             ])), operationLocation), 384 /* NoTokenSourceMaps */));
88908         }
88909         /**
88910          * Writes an Endfinally instruction to the current label's statement list.
88911          */
88912         function writeEndfinally() {
88913             lastOperationWasAbrupt = true;
88914             writeStatement(ts.createReturn(ts.createArrayLiteral([
88915                 createInstruction(7 /* Endfinally */)
88916             ])));
88917         }
88918     }
88919     ts.transformGenerators = transformGenerators;
88920     function createGeneratorHelper(context, body) {
88921         context.requestEmitHelper(ts.generatorHelper);
88922         return ts.createCall(ts.getUnscopedHelperName("__generator"), 
88923         /*typeArguments*/ undefined, [ts.createThis(), body]);
88924     }
88925     // The __generator helper is used by down-level transformations to emulate the runtime
88926     // semantics of an ES2015 generator function. When called, this helper returns an
88927     // object that implements the Iterator protocol, in that it has `next`, `return`, and
88928     // `throw` methods that step through the generator when invoked.
88929     //
88930     // parameters:
88931     //  @param thisArg  The value to use as the `this` binding for the transformed generator body.
88932     //  @param body     A function that acts as the transformed generator body.
88933     //
88934     // variables:
88935     //  _       Persistent state for the generator that is shared between the helper and the
88936     //          generator body. The state object has the following members:
88937     //            sent() - A method that returns or throws the current completion value.
88938     //            label  - The next point at which to resume evaluation of the generator body.
88939     //            trys   - A stack of protected regions (try/catch/finally blocks).
88940     //            ops    - A stack of pending instructions when inside of a finally block.
88941     //  f       A value indicating whether the generator is executing.
88942     //  y       An iterator to delegate for a yield*.
88943     //  t       A temporary variable that holds one of the following values (note that these
88944     //          cases do not overlap):
88945     //          - The completion value when resuming from a `yield` or `yield*`.
88946     //          - The error value for a catch block.
88947     //          - The current protected region (array of try/catch/finally/end labels).
88948     //          - The verb (`next`, `throw`, or `return` method) to delegate to the expression
88949     //            of a `yield*`.
88950     //          - The result of evaluating the verb delegated to the expression of a `yield*`.
88951     //
88952     // functions:
88953     //  verb(n)     Creates a bound callback to the `step` function for opcode `n`.
88954     //  step(op)    Evaluates opcodes in a generator body until execution is suspended or
88955     //              completed.
88956     //
88957     // The __generator helper understands a limited set of instructions:
88958     //  0: next(value?)     - Start or resume the generator with the specified value.
88959     //  1: throw(error)     - Resume the generator with an exception. If the generator is
88960     //                        suspended inside of one or more protected regions, evaluates
88961     //                        any intervening finally blocks between the current label and
88962     //                        the nearest catch block or function boundary. If uncaught, the
88963     //                        exception is thrown to the caller.
88964     //  2: return(value?)   - Resume the generator as if with a return. If the generator is
88965     //                        suspended inside of one or more protected regions, evaluates any
88966     //                        intervening finally blocks.
88967     //  3: break(label)     - Jump to the specified label. If the label is outside of the
88968     //                        current protected region, evaluates any intervening finally
88969     //                        blocks.
88970     //  4: yield(value?)    - Yield execution to the caller with an optional value. When
88971     //                        resumed, the generator will continue at the next label.
88972     //  5: yield*(value)    - Delegates evaluation to the supplied iterator. When
88973     //                        delegation completes, the generator will continue at the next
88974     //                        label.
88975     //  6: catch(error)     - Handles an exception thrown from within the generator body. If
88976     //                        the current label is inside of one or more protected regions,
88977     //                        evaluates any intervening finally blocks between the current
88978     //                        label and the nearest catch block or function boundary. If
88979     //                        uncaught, the exception is thrown to the caller.
88980     //  7: endfinally       - Ends a finally block, resuming the last instruction prior to
88981     //                        entering a finally block.
88982     //
88983     // For examples of how these are used, see the comments in ./transformers/generators.ts
88984     ts.generatorHelper = {
88985         name: "typescript:generator",
88986         importName: "__generator",
88987         scoped: false,
88988         priority: 6,
88989         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            };"
88990     };
88991 })(ts || (ts = {}));
88992 /*@internal*/
88993 var ts;
88994 (function (ts) {
88995     function transformModule(context) {
88996         function getTransformModuleDelegate(moduleKind) {
88997             switch (moduleKind) {
88998                 case ts.ModuleKind.AMD: return transformAMDModule;
88999                 case ts.ModuleKind.UMD: return transformUMDModule;
89000                 default: return transformCommonJSModule;
89001             }
89002         }
89003         var startLexicalEnvironment = context.startLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistVariableDeclaration = context.hoistVariableDeclaration;
89004         var compilerOptions = context.getCompilerOptions();
89005         var resolver = context.getEmitResolver();
89006         var host = context.getEmitHost();
89007         var languageVersion = ts.getEmitScriptTarget(compilerOptions);
89008         var moduleKind = ts.getEmitModuleKind(compilerOptions);
89009         var previousOnSubstituteNode = context.onSubstituteNode;
89010         var previousOnEmitNode = context.onEmitNode;
89011         context.onSubstituteNode = onSubstituteNode;
89012         context.onEmitNode = onEmitNode;
89013         context.enableSubstitution(75 /* Identifier */); // Substitutes expression identifiers with imported/exported symbols.
89014         context.enableSubstitution(209 /* BinaryExpression */); // Substitutes assignments to exported symbols.
89015         context.enableSubstitution(207 /* PrefixUnaryExpression */); // Substitutes updates to exported symbols.
89016         context.enableSubstitution(208 /* PostfixUnaryExpression */); // Substitutes updates to exported symbols.
89017         context.enableSubstitution(282 /* ShorthandPropertyAssignment */); // Substitutes shorthand property assignments for imported/exported symbols.
89018         context.enableEmitNotification(290 /* SourceFile */); // Restore state when substituting nodes in a file.
89019         var moduleInfoMap = []; // The ExternalModuleInfo for each file.
89020         var deferredExports = []; // Exports to defer until an EndOfDeclarationMarker is found.
89021         var currentSourceFile; // The current file.
89022         var currentModuleInfo; // The ExternalModuleInfo for the current file.
89023         var noSubstitution; // Set of nodes for which substitution rules should be ignored.
89024         var needUMDDynamicImportHelper;
89025         return ts.chainBundle(transformSourceFile);
89026         /**
89027          * Transforms the module aspects of a SourceFile.
89028          *
89029          * @param node The SourceFile node.
89030          */
89031         function transformSourceFile(node) {
89032             if (node.isDeclarationFile ||
89033                 !(ts.isEffectiveExternalModule(node, compilerOptions) ||
89034                     node.transformFlags & 2097152 /* ContainsDynamicImport */ ||
89035                     (ts.isJsonSourceFile(node) && ts.hasJsonModuleEmitEnabled(compilerOptions) && (compilerOptions.out || compilerOptions.outFile)))) {
89036                 return node;
89037             }
89038             currentSourceFile = node;
89039             currentModuleInfo = ts.collectExternalModuleInfo(node, resolver, compilerOptions);
89040             moduleInfoMap[ts.getOriginalNodeId(node)] = currentModuleInfo;
89041             // Perform the transformation.
89042             var transformModule = getTransformModuleDelegate(moduleKind);
89043             var updated = transformModule(node);
89044             currentSourceFile = undefined;
89045             currentModuleInfo = undefined;
89046             needUMDDynamicImportHelper = false;
89047             return ts.aggregateTransformFlags(updated);
89048         }
89049         function shouldEmitUnderscoreUnderscoreESModule() {
89050             if (!currentModuleInfo.exportEquals && ts.isExternalModule(currentSourceFile)) {
89051                 return true;
89052             }
89053             return false;
89054         }
89055         /**
89056          * Transforms a SourceFile into a CommonJS module.
89057          *
89058          * @param node The SourceFile node.
89059          */
89060         function transformCommonJSModule(node) {
89061             startLexicalEnvironment();
89062             var statements = [];
89063             var ensureUseStrict = ts.getStrictOptionValue(compilerOptions, "alwaysStrict") || (!compilerOptions.noImplicitUseStrict && ts.isExternalModule(currentSourceFile));
89064             var statementOffset = ts.addPrologue(statements, node.statements, ensureUseStrict && !ts.isJsonSourceFile(node), sourceElementVisitor);
89065             if (shouldEmitUnderscoreUnderscoreESModule()) {
89066                 ts.append(statements, createUnderscoreUnderscoreESModule());
89067             }
89068             if (ts.length(currentModuleInfo.exportedNames)) {
89069                 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())));
89070             }
89071             ts.append(statements, ts.visitNode(currentModuleInfo.externalHelpersImportDeclaration, sourceElementVisitor, ts.isStatement));
89072             ts.addRange(statements, ts.visitNodes(node.statements, sourceElementVisitor, ts.isStatement, statementOffset));
89073             addExportEqualsIfNeeded(statements, /*emitAsReturn*/ false);
89074             ts.insertStatementsAfterStandardPrologue(statements, endLexicalEnvironment());
89075             var updated = ts.updateSourceFileNode(node, ts.setTextRange(ts.createNodeArray(statements), node.statements));
89076             ts.addEmitHelpers(updated, context.readEmitHelpers());
89077             return updated;
89078         }
89079         /**
89080          * Transforms a SourceFile into an AMD module.
89081          *
89082          * @param node The SourceFile node.
89083          */
89084         function transformAMDModule(node) {
89085             var define = ts.createIdentifier("define");
89086             var moduleName = ts.tryGetModuleNameFromFile(node, host, compilerOptions);
89087             var jsonSourceFile = ts.isJsonSourceFile(node) && node;
89088             // An AMD define function has the following shape:
89089             //
89090             //     define(id?, dependencies?, factory);
89091             //
89092             // This has the shape of the following:
89093             //
89094             //     define(name, ["module1", "module2"], function (module1Alias) { ... }
89095             //
89096             // The location of the alias in the parameter list in the factory function needs to
89097             // match the position of the module name in the dependency list.
89098             //
89099             // To ensure this is true in cases of modules with no aliases, e.g.:
89100             //
89101             //     import "module"
89102             //
89103             // or
89104             //
89105             //     /// <amd-dependency path= "a.css" />
89106             //
89107             // we need to add modules without alias names to the end of the dependencies list
89108             var _a = collectAsynchronousDependencies(node, /*includeNonAmdDependencies*/ true), aliasedModuleNames = _a.aliasedModuleNames, unaliasedModuleNames = _a.unaliasedModuleNames, importAliasNames = _a.importAliasNames;
89109             // Create an updated SourceFile:
89110             //
89111             //     define(moduleName?, ["module1", "module2"], function ...
89112             var updated = ts.updateSourceFileNode(node, ts.setTextRange(ts.createNodeArray([
89113                 ts.createExpressionStatement(ts.createCall(define, 
89114                 /*typeArguments*/ undefined, __spreadArrays((moduleName ? [moduleName] : []), [
89115                     // Add the dependency array argument:
89116                     //
89117                     //     ["require", "exports", module1", "module2", ...]
89118                     ts.createArrayLiteral(jsonSourceFile ? ts.emptyArray : __spreadArrays([
89119                         ts.createLiteral("require"),
89120                         ts.createLiteral("exports")
89121                     ], aliasedModuleNames, unaliasedModuleNames)),
89122                     // Add the module body function argument:
89123                     //
89124                     //     function (require, exports, module1, module2) ...
89125                     jsonSourceFile ?
89126                         jsonSourceFile.statements.length ? jsonSourceFile.statements[0].expression : ts.createObjectLiteral() :
89127                         ts.createFunctionExpression(
89128                         /*modifiers*/ undefined, 
89129                         /*asteriskToken*/ undefined, 
89130                         /*name*/ undefined, 
89131                         /*typeParameters*/ undefined, __spreadArrays([
89132                             ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, "require"),
89133                             ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, "exports")
89134                         ], importAliasNames), 
89135                         /*type*/ undefined, transformAsynchronousModuleBody(node))
89136                 ])))
89137             ]), 
89138             /*location*/ node.statements));
89139             ts.addEmitHelpers(updated, context.readEmitHelpers());
89140             return updated;
89141         }
89142         /**
89143          * Transforms a SourceFile into a UMD module.
89144          *
89145          * @param node The SourceFile node.
89146          */
89147         function transformUMDModule(node) {
89148             var _a = collectAsynchronousDependencies(node, /*includeNonAmdDependencies*/ false), aliasedModuleNames = _a.aliasedModuleNames, unaliasedModuleNames = _a.unaliasedModuleNames, importAliasNames = _a.importAliasNames;
89149             var moduleName = ts.tryGetModuleNameFromFile(node, host, compilerOptions);
89150             var umdHeader = ts.createFunctionExpression(
89151             /*modifiers*/ undefined, 
89152             /*asteriskToken*/ undefined, 
89153             /*name*/ undefined, 
89154             /*typeParameters*/ undefined, [ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, "factory")], 
89155             /*type*/ undefined, ts.setTextRange(ts.createBlock([
89156                 ts.createIf(ts.createLogicalAnd(ts.createTypeCheck(ts.createIdentifier("module"), "object"), ts.createTypeCheck(ts.createPropertyAccess(ts.createIdentifier("module"), "exports"), "object")), ts.createBlock([
89157                     ts.createVariableStatement(
89158                     /*modifiers*/ undefined, [
89159                         ts.createVariableDeclaration("v", 
89160                         /*type*/ undefined, ts.createCall(ts.createIdentifier("factory"), 
89161                         /*typeArguments*/ undefined, [
89162                             ts.createIdentifier("require"),
89163                             ts.createIdentifier("exports")
89164                         ]))
89165                     ]),
89166                     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 */)
89167                 ]), ts.createIf(ts.createLogicalAnd(ts.createTypeCheck(ts.createIdentifier("define"), "function"), ts.createPropertyAccess(ts.createIdentifier("define"), "amd")), ts.createBlock([
89168                     ts.createExpressionStatement(ts.createCall(ts.createIdentifier("define"), 
89169                     /*typeArguments*/ undefined, __spreadArrays((moduleName ? [moduleName] : []), [
89170                         ts.createArrayLiteral(__spreadArrays([
89171                             ts.createLiteral("require"),
89172                             ts.createLiteral("exports")
89173                         ], aliasedModuleNames, unaliasedModuleNames)),
89174                         ts.createIdentifier("factory")
89175                     ])))
89176                 ])))
89177             ], 
89178             /*multiLine*/ true), 
89179             /*location*/ undefined));
89180             // Create an updated SourceFile:
89181             //
89182             //  (function (factory) {
89183             //      if (typeof module === "object" && typeof module.exports === "object") {
89184             //          var v = factory(require, exports);
89185             //          if (v !== undefined) module.exports = v;
89186             //      }
89187             //      else if (typeof define === 'function' && define.amd) {
89188             //          define(["require", "exports"], factory);
89189             //      }
89190             //  })(function ...)
89191             var updated = ts.updateSourceFileNode(node, ts.setTextRange(ts.createNodeArray([
89192                 ts.createExpressionStatement(ts.createCall(umdHeader, 
89193                 /*typeArguments*/ undefined, [
89194                     // Add the module body function argument:
89195                     //
89196                     //     function (require, exports) ...
89197                     ts.createFunctionExpression(
89198                     /*modifiers*/ undefined, 
89199                     /*asteriskToken*/ undefined, 
89200                     /*name*/ undefined, 
89201                     /*typeParameters*/ undefined, __spreadArrays([
89202                         ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, "require"),
89203                         ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, "exports")
89204                     ], importAliasNames), 
89205                     /*type*/ undefined, transformAsynchronousModuleBody(node))
89206                 ]))
89207             ]), 
89208             /*location*/ node.statements));
89209             ts.addEmitHelpers(updated, context.readEmitHelpers());
89210             return updated;
89211         }
89212         /**
89213          * Collect the additional asynchronous dependencies for the module.
89214          *
89215          * @param node The source file.
89216          * @param includeNonAmdDependencies A value indicating whether to include non-AMD dependencies.
89217          */
89218         function collectAsynchronousDependencies(node, includeNonAmdDependencies) {
89219             // names of modules with corresponding parameter in the factory function
89220             var aliasedModuleNames = [];
89221             // names of modules with no corresponding parameters in factory function
89222             var unaliasedModuleNames = [];
89223             // names of the parameters in the factory function; these
89224             // parameters need to match the indexes of the corresponding
89225             // module names in aliasedModuleNames.
89226             var importAliasNames = [];
89227             // Fill in amd-dependency tags
89228             for (var _i = 0, _a = node.amdDependencies; _i < _a.length; _i++) {
89229                 var amdDependency = _a[_i];
89230                 if (amdDependency.name) {
89231                     aliasedModuleNames.push(ts.createLiteral(amdDependency.path));
89232                     importAliasNames.push(ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, amdDependency.name));
89233                 }
89234                 else {
89235                     unaliasedModuleNames.push(ts.createLiteral(amdDependency.path));
89236                 }
89237             }
89238             for (var _b = 0, _c = currentModuleInfo.externalImports; _b < _c.length; _b++) {
89239                 var importNode = _c[_b];
89240                 // Find the name of the external module
89241                 var externalModuleName = ts.getExternalModuleNameLiteral(importNode, currentSourceFile, host, resolver, compilerOptions);
89242                 // Find the name of the module alias, if there is one
89243                 var importAliasName = ts.getLocalNameForExternalImport(importNode, currentSourceFile);
89244                 // It is possible that externalModuleName is undefined if it is not string literal.
89245                 // This can happen in the invalid import syntax.
89246                 // E.g : "import * from alias from 'someLib';"
89247                 if (externalModuleName) {
89248                     if (includeNonAmdDependencies && importAliasName) {
89249                         // Set emitFlags on the name of the classDeclaration
89250                         // This is so that when printer will not substitute the identifier
89251                         ts.setEmitFlags(importAliasName, 4 /* NoSubstitution */);
89252                         aliasedModuleNames.push(externalModuleName);
89253                         importAliasNames.push(ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, importAliasName));
89254                     }
89255                     else {
89256                         unaliasedModuleNames.push(externalModuleName);
89257                     }
89258                 }
89259             }
89260             return { aliasedModuleNames: aliasedModuleNames, unaliasedModuleNames: unaliasedModuleNames, importAliasNames: importAliasNames };
89261         }
89262         function getAMDImportExpressionForImport(node) {
89263             if (ts.isImportEqualsDeclaration(node) || ts.isExportDeclaration(node) || !ts.getExternalModuleNameLiteral(node, currentSourceFile, host, resolver, compilerOptions)) {
89264                 return undefined;
89265             }
89266             var name = ts.getLocalNameForExternalImport(node, currentSourceFile); // TODO: GH#18217
89267             var expr = getHelperExpressionForImport(node, name);
89268             if (expr === name) {
89269                 return undefined;
89270             }
89271             return ts.createExpressionStatement(ts.createAssignment(name, expr));
89272         }
89273         /**
89274          * Transforms a SourceFile into an AMD or UMD module body.
89275          *
89276          * @param node The SourceFile node.
89277          */
89278         function transformAsynchronousModuleBody(node) {
89279             startLexicalEnvironment();
89280             var statements = [];
89281             var statementOffset = ts.addPrologue(statements, node.statements, /*ensureUseStrict*/ !compilerOptions.noImplicitUseStrict, sourceElementVisitor);
89282             if (shouldEmitUnderscoreUnderscoreESModule()) {
89283                 ts.append(statements, createUnderscoreUnderscoreESModule());
89284             }
89285             if (ts.length(currentModuleInfo.exportedNames)) {
89286                 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())));
89287             }
89288             // Visit each statement of the module body.
89289             ts.append(statements, ts.visitNode(currentModuleInfo.externalHelpersImportDeclaration, sourceElementVisitor, ts.isStatement));
89290             if (moduleKind === ts.ModuleKind.AMD) {
89291                 ts.addRange(statements, ts.mapDefined(currentModuleInfo.externalImports, getAMDImportExpressionForImport));
89292             }
89293             ts.addRange(statements, ts.visitNodes(node.statements, sourceElementVisitor, ts.isStatement, statementOffset));
89294             // Append the 'export =' statement if provided.
89295             addExportEqualsIfNeeded(statements, /*emitAsReturn*/ true);
89296             // End the lexical environment for the module body
89297             // and merge any new lexical declarations.
89298             ts.insertStatementsAfterStandardPrologue(statements, endLexicalEnvironment());
89299             var body = ts.createBlock(statements, /*multiLine*/ true);
89300             if (needUMDDynamicImportHelper) {
89301                 ts.addEmitHelper(body, dynamicImportUMDHelper);
89302             }
89303             return body;
89304         }
89305         /**
89306          * Adds the down-level representation of `export=` to the statement list if one exists
89307          * in the source file.
89308          *
89309          * @param statements The Statement list to modify.
89310          * @param emitAsReturn A value indicating whether to emit the `export=` statement as a
89311          * return statement.
89312          */
89313         function addExportEqualsIfNeeded(statements, emitAsReturn) {
89314             if (currentModuleInfo.exportEquals) {
89315                 var expressionResult = ts.visitNode(currentModuleInfo.exportEquals.expression, moduleExpressionElementVisitor);
89316                 if (expressionResult) {
89317                     if (emitAsReturn) {
89318                         var statement = ts.createReturn(expressionResult);
89319                         ts.setTextRange(statement, currentModuleInfo.exportEquals);
89320                         ts.setEmitFlags(statement, 384 /* NoTokenSourceMaps */ | 1536 /* NoComments */);
89321                         statements.push(statement);
89322                     }
89323                     else {
89324                         var statement = ts.createExpressionStatement(ts.createAssignment(ts.createPropertyAccess(ts.createIdentifier("module"), "exports"), expressionResult));
89325                         ts.setTextRange(statement, currentModuleInfo.exportEquals);
89326                         ts.setEmitFlags(statement, 1536 /* NoComments */);
89327                         statements.push(statement);
89328                     }
89329                 }
89330             }
89331         }
89332         //
89333         // Top-Level Source Element Visitors
89334         //
89335         /**
89336          * Visits a node at the top level of the source file.
89337          *
89338          * @param node The node to visit.
89339          */
89340         function sourceElementVisitor(node) {
89341             switch (node.kind) {
89342                 case 254 /* ImportDeclaration */:
89343                     return visitImportDeclaration(node);
89344                 case 253 /* ImportEqualsDeclaration */:
89345                     return visitImportEqualsDeclaration(node);
89346                 case 260 /* ExportDeclaration */:
89347                     return visitExportDeclaration(node);
89348                 case 259 /* ExportAssignment */:
89349                     return visitExportAssignment(node);
89350                 case 225 /* VariableStatement */:
89351                     return visitVariableStatement(node);
89352                 case 244 /* FunctionDeclaration */:
89353                     return visitFunctionDeclaration(node);
89354                 case 245 /* ClassDeclaration */:
89355                     return visitClassDeclaration(node);
89356                 case 328 /* MergeDeclarationMarker */:
89357                     return visitMergeDeclarationMarker(node);
89358                 case 329 /* EndOfDeclarationMarker */:
89359                     return visitEndOfDeclarationMarker(node);
89360                 default:
89361                     return ts.visitEachChild(node, moduleExpressionElementVisitor, context);
89362             }
89363         }
89364         function moduleExpressionElementVisitor(node) {
89365             // This visitor does not need to descend into the tree if there is no dynamic import or destructuring assignment,
89366             // as export/import statements are only transformed at the top level of a file.
89367             if (!(node.transformFlags & 2097152 /* ContainsDynamicImport */) && !(node.transformFlags & 1024 /* ContainsDestructuringAssignment */)) {
89368                 return node;
89369             }
89370             if (ts.isImportCall(node)) {
89371                 return visitImportCallExpression(node);
89372             }
89373             else if (ts.isDestructuringAssignment(node)) {
89374                 return visitDestructuringAssignment(node);
89375             }
89376             else {
89377                 return ts.visitEachChild(node, moduleExpressionElementVisitor, context);
89378             }
89379         }
89380         function destructuringNeedsFlattening(node) {
89381             if (ts.isObjectLiteralExpression(node)) {
89382                 for (var _i = 0, _a = node.properties; _i < _a.length; _i++) {
89383                     var elem = _a[_i];
89384                     switch (elem.kind) {
89385                         case 281 /* PropertyAssignment */:
89386                             if (destructuringNeedsFlattening(elem.initializer)) {
89387                                 return true;
89388                             }
89389                             break;
89390                         case 282 /* ShorthandPropertyAssignment */:
89391                             if (destructuringNeedsFlattening(elem.name)) {
89392                                 return true;
89393                             }
89394                             break;
89395                         case 283 /* SpreadAssignment */:
89396                             if (destructuringNeedsFlattening(elem.expression)) {
89397                                 return true;
89398                             }
89399                             break;
89400                         case 161 /* MethodDeclaration */:
89401                         case 163 /* GetAccessor */:
89402                         case 164 /* SetAccessor */:
89403                             return false;
89404                         default: ts.Debug.assertNever(elem, "Unhandled object member kind");
89405                     }
89406                 }
89407             }
89408             else if (ts.isArrayLiteralExpression(node)) {
89409                 for (var _b = 0, _c = node.elements; _b < _c.length; _b++) {
89410                     var elem = _c[_b];
89411                     if (ts.isSpreadElement(elem)) {
89412                         if (destructuringNeedsFlattening(elem.expression)) {
89413                             return true;
89414                         }
89415                     }
89416                     else if (destructuringNeedsFlattening(elem)) {
89417                         return true;
89418                     }
89419                 }
89420             }
89421             else if (ts.isIdentifier(node)) {
89422                 return ts.length(getExports(node)) > (ts.isExportName(node) ? 1 : 0);
89423             }
89424             return false;
89425         }
89426         function visitDestructuringAssignment(node) {
89427             if (destructuringNeedsFlattening(node.left)) {
89428                 return ts.flattenDestructuringAssignment(node, moduleExpressionElementVisitor, context, 0 /* All */, /*needsValue*/ false, createAllExportExpressions);
89429             }
89430             return ts.visitEachChild(node, moduleExpressionElementVisitor, context);
89431         }
89432         function visitImportCallExpression(node) {
89433             var argument = ts.visitNode(ts.firstOrUndefined(node.arguments), moduleExpressionElementVisitor);
89434             var containsLexicalThis = !!(node.transformFlags & 4096 /* ContainsLexicalThis */);
89435             switch (compilerOptions.module) {
89436                 case ts.ModuleKind.AMD:
89437                     return createImportCallExpressionAMD(argument, containsLexicalThis);
89438                 case ts.ModuleKind.UMD:
89439                     return createImportCallExpressionUMD(argument, containsLexicalThis);
89440                 case ts.ModuleKind.CommonJS:
89441                 default:
89442                     return createImportCallExpressionCommonJS(argument, containsLexicalThis);
89443             }
89444         }
89445         function createImportCallExpressionUMD(arg, containsLexicalThis) {
89446             // (function (factory) {
89447             //      ... (regular UMD)
89448             // }
89449             // })(function (require, exports, useSyncRequire) {
89450             //      "use strict";
89451             //      Object.defineProperty(exports, "__esModule", { value: true });
89452             //      var __syncRequire = typeof module === "object" && typeof module.exports === "object";
89453             //      var __resolved = new Promise(function (resolve) { resolve(); });
89454             //      .....
89455             //      __syncRequire
89456             //          ? __resolved.then(function () { return require(x); }) /*CommonJs Require*/
89457             //          : new Promise(function (_a, _b) { require([x], _a, _b); }); /*Amd Require*/
89458             // });
89459             needUMDDynamicImportHelper = true;
89460             if (ts.isSimpleCopiableExpression(arg)) {
89461                 var argClone = ts.isGeneratedIdentifier(arg) ? arg : ts.isStringLiteral(arg) ? ts.createLiteral(arg) : ts.setEmitFlags(ts.setTextRange(ts.getSynthesizedClone(arg), arg), 1536 /* NoComments */);
89462                 return ts.createConditional(
89463                 /*condition*/ ts.createIdentifier("__syncRequire"), 
89464                 /*whenTrue*/ createImportCallExpressionCommonJS(arg, containsLexicalThis), 
89465                 /*whenFalse*/ createImportCallExpressionAMD(argClone, containsLexicalThis));
89466             }
89467             else {
89468                 var temp = ts.createTempVariable(hoistVariableDeclaration);
89469                 return ts.createComma(ts.createAssignment(temp, arg), ts.createConditional(
89470                 /*condition*/ ts.createIdentifier("__syncRequire"), 
89471                 /*whenTrue*/ createImportCallExpressionCommonJS(temp, containsLexicalThis), 
89472                 /*whenFalse*/ createImportCallExpressionAMD(temp, containsLexicalThis)));
89473             }
89474         }
89475         function createImportCallExpressionAMD(arg, containsLexicalThis) {
89476             // improt("./blah")
89477             // emit as
89478             // define(["require", "exports", "blah"], function (require, exports) {
89479             //     ...
89480             //     new Promise(function (_a, _b) { require([x], _a, _b); }); /*Amd Require*/
89481             // });
89482             var resolve = ts.createUniqueName("resolve");
89483             var reject = ts.createUniqueName("reject");
89484             var parameters = [
89485                 ts.createParameter(/*decorator*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, /*name*/ resolve),
89486                 ts.createParameter(/*decorator*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, /*name*/ reject)
89487             ];
89488             var body = ts.createBlock([
89489                 ts.createExpressionStatement(ts.createCall(ts.createIdentifier("require"), 
89490                 /*typeArguments*/ undefined, [ts.createArrayLiteral([arg || ts.createOmittedExpression()]), resolve, reject]))
89491             ]);
89492             var func;
89493             if (languageVersion >= 2 /* ES2015 */) {
89494                 func = ts.createArrowFunction(
89495                 /*modifiers*/ undefined, 
89496                 /*typeParameters*/ undefined, parameters, 
89497                 /*type*/ undefined, 
89498                 /*equalsGreaterThanToken*/ undefined, body);
89499             }
89500             else {
89501                 func = ts.createFunctionExpression(
89502                 /*modifiers*/ undefined, 
89503                 /*asteriskToken*/ undefined, 
89504                 /*name*/ undefined, 
89505                 /*typeParameters*/ undefined, parameters, 
89506                 /*type*/ undefined, body);
89507                 // if there is a lexical 'this' in the import call arguments, ensure we indicate
89508                 // that this new function expression indicates it captures 'this' so that the
89509                 // es2015 transformer will properly substitute 'this' with '_this'.
89510                 if (containsLexicalThis) {
89511                     ts.setEmitFlags(func, 8 /* CapturesThis */);
89512                 }
89513             }
89514             var promise = ts.createNew(ts.createIdentifier("Promise"), /*typeArguments*/ undefined, [func]);
89515             if (compilerOptions.esModuleInterop) {
89516                 context.requestEmitHelper(ts.importStarHelper);
89517                 return ts.createCall(ts.createPropertyAccess(promise, ts.createIdentifier("then")), /*typeArguments*/ undefined, [ts.getUnscopedHelperName("__importStar")]);
89518             }
89519             return promise;
89520         }
89521         function createImportCallExpressionCommonJS(arg, containsLexicalThis) {
89522             // import("./blah")
89523             // emit as
89524             // Promise.resolve().then(function () { return require(x); }) /*CommonJs Require*/
89525             // We have to wrap require in then callback so that require is done in asynchronously
89526             // if we simply do require in resolve callback in Promise constructor. We will execute the loading immediately
89527             var promiseResolveCall = ts.createCall(ts.createPropertyAccess(ts.createIdentifier("Promise"), "resolve"), /*typeArguments*/ undefined, /*argumentsArray*/ []);
89528             var requireCall = ts.createCall(ts.createIdentifier("require"), /*typeArguments*/ undefined, arg ? [arg] : []);
89529             if (compilerOptions.esModuleInterop) {
89530                 context.requestEmitHelper(ts.importStarHelper);
89531                 requireCall = ts.createCall(ts.getUnscopedHelperName("__importStar"), /*typeArguments*/ undefined, [requireCall]);
89532             }
89533             var func;
89534             if (languageVersion >= 2 /* ES2015 */) {
89535                 func = ts.createArrowFunction(
89536                 /*modifiers*/ undefined, 
89537                 /*typeParameters*/ undefined, 
89538                 /*parameters*/ [], 
89539                 /*type*/ undefined, 
89540                 /*equalsGreaterThanToken*/ undefined, requireCall);
89541             }
89542             else {
89543                 func = ts.createFunctionExpression(
89544                 /*modifiers*/ undefined, 
89545                 /*asteriskToken*/ undefined, 
89546                 /*name*/ undefined, 
89547                 /*typeParameters*/ undefined, 
89548                 /*parameters*/ [], 
89549                 /*type*/ undefined, ts.createBlock([ts.createReturn(requireCall)]));
89550                 // if there is a lexical 'this' in the import call arguments, ensure we indicate
89551                 // that this new function expression indicates it captures 'this' so that the
89552                 // es2015 transformer will properly substitute 'this' with '_this'.
89553                 if (containsLexicalThis) {
89554                     ts.setEmitFlags(func, 8 /* CapturesThis */);
89555                 }
89556             }
89557             return ts.createCall(ts.createPropertyAccess(promiseResolveCall, "then"), /*typeArguments*/ undefined, [func]);
89558         }
89559         function getHelperExpressionForExport(node, innerExpr) {
89560             if (!compilerOptions.esModuleInterop || ts.getEmitFlags(node) & 67108864 /* NeverApplyImportHelper */) {
89561                 return innerExpr;
89562             }
89563             if (ts.getExportNeedsImportStarHelper(node)) {
89564                 context.requestEmitHelper(ts.importStarHelper);
89565                 return ts.createCall(ts.getUnscopedHelperName("__importStar"), /*typeArguments*/ undefined, [innerExpr]);
89566             }
89567             return innerExpr;
89568         }
89569         function getHelperExpressionForImport(node, innerExpr) {
89570             if (!compilerOptions.esModuleInterop || ts.getEmitFlags(node) & 67108864 /* NeverApplyImportHelper */) {
89571                 return innerExpr;
89572             }
89573             if (ts.getImportNeedsImportStarHelper(node)) {
89574                 context.requestEmitHelper(ts.importStarHelper);
89575                 return ts.createCall(ts.getUnscopedHelperName("__importStar"), /*typeArguments*/ undefined, [innerExpr]);
89576             }
89577             if (ts.getImportNeedsImportDefaultHelper(node)) {
89578                 context.requestEmitHelper(ts.importDefaultHelper);
89579                 return ts.createCall(ts.getUnscopedHelperName("__importDefault"), /*typeArguments*/ undefined, [innerExpr]);
89580             }
89581             return innerExpr;
89582         }
89583         /**
89584          * Visits an ImportDeclaration node.
89585          *
89586          * @param node The node to visit.
89587          */
89588         function visitImportDeclaration(node) {
89589             var statements;
89590             var namespaceDeclaration = ts.getNamespaceDeclarationNode(node);
89591             if (moduleKind !== ts.ModuleKind.AMD) {
89592                 if (!node.importClause) {
89593                     // import "mod";
89594                     return ts.setOriginalNode(ts.setTextRange(ts.createExpressionStatement(createRequireCall(node)), node), node);
89595                 }
89596                 else {
89597                     var variables = [];
89598                     if (namespaceDeclaration && !ts.isDefaultImport(node)) {
89599                         // import * as n from "mod";
89600                         variables.push(ts.createVariableDeclaration(ts.getSynthesizedClone(namespaceDeclaration.name), 
89601                         /*type*/ undefined, getHelperExpressionForImport(node, createRequireCall(node))));
89602                     }
89603                     else {
89604                         // import d from "mod";
89605                         // import { x, y } from "mod";
89606                         // import d, { x, y } from "mod";
89607                         // import d, * as n from "mod";
89608                         variables.push(ts.createVariableDeclaration(ts.getGeneratedNameForNode(node), 
89609                         /*type*/ undefined, getHelperExpressionForImport(node, createRequireCall(node))));
89610                         if (namespaceDeclaration && ts.isDefaultImport(node)) {
89611                             variables.push(ts.createVariableDeclaration(ts.getSynthesizedClone(namespaceDeclaration.name), 
89612                             /*type*/ undefined, ts.getGeneratedNameForNode(node)));
89613                         }
89614                     }
89615                     statements = ts.append(statements, ts.setOriginalNode(ts.setTextRange(ts.createVariableStatement(
89616                     /*modifiers*/ undefined, ts.createVariableDeclarationList(variables, languageVersion >= 2 /* ES2015 */ ? 2 /* Const */ : 0 /* None */)), 
89617                     /*location*/ node), 
89618                     /*original*/ node));
89619                 }
89620             }
89621             else if (namespaceDeclaration && ts.isDefaultImport(node)) {
89622                 // import d, * as n from "mod";
89623                 statements = ts.append(statements, ts.createVariableStatement(
89624                 /*modifiers*/ undefined, ts.createVariableDeclarationList([
89625                     ts.setOriginalNode(ts.setTextRange(ts.createVariableDeclaration(ts.getSynthesizedClone(namespaceDeclaration.name), 
89626                     /*type*/ undefined, ts.getGeneratedNameForNode(node)), 
89627                     /*location*/ node), 
89628                     /*original*/ node)
89629                 ], languageVersion >= 2 /* ES2015 */ ? 2 /* Const */ : 0 /* None */)));
89630             }
89631             if (hasAssociatedEndOfDeclarationMarker(node)) {
89632                 // Defer exports until we encounter an EndOfDeclarationMarker node
89633                 var id = ts.getOriginalNodeId(node);
89634                 deferredExports[id] = appendExportsOfImportDeclaration(deferredExports[id], node);
89635             }
89636             else {
89637                 statements = appendExportsOfImportDeclaration(statements, node);
89638             }
89639             return ts.singleOrMany(statements);
89640         }
89641         /**
89642          * Creates a `require()` call to import an external module.
89643          *
89644          * @param importNode The declararation to import.
89645          */
89646         function createRequireCall(importNode) {
89647             var moduleName = ts.getExternalModuleNameLiteral(importNode, currentSourceFile, host, resolver, compilerOptions);
89648             var args = [];
89649             if (moduleName) {
89650                 args.push(moduleName);
89651             }
89652             return ts.createCall(ts.createIdentifier("require"), /*typeArguments*/ undefined, args);
89653         }
89654         /**
89655          * Visits an ImportEqualsDeclaration node.
89656          *
89657          * @param node The node to visit.
89658          */
89659         function visitImportEqualsDeclaration(node) {
89660             ts.Debug.assert(ts.isExternalModuleImportEqualsDeclaration(node), "import= for internal module references should be handled in an earlier transformer.");
89661             var statements;
89662             if (moduleKind !== ts.ModuleKind.AMD) {
89663                 if (ts.hasModifier(node, 1 /* Export */)) {
89664                     statements = ts.append(statements, ts.setOriginalNode(ts.setTextRange(ts.createExpressionStatement(createExportExpression(node.name, createRequireCall(node))), node), node));
89665                 }
89666                 else {
89667                     statements = ts.append(statements, ts.setOriginalNode(ts.setTextRange(ts.createVariableStatement(
89668                     /*modifiers*/ undefined, ts.createVariableDeclarationList([
89669                         ts.createVariableDeclaration(ts.getSynthesizedClone(node.name), 
89670                         /*type*/ undefined, createRequireCall(node))
89671                     ], 
89672                     /*flags*/ languageVersion >= 2 /* ES2015 */ ? 2 /* Const */ : 0 /* None */)), node), node));
89673                 }
89674             }
89675             else {
89676                 if (ts.hasModifier(node, 1 /* Export */)) {
89677                     statements = ts.append(statements, ts.setOriginalNode(ts.setTextRange(ts.createExpressionStatement(createExportExpression(ts.getExportName(node), ts.getLocalName(node))), node), node));
89678                 }
89679             }
89680             if (hasAssociatedEndOfDeclarationMarker(node)) {
89681                 // Defer exports until we encounter an EndOfDeclarationMarker node
89682                 var id = ts.getOriginalNodeId(node);
89683                 deferredExports[id] = appendExportsOfImportEqualsDeclaration(deferredExports[id], node);
89684             }
89685             else {
89686                 statements = appendExportsOfImportEqualsDeclaration(statements, node);
89687             }
89688             return ts.singleOrMany(statements);
89689         }
89690         /**
89691          * Visits an ExportDeclaration node.
89692          *
89693          * @param The node to visit.
89694          */
89695         function visitExportDeclaration(node) {
89696             if (!node.moduleSpecifier) {
89697                 // Elide export declarations with no module specifier as they are handled
89698                 // elsewhere.
89699                 return undefined;
89700             }
89701             var generatedName = ts.getGeneratedNameForNode(node);
89702             if (node.exportClause && ts.isNamedExports(node.exportClause)) {
89703                 var statements = [];
89704                 // export { x, y } from "mod";
89705                 if (moduleKind !== ts.ModuleKind.AMD) {
89706                     statements.push(ts.setOriginalNode(ts.setTextRange(ts.createVariableStatement(
89707                     /*modifiers*/ undefined, ts.createVariableDeclarationList([
89708                         ts.createVariableDeclaration(generatedName, 
89709                         /*type*/ undefined, createRequireCall(node))
89710                     ])), 
89711                     /*location*/ node), 
89712                     /* original */ node));
89713                 }
89714                 for (var _i = 0, _a = node.exportClause.elements; _i < _a.length; _i++) {
89715                     var specifier = _a[_i];
89716                     if (languageVersion === 0 /* ES3 */) {
89717                         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));
89718                     }
89719                     else {
89720                         var exportedValue = ts.createPropertyAccess(generatedName, specifier.propertyName || specifier.name);
89721                         statements.push(ts.setOriginalNode(ts.setTextRange(ts.createExpressionStatement(createExportExpression(ts.getExportName(specifier), exportedValue, /* location */ undefined, /* liveBinding */ true)), specifier), specifier));
89722                     }
89723                 }
89724                 return ts.singleOrMany(statements);
89725             }
89726             else if (node.exportClause) {
89727                 var statements = [];
89728                 // export * as ns from "mod";
89729                 statements.push(ts.setOriginalNode(ts.setTextRange(ts.createExpressionStatement(createExportExpression(ts.getSynthesizedClone(node.exportClause.name), moduleKind !== ts.ModuleKind.AMD ?
89730                     getHelperExpressionForExport(node, createRequireCall(node)) :
89731                     ts.createIdentifier(ts.idText(node.exportClause.name)))), node), node));
89732                 return ts.singleOrMany(statements);
89733             }
89734             else {
89735                 // export * from "mod";
89736                 return ts.setOriginalNode(ts.setTextRange(ts.createExpressionStatement(createExportStarHelper(context, moduleKind !== ts.ModuleKind.AMD ? createRequireCall(node) : generatedName)), node), node);
89737             }
89738         }
89739         /**
89740          * Visits an ExportAssignment node.
89741          *
89742          * @param node The node to visit.
89743          */
89744         function visitExportAssignment(node) {
89745             if (node.isExportEquals) {
89746                 return undefined;
89747             }
89748             var statements;
89749             var original = node.original;
89750             if (original && hasAssociatedEndOfDeclarationMarker(original)) {
89751                 // Defer exports until we encounter an EndOfDeclarationMarker node
89752                 var id = ts.getOriginalNodeId(node);
89753                 deferredExports[id] = appendExportStatement(deferredExports[id], ts.createIdentifier("default"), ts.visitNode(node.expression, moduleExpressionElementVisitor), /*location*/ node, /*allowComments*/ true);
89754             }
89755             else {
89756                 statements = appendExportStatement(statements, ts.createIdentifier("default"), ts.visitNode(node.expression, moduleExpressionElementVisitor), /*location*/ node, /*allowComments*/ true);
89757             }
89758             return ts.singleOrMany(statements);
89759         }
89760         /**
89761          * Visits a FunctionDeclaration node.
89762          *
89763          * @param node The node to visit.
89764          */
89765         function visitFunctionDeclaration(node) {
89766             var statements;
89767             if (ts.hasModifier(node, 1 /* Export */)) {
89768                 statements = ts.append(statements, ts.setOriginalNode(ts.setTextRange(ts.createFunctionDeclaration(
89769                 /*decorators*/ undefined, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), node.asteriskToken, ts.getDeclarationName(node, /*allowComments*/ true, /*allowSourceMaps*/ true), 
89770                 /*typeParameters*/ undefined, ts.visitNodes(node.parameters, moduleExpressionElementVisitor), 
89771                 /*type*/ undefined, ts.visitEachChild(node.body, moduleExpressionElementVisitor, context)), 
89772                 /*location*/ node), 
89773                 /*original*/ node));
89774             }
89775             else {
89776                 statements = ts.append(statements, ts.visitEachChild(node, moduleExpressionElementVisitor, context));
89777             }
89778             if (hasAssociatedEndOfDeclarationMarker(node)) {
89779                 // Defer exports until we encounter an EndOfDeclarationMarker node
89780                 var id = ts.getOriginalNodeId(node);
89781                 deferredExports[id] = appendExportsOfHoistedDeclaration(deferredExports[id], node);
89782             }
89783             else {
89784                 statements = appendExportsOfHoistedDeclaration(statements, node);
89785             }
89786             return ts.singleOrMany(statements);
89787         }
89788         /**
89789          * Visits a ClassDeclaration node.
89790          *
89791          * @param node The node to visit.
89792          */
89793         function visitClassDeclaration(node) {
89794             var statements;
89795             if (ts.hasModifier(node, 1 /* Export */)) {
89796                 statements = ts.append(statements, ts.setOriginalNode(ts.setTextRange(ts.createClassDeclaration(
89797                 /*decorators*/ undefined, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), ts.getDeclarationName(node, /*allowComments*/ true, /*allowSourceMaps*/ true), 
89798                 /*typeParameters*/ undefined, ts.visitNodes(node.heritageClauses, moduleExpressionElementVisitor), ts.visitNodes(node.members, moduleExpressionElementVisitor)), node), node));
89799             }
89800             else {
89801                 statements = ts.append(statements, ts.visitEachChild(node, moduleExpressionElementVisitor, context));
89802             }
89803             if (hasAssociatedEndOfDeclarationMarker(node)) {
89804                 // Defer exports until we encounter an EndOfDeclarationMarker node
89805                 var id = ts.getOriginalNodeId(node);
89806                 deferredExports[id] = appendExportsOfHoistedDeclaration(deferredExports[id], node);
89807             }
89808             else {
89809                 statements = appendExportsOfHoistedDeclaration(statements, node);
89810             }
89811             return ts.singleOrMany(statements);
89812         }
89813         /**
89814          * Visits a VariableStatement node.
89815          *
89816          * @param node The node to visit.
89817          */
89818         function visitVariableStatement(node) {
89819             var statements;
89820             var variables;
89821             var expressions;
89822             if (ts.hasModifier(node, 1 /* Export */)) {
89823                 var modifiers = void 0;
89824                 // If we're exporting these variables, then these just become assignments to 'exports.x'.
89825                 for (var _i = 0, _a = node.declarationList.declarations; _i < _a.length; _i++) {
89826                     var variable = _a[_i];
89827                     if (ts.isIdentifier(variable.name) && ts.isLocalName(variable.name)) {
89828                         if (!modifiers) {
89829                             modifiers = ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier);
89830                         }
89831                         variables = ts.append(variables, variable);
89832                     }
89833                     else if (variable.initializer) {
89834                         expressions = ts.append(expressions, transformInitializedVariable(variable));
89835                     }
89836                 }
89837                 if (variables) {
89838                     statements = ts.append(statements, ts.updateVariableStatement(node, modifiers, ts.updateVariableDeclarationList(node.declarationList, variables)));
89839                 }
89840                 if (expressions) {
89841                     statements = ts.append(statements, ts.setOriginalNode(ts.setTextRange(ts.createExpressionStatement(ts.inlineExpressions(expressions)), node), node));
89842                 }
89843             }
89844             else {
89845                 statements = ts.append(statements, ts.visitEachChild(node, moduleExpressionElementVisitor, context));
89846             }
89847             if (hasAssociatedEndOfDeclarationMarker(node)) {
89848                 // Defer exports until we encounter an EndOfDeclarationMarker node
89849                 var id = ts.getOriginalNodeId(node);
89850                 deferredExports[id] = appendExportsOfVariableStatement(deferredExports[id], node);
89851             }
89852             else {
89853                 statements = appendExportsOfVariableStatement(statements, node);
89854             }
89855             return ts.singleOrMany(statements);
89856         }
89857         function createAllExportExpressions(name, value, location) {
89858             var exportedNames = getExports(name);
89859             if (exportedNames) {
89860                 // For each additional export of the declaration, apply an export assignment.
89861                 var expression = ts.isExportName(name) ? value : ts.createAssignment(name, value);
89862                 for (var _i = 0, exportedNames_1 = exportedNames; _i < exportedNames_1.length; _i++) {
89863                     var exportName = exportedNames_1[_i];
89864                     // Mark the node to prevent triggering substitution.
89865                     ts.setEmitFlags(expression, 4 /* NoSubstitution */);
89866                     expression = createExportExpression(exportName, expression, /*location*/ location);
89867                 }
89868                 return expression;
89869             }
89870             return ts.createAssignment(name, value);
89871         }
89872         /**
89873          * Transforms an exported variable with an initializer into an expression.
89874          *
89875          * @param node The node to transform.
89876          */
89877         function transformInitializedVariable(node) {
89878             if (ts.isBindingPattern(node.name)) {
89879                 return ts.flattenDestructuringAssignment(ts.visitNode(node, moduleExpressionElementVisitor), 
89880                 /*visitor*/ undefined, context, 0 /* All */, 
89881                 /*needsValue*/ false, createAllExportExpressions);
89882             }
89883             else {
89884                 return ts.createAssignment(ts.setTextRange(ts.createPropertyAccess(ts.createIdentifier("exports"), node.name), 
89885                 /*location*/ node.name), node.initializer ? ts.visitNode(node.initializer, moduleExpressionElementVisitor) : ts.createVoidZero());
89886             }
89887         }
89888         /**
89889          * Visits a MergeDeclarationMarker used as a placeholder for the beginning of a merged
89890          * and transformed declaration.
89891          *
89892          * @param node The node to visit.
89893          */
89894         function visitMergeDeclarationMarker(node) {
89895             // For an EnumDeclaration or ModuleDeclaration that merges with a preceeding
89896             // declaration we do not emit a leading variable declaration. To preserve the
89897             // begin/end semantics of the declararation and to properly handle exports
89898             // we wrapped the leading variable declaration in a `MergeDeclarationMarker`.
89899             //
89900             // To balance the declaration, add the exports of the elided variable
89901             // statement.
89902             if (hasAssociatedEndOfDeclarationMarker(node) && node.original.kind === 225 /* VariableStatement */) {
89903                 var id = ts.getOriginalNodeId(node);
89904                 deferredExports[id] = appendExportsOfVariableStatement(deferredExports[id], node.original);
89905             }
89906             return node;
89907         }
89908         /**
89909          * Determines whether a node has an associated EndOfDeclarationMarker.
89910          *
89911          * @param node The node to test.
89912          */
89913         function hasAssociatedEndOfDeclarationMarker(node) {
89914             return (ts.getEmitFlags(node) & 4194304 /* HasEndOfDeclarationMarker */) !== 0;
89915         }
89916         /**
89917          * Visits a DeclarationMarker used as a placeholder for the end of a transformed
89918          * declaration.
89919          *
89920          * @param node The node to visit.
89921          */
89922         function visitEndOfDeclarationMarker(node) {
89923             // For some transformations we emit an `EndOfDeclarationMarker` to mark the actual
89924             // end of the transformed declaration. We use this marker to emit any deferred exports
89925             // of the declaration.
89926             var id = ts.getOriginalNodeId(node);
89927             var statements = deferredExports[id];
89928             if (statements) {
89929                 delete deferredExports[id];
89930                 return ts.append(statements, node);
89931             }
89932             return node;
89933         }
89934         /**
89935          * Appends the exports of an ImportDeclaration to a statement list, returning the
89936          * statement list.
89937          *
89938          * @param statements A statement list to which the down-level export statements are to be
89939          * appended. If `statements` is `undefined`, a new array is allocated if statements are
89940          * appended.
89941          * @param decl The declaration whose exports are to be recorded.
89942          */
89943         function appendExportsOfImportDeclaration(statements, decl) {
89944             if (currentModuleInfo.exportEquals) {
89945                 return statements;
89946             }
89947             var importClause = decl.importClause;
89948             if (!importClause) {
89949                 return statements;
89950             }
89951             if (importClause.name) {
89952                 statements = appendExportsOfDeclaration(statements, importClause);
89953             }
89954             var namedBindings = importClause.namedBindings;
89955             if (namedBindings) {
89956                 switch (namedBindings.kind) {
89957                     case 256 /* NamespaceImport */:
89958                         statements = appendExportsOfDeclaration(statements, namedBindings);
89959                         break;
89960                     case 257 /* NamedImports */:
89961                         for (var _i = 0, _a = namedBindings.elements; _i < _a.length; _i++) {
89962                             var importBinding = _a[_i];
89963                             statements = appendExportsOfDeclaration(statements, importBinding, /* liveBinding */ true);
89964                         }
89965                         break;
89966                 }
89967             }
89968             return statements;
89969         }
89970         /**
89971          * Appends the exports of an ImportEqualsDeclaration to a statement list, returning the
89972          * statement list.
89973          *
89974          * @param statements A statement list to which the down-level export statements are to be
89975          * appended. If `statements` is `undefined`, a new array is allocated if statements are
89976          * appended.
89977          * @param decl The declaration whose exports are to be recorded.
89978          */
89979         function appendExportsOfImportEqualsDeclaration(statements, decl) {
89980             if (currentModuleInfo.exportEquals) {
89981                 return statements;
89982             }
89983             return appendExportsOfDeclaration(statements, decl);
89984         }
89985         /**
89986          * Appends the exports of a VariableStatement to a statement list, returning the statement
89987          * list.
89988          *
89989          * @param statements A statement list to which the down-level export statements are to be
89990          * appended. If `statements` is `undefined`, a new array is allocated if statements are
89991          * appended.
89992          * @param node The VariableStatement whose exports are to be recorded.
89993          */
89994         function appendExportsOfVariableStatement(statements, node) {
89995             if (currentModuleInfo.exportEquals) {
89996                 return statements;
89997             }
89998             for (var _i = 0, _a = node.declarationList.declarations; _i < _a.length; _i++) {
89999                 var decl = _a[_i];
90000                 statements = appendExportsOfBindingElement(statements, decl);
90001             }
90002             return statements;
90003         }
90004         /**
90005          * Appends the exports of a VariableDeclaration or BindingElement to a statement list,
90006          * returning the statement list.
90007          *
90008          * @param statements A statement list to which the down-level export statements are to be
90009          * appended. If `statements` is `undefined`, a new array is allocated if statements are
90010          * appended.
90011          * @param decl The declaration whose exports are to be recorded.
90012          */
90013         function appendExportsOfBindingElement(statements, decl) {
90014             if (currentModuleInfo.exportEquals) {
90015                 return statements;
90016             }
90017             if (ts.isBindingPattern(decl.name)) {
90018                 for (var _i = 0, _a = decl.name.elements; _i < _a.length; _i++) {
90019                     var element = _a[_i];
90020                     if (!ts.isOmittedExpression(element)) {
90021                         statements = appendExportsOfBindingElement(statements, element);
90022                     }
90023                 }
90024             }
90025             else if (!ts.isGeneratedIdentifier(decl.name)) {
90026                 statements = appendExportsOfDeclaration(statements, decl);
90027             }
90028             return statements;
90029         }
90030         /**
90031          * Appends the exports of a ClassDeclaration or FunctionDeclaration to a statement list,
90032          * returning the statement list.
90033          *
90034          * @param statements A statement list to which the down-level export statements are to be
90035          * appended. If `statements` is `undefined`, a new array is allocated if statements are
90036          * appended.
90037          * @param decl The declaration whose exports are to be recorded.
90038          */
90039         function appendExportsOfHoistedDeclaration(statements, decl) {
90040             if (currentModuleInfo.exportEquals) {
90041                 return statements;
90042             }
90043             if (ts.hasModifier(decl, 1 /* Export */)) {
90044                 var exportName = ts.hasModifier(decl, 512 /* Default */) ? ts.createIdentifier("default") : ts.getDeclarationName(decl);
90045                 statements = appendExportStatement(statements, exportName, ts.getLocalName(decl), /*location*/ decl);
90046             }
90047             if (decl.name) {
90048                 statements = appendExportsOfDeclaration(statements, decl);
90049             }
90050             return statements;
90051         }
90052         /**
90053          * Appends the exports of a declaration to a statement list, returning the statement list.
90054          *
90055          * @param statements A statement list to which the down-level export statements are to be
90056          * appended. If `statements` is `undefined`, a new array is allocated if statements are
90057          * appended.
90058          * @param decl The declaration to export.
90059          */
90060         function appendExportsOfDeclaration(statements, decl, liveBinding) {
90061             var name = ts.getDeclarationName(decl);
90062             var exportSpecifiers = currentModuleInfo.exportSpecifiers.get(ts.idText(name));
90063             if (exportSpecifiers) {
90064                 for (var _i = 0, exportSpecifiers_1 = exportSpecifiers; _i < exportSpecifiers_1.length; _i++) {
90065                     var exportSpecifier = exportSpecifiers_1[_i];
90066                     statements = appendExportStatement(statements, exportSpecifier.name, name, /*location*/ exportSpecifier.name, /* allowComments */ undefined, liveBinding);
90067                 }
90068             }
90069             return statements;
90070         }
90071         /**
90072          * Appends the down-level representation of an export to a statement list, returning the
90073          * statement list.
90074          *
90075          * @param statements A statement list to which the down-level export statements are to be
90076          * appended. If `statements` is `undefined`, a new array is allocated if statements are
90077          * appended.
90078          * @param exportName The name of the export.
90079          * @param expression The expression to export.
90080          * @param location The location to use for source maps and comments for the export.
90081          * @param allowComments Whether to allow comments on the export.
90082          */
90083         function appendExportStatement(statements, exportName, expression, location, allowComments, liveBinding) {
90084             statements = ts.append(statements, createExportStatement(exportName, expression, location, allowComments, liveBinding));
90085             return statements;
90086         }
90087         function createUnderscoreUnderscoreESModule() {
90088             var statement;
90089             if (languageVersion === 0 /* ES3 */) {
90090                 statement = ts.createExpressionStatement(createExportExpression(ts.createIdentifier("__esModule"), ts.createLiteral(/*value*/ true)));
90091             }
90092             else {
90093                 statement = ts.createExpressionStatement(ts.createCall(ts.createPropertyAccess(ts.createIdentifier("Object"), "defineProperty"), 
90094                 /*typeArguments*/ undefined, [
90095                     ts.createIdentifier("exports"),
90096                     ts.createLiteral("__esModule"),
90097                     ts.createObjectLiteral([
90098                         ts.createPropertyAssignment("value", ts.createLiteral(/*value*/ true))
90099                     ])
90100                 ]));
90101             }
90102             ts.setEmitFlags(statement, 1048576 /* CustomPrologue */);
90103             return statement;
90104         }
90105         /**
90106          * Creates a call to the current file's export function to export a value.
90107          *
90108          * @param name The bound name of the export.
90109          * @param value The exported value.
90110          * @param location The location to use for source maps and comments for the export.
90111          * @param allowComments An optional value indicating whether to emit comments for the statement.
90112          */
90113         function createExportStatement(name, value, location, allowComments, liveBinding) {
90114             var statement = ts.setTextRange(ts.createExpressionStatement(createExportExpression(name, value, /* location */ undefined, liveBinding)), location);
90115             ts.startOnNewLine(statement);
90116             if (!allowComments) {
90117                 ts.setEmitFlags(statement, 1536 /* NoComments */);
90118             }
90119             return statement;
90120         }
90121         /**
90122          * Creates a call to the current file's export function to export a value.
90123          *
90124          * @param name The bound name of the export.
90125          * @param value The exported value.
90126          * @param location The location to use for source maps and comments for the export.
90127          */
90128         function createExportExpression(name, value, location, liveBinding) {
90129             return ts.setTextRange(liveBinding && languageVersion !== 0 /* ES3 */ ? ts.createCall(ts.createPropertyAccess(ts.createIdentifier("Object"), "defineProperty"), 
90130             /*typeArguments*/ undefined, [
90131                 ts.createIdentifier("exports"),
90132                 ts.createLiteral(name),
90133                 ts.createObjectLiteral([
90134                     ts.createPropertyAssignment("enumerable", ts.createLiteral(/*value*/ true)),
90135                     ts.createPropertyAssignment("get", ts.createFunctionExpression(
90136                     /*modifiers*/ undefined, 
90137                     /*asteriskToken*/ undefined, 
90138                     /*name*/ undefined, 
90139                     /*typeParameters*/ undefined, 
90140                     /*parameters*/ [], 
90141                     /*type*/ undefined, ts.createBlock([ts.createReturn(value)])))
90142                 ])
90143             ]) : ts.createAssignment(ts.createPropertyAccess(ts.createIdentifier("exports"), ts.getSynthesizedClone(name)), value), location);
90144         }
90145         //
90146         // Modifier Visitors
90147         //
90148         /**
90149          * Visit nodes to elide module-specific modifiers.
90150          *
90151          * @param node The node to visit.
90152          */
90153         function modifierVisitor(node) {
90154             // Elide module-specific modifiers.
90155             switch (node.kind) {
90156                 case 89 /* ExportKeyword */:
90157                 case 84 /* DefaultKeyword */:
90158                     return undefined;
90159             }
90160             return node;
90161         }
90162         //
90163         // Emit Notification
90164         //
90165         /**
90166          * Hook for node emit notifications.
90167          *
90168          * @param hint A hint as to the intended usage of the node.
90169          * @param node The node to emit.
90170          * @param emit A callback used to emit the node in the printer.
90171          */
90172         function onEmitNode(hint, node, emitCallback) {
90173             if (node.kind === 290 /* SourceFile */) {
90174                 currentSourceFile = node;
90175                 currentModuleInfo = moduleInfoMap[ts.getOriginalNodeId(currentSourceFile)];
90176                 noSubstitution = [];
90177                 previousOnEmitNode(hint, node, emitCallback);
90178                 currentSourceFile = undefined;
90179                 currentModuleInfo = undefined;
90180                 noSubstitution = undefined;
90181             }
90182             else {
90183                 previousOnEmitNode(hint, node, emitCallback);
90184             }
90185         }
90186         //
90187         // Substitutions
90188         //
90189         /**
90190          * Hooks node substitutions.
90191          *
90192          * @param hint A hint as to the intended usage of the node.
90193          * @param node The node to substitute.
90194          */
90195         function onSubstituteNode(hint, node) {
90196             node = previousOnSubstituteNode(hint, node);
90197             if (node.id && noSubstitution[node.id]) {
90198                 return node;
90199             }
90200             if (hint === 1 /* Expression */) {
90201                 return substituteExpression(node);
90202             }
90203             else if (ts.isShorthandPropertyAssignment(node)) {
90204                 return substituteShorthandPropertyAssignment(node);
90205             }
90206             return node;
90207         }
90208         /**
90209          * Substitution for a ShorthandPropertyAssignment whose declaration name is an imported
90210          * or exported symbol.
90211          *
90212          * @param node The node to substitute.
90213          */
90214         function substituteShorthandPropertyAssignment(node) {
90215             var name = node.name;
90216             var exportedOrImportedName = substituteExpressionIdentifier(name);
90217             if (exportedOrImportedName !== name) {
90218                 // A shorthand property with an assignment initializer is probably part of a
90219                 // destructuring assignment
90220                 if (node.objectAssignmentInitializer) {
90221                     var initializer = ts.createAssignment(exportedOrImportedName, node.objectAssignmentInitializer);
90222                     return ts.setTextRange(ts.createPropertyAssignment(name, initializer), node);
90223                 }
90224                 return ts.setTextRange(ts.createPropertyAssignment(name, exportedOrImportedName), node);
90225             }
90226             return node;
90227         }
90228         /**
90229          * Substitution for an Expression that may contain an imported or exported symbol.
90230          *
90231          * @param node The node to substitute.
90232          */
90233         function substituteExpression(node) {
90234             switch (node.kind) {
90235                 case 75 /* Identifier */:
90236                     return substituteExpressionIdentifier(node);
90237                 case 209 /* BinaryExpression */:
90238                     return substituteBinaryExpression(node);
90239                 case 208 /* PostfixUnaryExpression */:
90240                 case 207 /* PrefixUnaryExpression */:
90241                     return substituteUnaryExpression(node);
90242             }
90243             return node;
90244         }
90245         /**
90246          * Substitution for an Identifier expression that may contain an imported or exported
90247          * symbol.
90248          *
90249          * @param node The node to substitute.
90250          */
90251         function substituteExpressionIdentifier(node) {
90252             if (ts.getEmitFlags(node) & 4096 /* HelperName */) {
90253                 var externalHelpersModuleName = ts.getExternalHelpersModuleName(currentSourceFile);
90254                 if (externalHelpersModuleName) {
90255                     return ts.createPropertyAccess(externalHelpersModuleName, node);
90256                 }
90257                 return node;
90258             }
90259             if (!ts.isGeneratedIdentifier(node) && !ts.isLocalName(node)) {
90260                 var exportContainer = resolver.getReferencedExportContainer(node, ts.isExportName(node));
90261                 if (exportContainer && exportContainer.kind === 290 /* SourceFile */) {
90262                     return ts.setTextRange(ts.createPropertyAccess(ts.createIdentifier("exports"), ts.getSynthesizedClone(node)), 
90263                     /*location*/ node);
90264                 }
90265                 var importDeclaration = resolver.getReferencedImportDeclaration(node);
90266                 if (importDeclaration) {
90267                     if (ts.isImportClause(importDeclaration)) {
90268                         return ts.setTextRange(ts.createPropertyAccess(ts.getGeneratedNameForNode(importDeclaration.parent), ts.createIdentifier("default")), 
90269                         /*location*/ node);
90270                     }
90271                     else if (ts.isImportSpecifier(importDeclaration)) {
90272                         var name = importDeclaration.propertyName || importDeclaration.name;
90273                         return ts.setTextRange(ts.createPropertyAccess(ts.getGeneratedNameForNode(importDeclaration.parent.parent.parent), ts.getSynthesizedClone(name)), 
90274                         /*location*/ node);
90275                     }
90276                 }
90277             }
90278             return node;
90279         }
90280         /**
90281          * Substitution for a BinaryExpression that may contain an imported or exported symbol.
90282          *
90283          * @param node The node to substitute.
90284          */
90285         function substituteBinaryExpression(node) {
90286             // When we see an assignment expression whose left-hand side is an exported symbol,
90287             // we should ensure all exports of that symbol are updated with the correct value.
90288             //
90289             // - We do not substitute generated identifiers for any reason.
90290             // - We do not substitute identifiers tagged with the LocalName flag.
90291             // - We do not substitute identifiers that were originally the name of an enum or
90292             //   namespace due to how they are transformed in TypeScript.
90293             // - We only substitute identifiers that are exported at the top level.
90294             if (ts.isAssignmentOperator(node.operatorToken.kind)
90295                 && ts.isIdentifier(node.left)
90296                 && !ts.isGeneratedIdentifier(node.left)
90297                 && !ts.isLocalName(node.left)
90298                 && !ts.isDeclarationNameOfEnumOrNamespace(node.left)) {
90299                 var exportedNames = getExports(node.left);
90300                 if (exportedNames) {
90301                     // For each additional export of the declaration, apply an export assignment.
90302                     var expression = node;
90303                     for (var _i = 0, exportedNames_2 = exportedNames; _i < exportedNames_2.length; _i++) {
90304                         var exportName = exportedNames_2[_i];
90305                         // Mark the node to prevent triggering this rule again.
90306                         noSubstitution[ts.getNodeId(expression)] = true;
90307                         expression = createExportExpression(exportName, expression, /*location*/ node);
90308                     }
90309                     return expression;
90310                 }
90311             }
90312             return node;
90313         }
90314         /**
90315          * Substitution for a UnaryExpression that may contain an imported or exported symbol.
90316          *
90317          * @param node The node to substitute.
90318          */
90319         function substituteUnaryExpression(node) {
90320             // When we see a prefix or postfix increment expression whose operand is an exported
90321             // symbol, we should ensure all exports of that symbol are updated with the correct
90322             // value.
90323             //
90324             // - We do not substitute generated identifiers for any reason.
90325             // - We do not substitute identifiers tagged with the LocalName flag.
90326             // - We do not substitute identifiers that were originally the name of an enum or
90327             //   namespace due to how they are transformed in TypeScript.
90328             // - We only substitute identifiers that are exported at the top level.
90329             if ((node.operator === 45 /* PlusPlusToken */ || node.operator === 46 /* MinusMinusToken */)
90330                 && ts.isIdentifier(node.operand)
90331                 && !ts.isGeneratedIdentifier(node.operand)
90332                 && !ts.isLocalName(node.operand)
90333                 && !ts.isDeclarationNameOfEnumOrNamespace(node.operand)) {
90334                 var exportedNames = getExports(node.operand);
90335                 if (exportedNames) {
90336                     var expression = node.kind === 208 /* PostfixUnaryExpression */
90337                         ? ts.setTextRange(ts.createBinary(node.operand, ts.createToken(node.operator === 45 /* PlusPlusToken */ ? 63 /* PlusEqualsToken */ : 64 /* MinusEqualsToken */), ts.createLiteral(1)), 
90338                         /*location*/ node)
90339                         : node;
90340                     for (var _i = 0, exportedNames_3 = exportedNames; _i < exportedNames_3.length; _i++) {
90341                         var exportName = exportedNames_3[_i];
90342                         // Mark the node to prevent triggering this rule again.
90343                         noSubstitution[ts.getNodeId(expression)] = true;
90344                         expression = createExportExpression(exportName, expression);
90345                     }
90346                     return expression;
90347                 }
90348             }
90349             return node;
90350         }
90351         /**
90352          * Gets the additional exports of a name.
90353          *
90354          * @param name The name.
90355          */
90356         function getExports(name) {
90357             if (!ts.isGeneratedIdentifier(name)) {
90358                 var valueDeclaration = resolver.getReferencedImportDeclaration(name)
90359                     || resolver.getReferencedValueDeclaration(name);
90360                 if (valueDeclaration) {
90361                     return currentModuleInfo
90362                         && currentModuleInfo.exportedBindings[ts.getOriginalNodeId(valueDeclaration)];
90363                 }
90364             }
90365         }
90366     }
90367     ts.transformModule = transformModule;
90368     ts.createBindingHelper = {
90369         name: "typescript:commonjscreatebinding",
90370         importName: "__createBinding",
90371         scoped: false,
90372         priority: 1,
90373         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}));"
90374     };
90375     function createCreateBindingHelper(context, module, inputName, outputName) {
90376         context.requestEmitHelper(ts.createBindingHelper);
90377         return ts.createCall(ts.getUnscopedHelperName("__createBinding"), /*typeArguments*/ undefined, __spreadArrays([ts.createIdentifier("exports"), module, inputName], (outputName ? [outputName] : [])));
90378     }
90379     ts.setModuleDefaultHelper = {
90380         name: "typescript:commonjscreatevalue",
90381         importName: "__setModuleDefault",
90382         scoped: false,
90383         priority: 1,
90384         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});"
90385     };
90386     // emit output for the __export helper function
90387     var exportStarHelper = {
90388         name: "typescript:export-star",
90389         importName: "__exportStar",
90390         scoped: false,
90391         dependencies: [ts.createBindingHelper],
90392         priority: 2,
90393         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            };"
90394     };
90395     function createExportStarHelper(context, module) {
90396         context.requestEmitHelper(exportStarHelper);
90397         return ts.createCall(ts.getUnscopedHelperName("__exportStar"), /*typeArguments*/ undefined, [module, ts.createIdentifier("exports")]);
90398     }
90399     // emit helper for dynamic import
90400     var dynamicImportUMDHelper = {
90401         name: "typescript:dynamicimport-sync-require",
90402         scoped: true,
90403         text: "\n            var __syncRequire = typeof module === \"object\" && typeof module.exports === \"object\";"
90404     };
90405     // emit helper for `import * as Name from "foo"`
90406     ts.importStarHelper = {
90407         name: "typescript:commonjsimportstar",
90408         importName: "__importStar",
90409         scoped: false,
90410         dependencies: [ts.createBindingHelper, ts.setModuleDefaultHelper],
90411         priority: 2,
90412         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};"
90413     };
90414     // emit helper for `import Name from "foo"`
90415     ts.importDefaultHelper = {
90416         name: "typescript:commonjsimportdefault",
90417         importName: "__importDefault",
90418         scoped: false,
90419         text: "\nvar __importDefault = (this && this.__importDefault) || function (mod) {\n    return (mod && mod.__esModule) ? mod : { \"default\": mod };\n};"
90420     };
90421 })(ts || (ts = {}));
90422 /*@internal*/
90423 var ts;
90424 (function (ts) {
90425     function transformSystemModule(context) {
90426         var startLexicalEnvironment = context.startLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistVariableDeclaration = context.hoistVariableDeclaration;
90427         var compilerOptions = context.getCompilerOptions();
90428         var resolver = context.getEmitResolver();
90429         var host = context.getEmitHost();
90430         var previousOnSubstituteNode = context.onSubstituteNode;
90431         var previousOnEmitNode = context.onEmitNode;
90432         context.onSubstituteNode = onSubstituteNode;
90433         context.onEmitNode = onEmitNode;
90434         context.enableSubstitution(75 /* Identifier */); // Substitutes expression identifiers for imported symbols.
90435         context.enableSubstitution(282 /* ShorthandPropertyAssignment */); // Substitutes expression identifiers for imported symbols
90436         context.enableSubstitution(209 /* BinaryExpression */); // Substitutes assignments to exported symbols.
90437         context.enableSubstitution(207 /* PrefixUnaryExpression */); // Substitutes updates to exported symbols.
90438         context.enableSubstitution(208 /* PostfixUnaryExpression */); // Substitutes updates to exported symbols.
90439         context.enableSubstitution(219 /* MetaProperty */); // Substitutes 'import.meta'
90440         context.enableEmitNotification(290 /* SourceFile */); // Restore state when substituting nodes in a file.
90441         var moduleInfoMap = []; // The ExternalModuleInfo for each file.
90442         var deferredExports = []; // Exports to defer until an EndOfDeclarationMarker is found.
90443         var exportFunctionsMap = []; // The export function associated with a source file.
90444         var noSubstitutionMap = []; // Set of nodes for which substitution rules should be ignored for each file.
90445         var contextObjectMap = []; // The context object associated with a source file.
90446         var currentSourceFile; // The current file.
90447         var moduleInfo; // ExternalModuleInfo for the current file.
90448         var exportFunction; // The export function for the current file.
90449         var contextObject; // The context object for the current file.
90450         var hoistedStatements;
90451         var enclosingBlockScopedContainer;
90452         var noSubstitution; // Set of nodes for which substitution rules should be ignored.
90453         return ts.chainBundle(transformSourceFile);
90454         /**
90455          * Transforms the module aspects of a SourceFile.
90456          *
90457          * @param node The SourceFile node.
90458          */
90459         function transformSourceFile(node) {
90460             if (node.isDeclarationFile || !(ts.isEffectiveExternalModule(node, compilerOptions) || node.transformFlags & 2097152 /* ContainsDynamicImport */)) {
90461                 return node;
90462             }
90463             var id = ts.getOriginalNodeId(node);
90464             currentSourceFile = node;
90465             enclosingBlockScopedContainer = node;
90466             // System modules have the following shape:
90467             //
90468             //     System.register(['dep-1', ... 'dep-n'], function(exports) {/* module body function */})
90469             //
90470             // The parameter 'exports' here is a callback '<T>(name: string, value: T) => T' that
90471             // is used to publish exported values. 'exports' returns its 'value' argument so in
90472             // most cases expressions that mutate exported values can be rewritten as:
90473             //
90474             //     expr -> exports('name', expr)
90475             //
90476             // The only exception in this rule is postfix unary operators,
90477             // see comment to 'substitutePostfixUnaryExpression' for more details
90478             // Collect information about the external module and dependency groups.
90479             moduleInfo = moduleInfoMap[id] = ts.collectExternalModuleInfo(node, resolver, compilerOptions);
90480             // Make sure that the name of the 'exports' function does not conflict with
90481             // existing identifiers.
90482             exportFunction = ts.createUniqueName("exports");
90483             exportFunctionsMap[id] = exportFunction;
90484             contextObject = contextObjectMap[id] = ts.createUniqueName("context");
90485             // Add the body of the module.
90486             var dependencyGroups = collectDependencyGroups(moduleInfo.externalImports);
90487             var moduleBodyBlock = createSystemModuleBody(node, dependencyGroups);
90488             var moduleBodyFunction = ts.createFunctionExpression(
90489             /*modifiers*/ undefined, 
90490             /*asteriskToken*/ undefined, 
90491             /*name*/ undefined, 
90492             /*typeParameters*/ undefined, [
90493                 ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, exportFunction),
90494                 ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, contextObject)
90495             ], 
90496             /*type*/ undefined, moduleBodyBlock);
90497             // Write the call to `System.register`
90498             // Clear the emit-helpers flag for later passes since we'll have already used it in the module body
90499             // So the helper will be emit at the correct position instead of at the top of the source-file
90500             var moduleName = ts.tryGetModuleNameFromFile(node, host, compilerOptions);
90501             var dependencies = ts.createArrayLiteral(ts.map(dependencyGroups, function (dependencyGroup) { return dependencyGroup.name; }));
90502             var updated = ts.setEmitFlags(ts.updateSourceFileNode(node, ts.setTextRange(ts.createNodeArray([
90503                 ts.createExpressionStatement(ts.createCall(ts.createPropertyAccess(ts.createIdentifier("System"), "register"), 
90504                 /*typeArguments*/ undefined, moduleName
90505                     ? [moduleName, dependencies, moduleBodyFunction]
90506                     : [dependencies, moduleBodyFunction]))
90507             ]), node.statements)), 1024 /* NoTrailingComments */);
90508             if (!(compilerOptions.outFile || compilerOptions.out)) {
90509                 ts.moveEmitHelpers(updated, moduleBodyBlock, function (helper) { return !helper.scoped; });
90510             }
90511             if (noSubstitution) {
90512                 noSubstitutionMap[id] = noSubstitution;
90513                 noSubstitution = undefined;
90514             }
90515             currentSourceFile = undefined;
90516             moduleInfo = undefined;
90517             exportFunction = undefined;
90518             contextObject = undefined;
90519             hoistedStatements = undefined;
90520             enclosingBlockScopedContainer = undefined;
90521             return ts.aggregateTransformFlags(updated);
90522         }
90523         /**
90524          * Collects the dependency groups for this files imports.
90525          *
90526          * @param externalImports The imports for the file.
90527          */
90528         function collectDependencyGroups(externalImports) {
90529             var groupIndices = ts.createMap();
90530             var dependencyGroups = [];
90531             for (var _i = 0, externalImports_1 = externalImports; _i < externalImports_1.length; _i++) {
90532                 var externalImport = externalImports_1[_i];
90533                 var externalModuleName = ts.getExternalModuleNameLiteral(externalImport, currentSourceFile, host, resolver, compilerOptions);
90534                 if (externalModuleName) {
90535                     var text = externalModuleName.text;
90536                     var groupIndex = groupIndices.get(text);
90537                     if (groupIndex !== undefined) {
90538                         // deduplicate/group entries in dependency list by the dependency name
90539                         dependencyGroups[groupIndex].externalImports.push(externalImport);
90540                     }
90541                     else {
90542                         groupIndices.set(text, dependencyGroups.length);
90543                         dependencyGroups.push({
90544                             name: externalModuleName,
90545                             externalImports: [externalImport]
90546                         });
90547                     }
90548                 }
90549             }
90550             return dependencyGroups;
90551         }
90552         /**
90553          * Adds the statements for the module body function for the source file.
90554          *
90555          * @param node The source file for the module.
90556          * @param dependencyGroups The grouped dependencies of the module.
90557          */
90558         function createSystemModuleBody(node, dependencyGroups) {
90559             // Shape of the body in system modules:
90560             //
90561             //  function (exports) {
90562             //      <list of local aliases for imports>
90563             //      <hoisted variable declarations>
90564             //      <hoisted function declarations>
90565             //      return {
90566             //          setters: [
90567             //              <list of setter function for imports>
90568             //          ],
90569             //          execute: function() {
90570             //              <module statements>
90571             //          }
90572             //      }
90573             //      <temp declarations>
90574             //  }
90575             //
90576             // i.e:
90577             //
90578             //   import {x} from 'file1'
90579             //   var y = 1;
90580             //   export function foo() { return y + x(); }
90581             //   console.log(y);
90582             //
90583             // Will be transformed to:
90584             //
90585             //  function(exports) {
90586             //      function foo() { return y + file_1.x(); }
90587             //      exports("foo", foo);
90588             //      var file_1, y;
90589             //      return {
90590             //          setters: [
90591             //              function(v) { file_1 = v }
90592             //          ],
90593             //          execute(): function() {
90594             //              y = 1;
90595             //              console.log(y);
90596             //          }
90597             //      };
90598             //  }
90599             var statements = [];
90600             // We start a new lexical environment in this function body, but *not* in the
90601             // body of the execute function. This allows us to emit temporary declarations
90602             // only in the outer module body and not in the inner one.
90603             startLexicalEnvironment();
90604             // Add any prologue directives.
90605             var ensureUseStrict = ts.getStrictOptionValue(compilerOptions, "alwaysStrict") || (!compilerOptions.noImplicitUseStrict && ts.isExternalModule(currentSourceFile));
90606             var statementOffset = ts.addPrologue(statements, node.statements, ensureUseStrict, sourceElementVisitor);
90607             // var __moduleName = context_1 && context_1.id;
90608             statements.push(ts.createVariableStatement(
90609             /*modifiers*/ undefined, ts.createVariableDeclarationList([
90610                 ts.createVariableDeclaration("__moduleName", 
90611                 /*type*/ undefined, ts.createLogicalAnd(contextObject, ts.createPropertyAccess(contextObject, "id")))
90612             ])));
90613             // Visit the synthetic external helpers import declaration if present
90614             ts.visitNode(moduleInfo.externalHelpersImportDeclaration, sourceElementVisitor, ts.isStatement);
90615             // Visit the statements of the source file, emitting any transformations into
90616             // the `executeStatements` array. We do this *before* we fill the `setters` array
90617             // as we both emit transformations as well as aggregate some data used when creating
90618             // setters. This allows us to reduce the number of times we need to loop through the
90619             // statements of the source file.
90620             var executeStatements = ts.visitNodes(node.statements, sourceElementVisitor, ts.isStatement, statementOffset);
90621             // Emit early exports for function declarations.
90622             ts.addRange(statements, hoistedStatements);
90623             // We emit hoisted variables early to align roughly with our previous emit output.
90624             // Two key differences in this approach are:
90625             // - Temporary variables will appear at the top rather than at the bottom of the file
90626             ts.insertStatementsAfterStandardPrologue(statements, endLexicalEnvironment());
90627             var exportStarFunction = addExportStarIfNeeded(statements); // TODO: GH#18217
90628             var modifiers = node.transformFlags & 524288 /* ContainsAwait */ ?
90629                 ts.createModifiersFromModifierFlags(256 /* Async */) :
90630                 undefined;
90631             var moduleObject = ts.createObjectLiteral([
90632                 ts.createPropertyAssignment("setters", createSettersArray(exportStarFunction, dependencyGroups)),
90633                 ts.createPropertyAssignment("execute", ts.createFunctionExpression(modifiers, 
90634                 /*asteriskToken*/ undefined, 
90635                 /*name*/ undefined, 
90636                 /*typeParameters*/ undefined, 
90637                 /*parameters*/ [], 
90638                 /*type*/ undefined, ts.createBlock(executeStatements, /*multiLine*/ true)))
90639             ]);
90640             moduleObject.multiLine = true;
90641             statements.push(ts.createReturn(moduleObject));
90642             return ts.createBlock(statements, /*multiLine*/ true);
90643         }
90644         /**
90645          * Adds an exportStar function to a statement list if it is needed for the file.
90646          *
90647          * @param statements A statement list.
90648          */
90649         function addExportStarIfNeeded(statements) {
90650             if (!moduleInfo.hasExportStarsToExportValues) {
90651                 return;
90652             }
90653             // when resolving exports local exported entries/indirect exported entries in the module
90654             // should always win over entries with similar names that were added via star exports
90655             // to support this we store names of local/indirect exported entries in a set.
90656             // this set is used to filter names brought by star expors.
90657             // local names set should only be added if we have anything exported
90658             if (!moduleInfo.exportedNames && moduleInfo.exportSpecifiers.size === 0) {
90659                 // no exported declarations (export var ...) or export specifiers (export {x})
90660                 // check if we have any non star export declarations.
90661                 var hasExportDeclarationWithExportClause = false;
90662                 for (var _i = 0, _a = moduleInfo.externalImports; _i < _a.length; _i++) {
90663                     var externalImport = _a[_i];
90664                     if (externalImport.kind === 260 /* ExportDeclaration */ && externalImport.exportClause) {
90665                         hasExportDeclarationWithExportClause = true;
90666                         break;
90667                     }
90668                 }
90669                 if (!hasExportDeclarationWithExportClause) {
90670                     // we still need to emit exportStar helper
90671                     var exportStarFunction_1 = createExportStarFunction(/*localNames*/ undefined);
90672                     statements.push(exportStarFunction_1);
90673                     return exportStarFunction_1.name;
90674                 }
90675             }
90676             var exportedNames = [];
90677             if (moduleInfo.exportedNames) {
90678                 for (var _b = 0, _c = moduleInfo.exportedNames; _b < _c.length; _b++) {
90679                     var exportedLocalName = _c[_b];
90680                     if (exportedLocalName.escapedText === "default") {
90681                         continue;
90682                     }
90683                     // write name of exported declaration, i.e 'export var x...'
90684                     exportedNames.push(ts.createPropertyAssignment(ts.createLiteral(exportedLocalName), ts.createTrue()));
90685                 }
90686             }
90687             for (var _d = 0, _e = moduleInfo.externalImports; _d < _e.length; _d++) {
90688                 var externalImport = _e[_d];
90689                 if (externalImport.kind !== 260 /* ExportDeclaration */) {
90690                     continue;
90691                 }
90692                 if (!externalImport.exportClause) {
90693                     // export * from ...
90694                     continue;
90695                 }
90696                 if (ts.isNamedExports(externalImport.exportClause)) {
90697                     for (var _f = 0, _g = externalImport.exportClause.elements; _f < _g.length; _f++) {
90698                         var element = _g[_f];
90699                         // write name of indirectly exported entry, i.e. 'export {x} from ...'
90700                         exportedNames.push(ts.createPropertyAssignment(ts.createLiteral(ts.idText(element.name || element.propertyName)), ts.createTrue()));
90701                     }
90702                 }
90703                 else {
90704                     exportedNames.push(ts.createPropertyAssignment(ts.createLiteral(ts.idText(externalImport.exportClause.name)), ts.createTrue()));
90705                 }
90706             }
90707             var exportedNamesStorageRef = ts.createUniqueName("exportedNames");
90708             statements.push(ts.createVariableStatement(
90709             /*modifiers*/ undefined, ts.createVariableDeclarationList([
90710                 ts.createVariableDeclaration(exportedNamesStorageRef, 
90711                 /*type*/ undefined, ts.createObjectLiteral(exportedNames, /*multiline*/ true))
90712             ])));
90713             var exportStarFunction = createExportStarFunction(exportedNamesStorageRef);
90714             statements.push(exportStarFunction);
90715             return exportStarFunction.name;
90716         }
90717         /**
90718          * Creates an exportStar function for the file, with an optional set of excluded local
90719          * names.
90720          *
90721          * @param localNames An optional reference to an object containing a set of excluded local
90722          * names.
90723          */
90724         function createExportStarFunction(localNames) {
90725             var exportStarFunction = ts.createUniqueName("exportStar");
90726             var m = ts.createIdentifier("m");
90727             var n = ts.createIdentifier("n");
90728             var exports = ts.createIdentifier("exports");
90729             var condition = ts.createStrictInequality(n, ts.createLiteral("default"));
90730             if (localNames) {
90731                 condition = ts.createLogicalAnd(condition, ts.createLogicalNot(ts.createCall(ts.createPropertyAccess(localNames, "hasOwnProperty"), 
90732                 /*typeArguments*/ undefined, [n])));
90733             }
90734             return ts.createFunctionDeclaration(
90735             /*decorators*/ undefined, 
90736             /*modifiers*/ undefined, 
90737             /*asteriskToken*/ undefined, exportStarFunction, 
90738             /*typeParameters*/ undefined, [ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, m)], 
90739             /*type*/ undefined, ts.createBlock([
90740                 ts.createVariableStatement(
90741                 /*modifiers*/ undefined, ts.createVariableDeclarationList([
90742                     ts.createVariableDeclaration(exports, 
90743                     /*type*/ undefined, ts.createObjectLiteral([]))
90744                 ])),
90745                 ts.createForIn(ts.createVariableDeclarationList([
90746                     ts.createVariableDeclaration(n, /*type*/ undefined)
90747                 ]), m, ts.createBlock([
90748                     ts.setEmitFlags(ts.createIf(condition, ts.createExpressionStatement(ts.createAssignment(ts.createElementAccess(exports, n), ts.createElementAccess(m, n)))), 1 /* SingleLine */)
90749                 ])),
90750                 ts.createExpressionStatement(ts.createCall(exportFunction, 
90751                 /*typeArguments*/ undefined, [exports]))
90752             ], /*multiline*/ true));
90753         }
90754         /**
90755          * Creates an array setter callbacks for each dependency group.
90756          *
90757          * @param exportStarFunction A reference to an exportStarFunction for the file.
90758          * @param dependencyGroups An array of grouped dependencies.
90759          */
90760         function createSettersArray(exportStarFunction, dependencyGroups) {
90761             var setters = [];
90762             for (var _i = 0, dependencyGroups_1 = dependencyGroups; _i < dependencyGroups_1.length; _i++) {
90763                 var group_2 = dependencyGroups_1[_i];
90764                 // derive a unique name for parameter from the first named entry in the group
90765                 var localName = ts.forEach(group_2.externalImports, function (i) { return ts.getLocalNameForExternalImport(i, currentSourceFile); });
90766                 var parameterName = localName ? ts.getGeneratedNameForNode(localName) : ts.createUniqueName("");
90767                 var statements = [];
90768                 for (var _a = 0, _b = group_2.externalImports; _a < _b.length; _a++) {
90769                     var entry = _b[_a];
90770                     var importVariableName = ts.getLocalNameForExternalImport(entry, currentSourceFile); // TODO: GH#18217
90771                     switch (entry.kind) {
90772                         case 254 /* ImportDeclaration */:
90773                             if (!entry.importClause) {
90774                                 // 'import "..."' case
90775                                 // module is imported only for side-effects, no emit required
90776                                 break;
90777                             }
90778                         // falls through
90779                         case 253 /* ImportEqualsDeclaration */:
90780                             ts.Debug.assert(importVariableName !== undefined);
90781                             // save import into the local
90782                             statements.push(ts.createExpressionStatement(ts.createAssignment(importVariableName, parameterName)));
90783                             break;
90784                         case 260 /* ExportDeclaration */:
90785                             ts.Debug.assert(importVariableName !== undefined);
90786                             if (entry.exportClause) {
90787                                 if (ts.isNamedExports(entry.exportClause)) {
90788                                     //  export {a, b as c} from 'foo'
90789                                     //
90790                                     // emit as:
90791                                     //
90792                                     //  exports_({
90793                                     //     "a": _["a"],
90794                                     //     "c": _["b"]
90795                                     //  });
90796                                     var properties = [];
90797                                     for (var _c = 0, _d = entry.exportClause.elements; _c < _d.length; _c++) {
90798                                         var e = _d[_c];
90799                                         properties.push(ts.createPropertyAssignment(ts.createLiteral(ts.idText(e.name)), ts.createElementAccess(parameterName, ts.createLiteral(ts.idText(e.propertyName || e.name)))));
90800                                     }
90801                                     statements.push(ts.createExpressionStatement(ts.createCall(exportFunction, 
90802                                     /*typeArguments*/ undefined, [ts.createObjectLiteral(properties, /*multiline*/ true)])));
90803                                 }
90804                                 else {
90805                                     statements.push(ts.createExpressionStatement(ts.createCall(exportFunction, 
90806                                     /*typeArguments*/ undefined, [
90807                                         ts.createLiteral(ts.idText(entry.exportClause.name)),
90808                                         parameterName
90809                                     ])));
90810                                 }
90811                             }
90812                             else {
90813                                 //  export * from 'foo'
90814                                 //
90815                                 // emit as:
90816                                 //
90817                                 //  exportStar(foo_1_1);
90818                                 statements.push(ts.createExpressionStatement(ts.createCall(exportStarFunction, 
90819                                 /*typeArguments*/ undefined, [parameterName])));
90820                             }
90821                             break;
90822                     }
90823                 }
90824                 setters.push(ts.createFunctionExpression(
90825                 /*modifiers*/ undefined, 
90826                 /*asteriskToken*/ undefined, 
90827                 /*name*/ undefined, 
90828                 /*typeParameters*/ undefined, [ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, parameterName)], 
90829                 /*type*/ undefined, ts.createBlock(statements, /*multiLine*/ true)));
90830             }
90831             return ts.createArrayLiteral(setters, /*multiLine*/ true);
90832         }
90833         //
90834         // Top-level Source Element Visitors
90835         //
90836         /**
90837          * Visit source elements at the top-level of a module.
90838          *
90839          * @param node The node to visit.
90840          */
90841         function sourceElementVisitor(node) {
90842             switch (node.kind) {
90843                 case 254 /* ImportDeclaration */:
90844                     return visitImportDeclaration(node);
90845                 case 253 /* ImportEqualsDeclaration */:
90846                     return visitImportEqualsDeclaration(node);
90847                 case 260 /* ExportDeclaration */:
90848                     return visitExportDeclaration(node);
90849                 case 259 /* ExportAssignment */:
90850                     return visitExportAssignment(node);
90851                 default:
90852                     return nestedElementVisitor(node);
90853             }
90854         }
90855         /**
90856          * Visits an ImportDeclaration node.
90857          *
90858          * @param node The node to visit.
90859          */
90860         function visitImportDeclaration(node) {
90861             var statements;
90862             if (node.importClause) {
90863                 hoistVariableDeclaration(ts.getLocalNameForExternalImport(node, currentSourceFile)); // TODO: GH#18217
90864             }
90865             if (hasAssociatedEndOfDeclarationMarker(node)) {
90866                 // Defer exports until we encounter an EndOfDeclarationMarker node
90867                 var id = ts.getOriginalNodeId(node);
90868                 deferredExports[id] = appendExportsOfImportDeclaration(deferredExports[id], node);
90869             }
90870             else {
90871                 statements = appendExportsOfImportDeclaration(statements, node);
90872             }
90873             return ts.singleOrMany(statements);
90874         }
90875         function visitExportDeclaration(node) {
90876             ts.Debug.assertIsDefined(node);
90877             return undefined;
90878         }
90879         /**
90880          * Visits an ImportEqualsDeclaration node.
90881          *
90882          * @param node The node to visit.
90883          */
90884         function visitImportEqualsDeclaration(node) {
90885             ts.Debug.assert(ts.isExternalModuleImportEqualsDeclaration(node), "import= for internal module references should be handled in an earlier transformer.");
90886             var statements;
90887             hoistVariableDeclaration(ts.getLocalNameForExternalImport(node, currentSourceFile)); // TODO: GH#18217
90888             if (hasAssociatedEndOfDeclarationMarker(node)) {
90889                 // Defer exports until we encounter an EndOfDeclarationMarker node
90890                 var id = ts.getOriginalNodeId(node);
90891                 deferredExports[id] = appendExportsOfImportEqualsDeclaration(deferredExports[id], node);
90892             }
90893             else {
90894                 statements = appendExportsOfImportEqualsDeclaration(statements, node);
90895             }
90896             return ts.singleOrMany(statements);
90897         }
90898         /**
90899          * Visits an ExportAssignment node.
90900          *
90901          * @param node The node to visit.
90902          */
90903         function visitExportAssignment(node) {
90904             if (node.isExportEquals) {
90905                 // Elide `export=` as it is illegal in a SystemJS module.
90906                 return undefined;
90907             }
90908             var expression = ts.visitNode(node.expression, destructuringAndImportCallVisitor, ts.isExpression);
90909             var original = node.original;
90910             if (original && hasAssociatedEndOfDeclarationMarker(original)) {
90911                 // Defer exports until we encounter an EndOfDeclarationMarker node
90912                 var id = ts.getOriginalNodeId(node);
90913                 deferredExports[id] = appendExportStatement(deferredExports[id], ts.createIdentifier("default"), expression, /*allowComments*/ true);
90914             }
90915             else {
90916                 return createExportStatement(ts.createIdentifier("default"), expression, /*allowComments*/ true);
90917             }
90918         }
90919         /**
90920          * Visits a FunctionDeclaration, hoisting it to the outer module body function.
90921          *
90922          * @param node The node to visit.
90923          */
90924         function visitFunctionDeclaration(node) {
90925             if (ts.hasModifier(node, 1 /* Export */)) {
90926                 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), 
90927                 /*typeParameters*/ undefined, ts.visitNodes(node.parameters, destructuringAndImportCallVisitor, ts.isParameterDeclaration), 
90928                 /*type*/ undefined, ts.visitNode(node.body, destructuringAndImportCallVisitor, ts.isBlock)));
90929             }
90930             else {
90931                 hoistedStatements = ts.append(hoistedStatements, ts.visitEachChild(node, destructuringAndImportCallVisitor, context));
90932             }
90933             if (hasAssociatedEndOfDeclarationMarker(node)) {
90934                 // Defer exports until we encounter an EndOfDeclarationMarker node
90935                 var id = ts.getOriginalNodeId(node);
90936                 deferredExports[id] = appendExportsOfHoistedDeclaration(deferredExports[id], node);
90937             }
90938             else {
90939                 hoistedStatements = appendExportsOfHoistedDeclaration(hoistedStatements, node);
90940             }
90941             return undefined;
90942         }
90943         /**
90944          * Visits a ClassDeclaration, hoisting its name to the outer module body function.
90945          *
90946          * @param node The node to visit.
90947          */
90948         function visitClassDeclaration(node) {
90949             var statements;
90950             // Hoist the name of the class declaration to the outer module body function.
90951             var name = ts.getLocalName(node);
90952             hoistVariableDeclaration(name);
90953             // Rewrite the class declaration into an assignment of a class expression.
90954             statements = ts.append(statements, ts.setTextRange(ts.createExpressionStatement(ts.createAssignment(name, ts.setTextRange(ts.createClassExpression(
90955             /*modifiers*/ undefined, node.name, 
90956             /*typeParameters*/ undefined, ts.visitNodes(node.heritageClauses, destructuringAndImportCallVisitor, ts.isHeritageClause), ts.visitNodes(node.members, destructuringAndImportCallVisitor, ts.isClassElement)), node))), node));
90957             if (hasAssociatedEndOfDeclarationMarker(node)) {
90958                 // Defer exports until we encounter an EndOfDeclarationMarker node
90959                 var id = ts.getOriginalNodeId(node);
90960                 deferredExports[id] = appendExportsOfHoistedDeclaration(deferredExports[id], node);
90961             }
90962             else {
90963                 statements = appendExportsOfHoistedDeclaration(statements, node);
90964             }
90965             return ts.singleOrMany(statements);
90966         }
90967         /**
90968          * Visits a variable statement, hoisting declared names to the top-level module body.
90969          * Each declaration is rewritten into an assignment expression.
90970          *
90971          * @param node The node to visit.
90972          */
90973         function visitVariableStatement(node) {
90974             if (!shouldHoistVariableDeclarationList(node.declarationList)) {
90975                 return ts.visitNode(node, destructuringAndImportCallVisitor, ts.isStatement);
90976             }
90977             var expressions;
90978             var isExportedDeclaration = ts.hasModifier(node, 1 /* Export */);
90979             var isMarkedDeclaration = hasAssociatedEndOfDeclarationMarker(node);
90980             for (var _i = 0, _a = node.declarationList.declarations; _i < _a.length; _i++) {
90981                 var variable = _a[_i];
90982                 if (variable.initializer) {
90983                     expressions = ts.append(expressions, transformInitializedVariable(variable, isExportedDeclaration && !isMarkedDeclaration));
90984                 }
90985                 else {
90986                     hoistBindingElement(variable);
90987                 }
90988             }
90989             var statements;
90990             if (expressions) {
90991                 statements = ts.append(statements, ts.setTextRange(ts.createExpressionStatement(ts.inlineExpressions(expressions)), node));
90992             }
90993             if (isMarkedDeclaration) {
90994                 // Defer exports until we encounter an EndOfDeclarationMarker node
90995                 var id = ts.getOriginalNodeId(node);
90996                 deferredExports[id] = appendExportsOfVariableStatement(deferredExports[id], node, isExportedDeclaration);
90997             }
90998             else {
90999                 statements = appendExportsOfVariableStatement(statements, node, /*exportSelf*/ false);
91000             }
91001             return ts.singleOrMany(statements);
91002         }
91003         /**
91004          * Hoists the declared names of a VariableDeclaration or BindingElement.
91005          *
91006          * @param node The declaration to hoist.
91007          */
91008         function hoistBindingElement(node) {
91009             if (ts.isBindingPattern(node.name)) {
91010                 for (var _i = 0, _a = node.name.elements; _i < _a.length; _i++) {
91011                     var element = _a[_i];
91012                     if (!ts.isOmittedExpression(element)) {
91013                         hoistBindingElement(element);
91014                     }
91015                 }
91016             }
91017             else {
91018                 hoistVariableDeclaration(ts.getSynthesizedClone(node.name));
91019             }
91020         }
91021         /**
91022          * Determines whether a VariableDeclarationList should be hoisted.
91023          *
91024          * @param node The node to test.
91025          */
91026         function shouldHoistVariableDeclarationList(node) {
91027             // hoist only non-block scoped declarations or block scoped declarations parented by source file
91028             return (ts.getEmitFlags(node) & 2097152 /* NoHoisting */) === 0
91029                 && (enclosingBlockScopedContainer.kind === 290 /* SourceFile */
91030                     || (ts.getOriginalNode(node).flags & 3 /* BlockScoped */) === 0);
91031         }
91032         /**
91033          * Transform an initialized variable declaration into an expression.
91034          *
91035          * @param node The node to transform.
91036          * @param isExportedDeclaration A value indicating whether the variable is exported.
91037          */
91038         function transformInitializedVariable(node, isExportedDeclaration) {
91039             var createAssignment = isExportedDeclaration ? createExportedVariableAssignment : createNonExportedVariableAssignment;
91040             return ts.isBindingPattern(node.name)
91041                 ? ts.flattenDestructuringAssignment(node, destructuringAndImportCallVisitor, context, 0 /* All */, 
91042                 /*needsValue*/ false, createAssignment)
91043                 : node.initializer ? createAssignment(node.name, ts.visitNode(node.initializer, destructuringAndImportCallVisitor, ts.isExpression)) : node.name;
91044         }
91045         /**
91046          * Creates an assignment expression for an exported variable declaration.
91047          *
91048          * @param name The name of the variable.
91049          * @param value The value of the variable's initializer.
91050          * @param location The source map location for the assignment.
91051          */
91052         function createExportedVariableAssignment(name, value, location) {
91053             return createVariableAssignment(name, value, location, /*isExportedDeclaration*/ true);
91054         }
91055         /**
91056          * Creates an assignment expression for a non-exported variable declaration.
91057          *
91058          * @param name The name of the variable.
91059          * @param value The value of the variable's initializer.
91060          * @param location The source map location for the assignment.
91061          */
91062         function createNonExportedVariableAssignment(name, value, location) {
91063             return createVariableAssignment(name, value, location, /*isExportedDeclaration*/ false);
91064         }
91065         /**
91066          * Creates an assignment expression for a variable declaration.
91067          *
91068          * @param name The name of the variable.
91069          * @param value The value of the variable's initializer.
91070          * @param location The source map location for the assignment.
91071          * @param isExportedDeclaration A value indicating whether the variable is exported.
91072          */
91073         function createVariableAssignment(name, value, location, isExportedDeclaration) {
91074             hoistVariableDeclaration(ts.getSynthesizedClone(name));
91075             return isExportedDeclaration
91076                 ? createExportExpression(name, preventSubstitution(ts.setTextRange(ts.createAssignment(name, value), location)))
91077                 : preventSubstitution(ts.setTextRange(ts.createAssignment(name, value), location));
91078         }
91079         /**
91080          * Visits a MergeDeclarationMarker used as a placeholder for the beginning of a merged
91081          * and transformed declaration.
91082          *
91083          * @param node The node to visit.
91084          */
91085         function visitMergeDeclarationMarker(node) {
91086             // For an EnumDeclaration or ModuleDeclaration that merges with a preceeding
91087             // declaration we do not emit a leading variable declaration. To preserve the
91088             // begin/end semantics of the declararation and to properly handle exports
91089             // we wrapped the leading variable declaration in a `MergeDeclarationMarker`.
91090             //
91091             // To balance the declaration, we defer the exports of the elided variable
91092             // statement until we visit this declaration's `EndOfDeclarationMarker`.
91093             if (hasAssociatedEndOfDeclarationMarker(node) && node.original.kind === 225 /* VariableStatement */) {
91094                 var id = ts.getOriginalNodeId(node);
91095                 var isExportedDeclaration = ts.hasModifier(node.original, 1 /* Export */);
91096                 deferredExports[id] = appendExportsOfVariableStatement(deferredExports[id], node.original, isExportedDeclaration);
91097             }
91098             return node;
91099         }
91100         /**
91101          * Determines whether a node has an associated EndOfDeclarationMarker.
91102          *
91103          * @param node The node to test.
91104          */
91105         function hasAssociatedEndOfDeclarationMarker(node) {
91106             return (ts.getEmitFlags(node) & 4194304 /* HasEndOfDeclarationMarker */) !== 0;
91107         }
91108         /**
91109          * Visits a DeclarationMarker used as a placeholder for the end of a transformed
91110          * declaration.
91111          *
91112          * @param node The node to visit.
91113          */
91114         function visitEndOfDeclarationMarker(node) {
91115             // For some transformations we emit an `EndOfDeclarationMarker` to mark the actual
91116             // end of the transformed declaration. We use this marker to emit any deferred exports
91117             // of the declaration.
91118             var id = ts.getOriginalNodeId(node);
91119             var statements = deferredExports[id];
91120             if (statements) {
91121                 delete deferredExports[id];
91122                 return ts.append(statements, node);
91123             }
91124             else {
91125                 var original = ts.getOriginalNode(node);
91126                 if (ts.isModuleOrEnumDeclaration(original)) {
91127                     return ts.append(appendExportsOfDeclaration(statements, original), node);
91128                 }
91129             }
91130             return node;
91131         }
91132         /**
91133          * Appends the exports of an ImportDeclaration to a statement list, returning the
91134          * statement list.
91135          *
91136          * @param statements A statement list to which the down-level export statements are to be
91137          * appended. If `statements` is `undefined`, a new array is allocated if statements are
91138          * appended.
91139          * @param decl The declaration whose exports are to be recorded.
91140          */
91141         function appendExportsOfImportDeclaration(statements, decl) {
91142             if (moduleInfo.exportEquals) {
91143                 return statements;
91144             }
91145             var importClause = decl.importClause;
91146             if (!importClause) {
91147                 return statements;
91148             }
91149             if (importClause.name) {
91150                 statements = appendExportsOfDeclaration(statements, importClause);
91151             }
91152             var namedBindings = importClause.namedBindings;
91153             if (namedBindings) {
91154                 switch (namedBindings.kind) {
91155                     case 256 /* NamespaceImport */:
91156                         statements = appendExportsOfDeclaration(statements, namedBindings);
91157                         break;
91158                     case 257 /* NamedImports */:
91159                         for (var _i = 0, _a = namedBindings.elements; _i < _a.length; _i++) {
91160                             var importBinding = _a[_i];
91161                             statements = appendExportsOfDeclaration(statements, importBinding);
91162                         }
91163                         break;
91164                 }
91165             }
91166             return statements;
91167         }
91168         /**
91169          * Appends the export of an ImportEqualsDeclaration to a statement list, returning the
91170          * statement list.
91171          *
91172          * @param statements A statement list to which the down-level export statements are to be
91173          * appended. If `statements` is `undefined`, a new array is allocated if statements are
91174          * appended.
91175          * @param decl The declaration whose exports are to be recorded.
91176          */
91177         function appendExportsOfImportEqualsDeclaration(statements, decl) {
91178             if (moduleInfo.exportEquals) {
91179                 return statements;
91180             }
91181             return appendExportsOfDeclaration(statements, decl);
91182         }
91183         /**
91184          * Appends the exports of a VariableStatement to a statement list, returning the statement
91185          * list.
91186          *
91187          * @param statements A statement list to which the down-level export statements are to be
91188          * appended. If `statements` is `undefined`, a new array is allocated if statements are
91189          * appended.
91190          * @param node The VariableStatement whose exports are to be recorded.
91191          * @param exportSelf A value indicating whether to also export each VariableDeclaration of
91192          * `nodes` declaration list.
91193          */
91194         function appendExportsOfVariableStatement(statements, node, exportSelf) {
91195             if (moduleInfo.exportEquals) {
91196                 return statements;
91197             }
91198             for (var _i = 0, _a = node.declarationList.declarations; _i < _a.length; _i++) {
91199                 var decl = _a[_i];
91200                 if (decl.initializer || exportSelf) {
91201                     statements = appendExportsOfBindingElement(statements, decl, exportSelf);
91202                 }
91203             }
91204             return statements;
91205         }
91206         /**
91207          * Appends the exports of a VariableDeclaration or BindingElement to a statement list,
91208          * returning the statement list.
91209          *
91210          * @param statements A statement list to which the down-level export statements are to be
91211          * appended. If `statements` is `undefined`, a new array is allocated if statements are
91212          * appended.
91213          * @param decl The declaration whose exports are to be recorded.
91214          * @param exportSelf A value indicating whether to also export the declaration itself.
91215          */
91216         function appendExportsOfBindingElement(statements, decl, exportSelf) {
91217             if (moduleInfo.exportEquals) {
91218                 return statements;
91219             }
91220             if (ts.isBindingPattern(decl.name)) {
91221                 for (var _i = 0, _a = decl.name.elements; _i < _a.length; _i++) {
91222                     var element = _a[_i];
91223                     if (!ts.isOmittedExpression(element)) {
91224                         statements = appendExportsOfBindingElement(statements, element, exportSelf);
91225                     }
91226                 }
91227             }
91228             else if (!ts.isGeneratedIdentifier(decl.name)) {
91229                 var excludeName = void 0;
91230                 if (exportSelf) {
91231                     statements = appendExportStatement(statements, decl.name, ts.getLocalName(decl));
91232                     excludeName = ts.idText(decl.name);
91233                 }
91234                 statements = appendExportsOfDeclaration(statements, decl, excludeName);
91235             }
91236             return statements;
91237         }
91238         /**
91239          * Appends the exports of a ClassDeclaration or FunctionDeclaration to a statement list,
91240          * returning the statement list.
91241          *
91242          * @param statements A statement list to which the down-level export statements are to be
91243          * appended. If `statements` is `undefined`, a new array is allocated if statements are
91244          * appended.
91245          * @param decl The declaration whose exports are to be recorded.
91246          */
91247         function appendExportsOfHoistedDeclaration(statements, decl) {
91248             if (moduleInfo.exportEquals) {
91249                 return statements;
91250             }
91251             var excludeName;
91252             if (ts.hasModifier(decl, 1 /* Export */)) {
91253                 var exportName = ts.hasModifier(decl, 512 /* Default */) ? ts.createLiteral("default") : decl.name;
91254                 statements = appendExportStatement(statements, exportName, ts.getLocalName(decl));
91255                 excludeName = ts.getTextOfIdentifierOrLiteral(exportName);
91256             }
91257             if (decl.name) {
91258                 statements = appendExportsOfDeclaration(statements, decl, excludeName);
91259             }
91260             return statements;
91261         }
91262         /**
91263          * Appends the exports of a declaration to a statement list, returning the statement list.
91264          *
91265          * @param statements A statement list to which the down-level export statements are to be
91266          * appended. If `statements` is `undefined`, a new array is allocated if statements are
91267          * appended.
91268          * @param decl The declaration to export.
91269          * @param excludeName An optional name to exclude from exports.
91270          */
91271         function appendExportsOfDeclaration(statements, decl, excludeName) {
91272             if (moduleInfo.exportEquals) {
91273                 return statements;
91274             }
91275             var name = ts.getDeclarationName(decl);
91276             var exportSpecifiers = moduleInfo.exportSpecifiers.get(ts.idText(name));
91277             if (exportSpecifiers) {
91278                 for (var _i = 0, exportSpecifiers_2 = exportSpecifiers; _i < exportSpecifiers_2.length; _i++) {
91279                     var exportSpecifier = exportSpecifiers_2[_i];
91280                     if (exportSpecifier.name.escapedText !== excludeName) {
91281                         statements = appendExportStatement(statements, exportSpecifier.name, name);
91282                     }
91283                 }
91284             }
91285             return statements;
91286         }
91287         /**
91288          * Appends the down-level representation of an export to a statement list, returning the
91289          * statement list.
91290          *
91291          * @param statements A statement list to which the down-level export statements are to be
91292          * appended. If `statements` is `undefined`, a new array is allocated if statements are
91293          * appended.
91294          * @param exportName The name of the export.
91295          * @param expression The expression to export.
91296          * @param allowComments Whether to allow comments on the export.
91297          */
91298         function appendExportStatement(statements, exportName, expression, allowComments) {
91299             statements = ts.append(statements, createExportStatement(exportName, expression, allowComments));
91300             return statements;
91301         }
91302         /**
91303          * Creates a call to the current file's export function to export a value.
91304          *
91305          * @param name The bound name of the export.
91306          * @param value The exported value.
91307          * @param allowComments An optional value indicating whether to emit comments for the statement.
91308          */
91309         function createExportStatement(name, value, allowComments) {
91310             var statement = ts.createExpressionStatement(createExportExpression(name, value));
91311             ts.startOnNewLine(statement);
91312             if (!allowComments) {
91313                 ts.setEmitFlags(statement, 1536 /* NoComments */);
91314             }
91315             return statement;
91316         }
91317         /**
91318          * Creates a call to the current file's export function to export a value.
91319          *
91320          * @param name The bound name of the export.
91321          * @param value The exported value.
91322          */
91323         function createExportExpression(name, value) {
91324             var exportName = ts.isIdentifier(name) ? ts.createLiteral(name) : name;
91325             ts.setEmitFlags(value, ts.getEmitFlags(value) | 1536 /* NoComments */);
91326             return ts.setCommentRange(ts.createCall(exportFunction, /*typeArguments*/ undefined, [exportName, value]), value);
91327         }
91328         //
91329         // Top-Level or Nested Source Element Visitors
91330         //
91331         /**
91332          * Visit nested elements at the top-level of a module.
91333          *
91334          * @param node The node to visit.
91335          */
91336         function nestedElementVisitor(node) {
91337             switch (node.kind) {
91338                 case 225 /* VariableStatement */:
91339                     return visitVariableStatement(node);
91340                 case 244 /* FunctionDeclaration */:
91341                     return visitFunctionDeclaration(node);
91342                 case 245 /* ClassDeclaration */:
91343                     return visitClassDeclaration(node);
91344                 case 230 /* ForStatement */:
91345                     return visitForStatement(node);
91346                 case 231 /* ForInStatement */:
91347                     return visitForInStatement(node);
91348                 case 232 /* ForOfStatement */:
91349                     return visitForOfStatement(node);
91350                 case 228 /* DoStatement */:
91351                     return visitDoStatement(node);
91352                 case 229 /* WhileStatement */:
91353                     return visitWhileStatement(node);
91354                 case 238 /* LabeledStatement */:
91355                     return visitLabeledStatement(node);
91356                 case 236 /* WithStatement */:
91357                     return visitWithStatement(node);
91358                 case 237 /* SwitchStatement */:
91359                     return visitSwitchStatement(node);
91360                 case 251 /* CaseBlock */:
91361                     return visitCaseBlock(node);
91362                 case 277 /* CaseClause */:
91363                     return visitCaseClause(node);
91364                 case 278 /* DefaultClause */:
91365                     return visitDefaultClause(node);
91366                 case 240 /* TryStatement */:
91367                     return visitTryStatement(node);
91368                 case 280 /* CatchClause */:
91369                     return visitCatchClause(node);
91370                 case 223 /* Block */:
91371                     return visitBlock(node);
91372                 case 328 /* MergeDeclarationMarker */:
91373                     return visitMergeDeclarationMarker(node);
91374                 case 329 /* EndOfDeclarationMarker */:
91375                     return visitEndOfDeclarationMarker(node);
91376                 default:
91377                     return destructuringAndImportCallVisitor(node);
91378             }
91379         }
91380         /**
91381          * Visits the body of a ForStatement to hoist declarations.
91382          *
91383          * @param node The node to visit.
91384          */
91385         function visitForStatement(node) {
91386             var savedEnclosingBlockScopedContainer = enclosingBlockScopedContainer;
91387             enclosingBlockScopedContainer = node;
91388             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));
91389             enclosingBlockScopedContainer = savedEnclosingBlockScopedContainer;
91390             return node;
91391         }
91392         /**
91393          * Visits the body of a ForInStatement to hoist declarations.
91394          *
91395          * @param node The node to visit.
91396          */
91397         function visitForInStatement(node) {
91398             var savedEnclosingBlockScopedContainer = enclosingBlockScopedContainer;
91399             enclosingBlockScopedContainer = node;
91400             node = ts.updateForIn(node, visitForInitializer(node.initializer), ts.visitNode(node.expression, destructuringAndImportCallVisitor, ts.isExpression), ts.visitNode(node.statement, nestedElementVisitor, ts.isStatement, ts.liftToBlock));
91401             enclosingBlockScopedContainer = savedEnclosingBlockScopedContainer;
91402             return node;
91403         }
91404         /**
91405          * Visits the body of a ForOfStatement to hoist declarations.
91406          *
91407          * @param node The node to visit.
91408          */
91409         function visitForOfStatement(node) {
91410             var savedEnclosingBlockScopedContainer = enclosingBlockScopedContainer;
91411             enclosingBlockScopedContainer = node;
91412             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));
91413             enclosingBlockScopedContainer = savedEnclosingBlockScopedContainer;
91414             return node;
91415         }
91416         /**
91417          * Determines whether to hoist the initializer of a ForStatement, ForInStatement, or
91418          * ForOfStatement.
91419          *
91420          * @param node The node to test.
91421          */
91422         function shouldHoistForInitializer(node) {
91423             return ts.isVariableDeclarationList(node)
91424                 && shouldHoistVariableDeclarationList(node);
91425         }
91426         /**
91427          * Visits the initializer of a ForStatement, ForInStatement, or ForOfStatement
91428          *
91429          * @param node The node to visit.
91430          */
91431         function visitForInitializer(node) {
91432             if (shouldHoistForInitializer(node)) {
91433                 var expressions = void 0;
91434                 for (var _i = 0, _a = node.declarations; _i < _a.length; _i++) {
91435                     var variable = _a[_i];
91436                     expressions = ts.append(expressions, transformInitializedVariable(variable, /*isExportedDeclaration*/ false));
91437                     if (!variable.initializer) {
91438                         hoistBindingElement(variable);
91439                     }
91440                 }
91441                 return expressions ? ts.inlineExpressions(expressions) : ts.createOmittedExpression();
91442             }
91443             else {
91444                 return ts.visitEachChild(node, nestedElementVisitor, context);
91445             }
91446         }
91447         /**
91448          * Visits the body of a DoStatement to hoist declarations.
91449          *
91450          * @param node The node to visit.
91451          */
91452         function visitDoStatement(node) {
91453             return ts.updateDo(node, ts.visitNode(node.statement, nestedElementVisitor, ts.isStatement, ts.liftToBlock), ts.visitNode(node.expression, destructuringAndImportCallVisitor, ts.isExpression));
91454         }
91455         /**
91456          * Visits the body of a WhileStatement to hoist declarations.
91457          *
91458          * @param node The node to visit.
91459          */
91460         function visitWhileStatement(node) {
91461             return ts.updateWhile(node, ts.visitNode(node.expression, destructuringAndImportCallVisitor, ts.isExpression), ts.visitNode(node.statement, nestedElementVisitor, ts.isStatement, ts.liftToBlock));
91462         }
91463         /**
91464          * Visits the body of a LabeledStatement to hoist declarations.
91465          *
91466          * @param node The node to visit.
91467          */
91468         function visitLabeledStatement(node) {
91469             return ts.updateLabel(node, node.label, ts.visitNode(node.statement, nestedElementVisitor, ts.isStatement, ts.liftToBlock));
91470         }
91471         /**
91472          * Visits the body of a WithStatement to hoist declarations.
91473          *
91474          * @param node The node to visit.
91475          */
91476         function visitWithStatement(node) {
91477             return ts.updateWith(node, ts.visitNode(node.expression, destructuringAndImportCallVisitor, ts.isExpression), ts.visitNode(node.statement, nestedElementVisitor, ts.isStatement, ts.liftToBlock));
91478         }
91479         /**
91480          * Visits the body of a SwitchStatement to hoist declarations.
91481          *
91482          * @param node The node to visit.
91483          */
91484         function visitSwitchStatement(node) {
91485             return ts.updateSwitch(node, ts.visitNode(node.expression, destructuringAndImportCallVisitor, ts.isExpression), ts.visitNode(node.caseBlock, nestedElementVisitor, ts.isCaseBlock));
91486         }
91487         /**
91488          * Visits the body of a CaseBlock to hoist declarations.
91489          *
91490          * @param node The node to visit.
91491          */
91492         function visitCaseBlock(node) {
91493             var savedEnclosingBlockScopedContainer = enclosingBlockScopedContainer;
91494             enclosingBlockScopedContainer = node;
91495             node = ts.updateCaseBlock(node, ts.visitNodes(node.clauses, nestedElementVisitor, ts.isCaseOrDefaultClause));
91496             enclosingBlockScopedContainer = savedEnclosingBlockScopedContainer;
91497             return node;
91498         }
91499         /**
91500          * Visits the body of a CaseClause to hoist declarations.
91501          *
91502          * @param node The node to visit.
91503          */
91504         function visitCaseClause(node) {
91505             return ts.updateCaseClause(node, ts.visitNode(node.expression, destructuringAndImportCallVisitor, ts.isExpression), ts.visitNodes(node.statements, nestedElementVisitor, ts.isStatement));
91506         }
91507         /**
91508          * Visits the body of a DefaultClause to hoist declarations.
91509          *
91510          * @param node The node to visit.
91511          */
91512         function visitDefaultClause(node) {
91513             return ts.visitEachChild(node, nestedElementVisitor, context);
91514         }
91515         /**
91516          * Visits the body of a TryStatement to hoist declarations.
91517          *
91518          * @param node The node to visit.
91519          */
91520         function visitTryStatement(node) {
91521             return ts.visitEachChild(node, nestedElementVisitor, context);
91522         }
91523         /**
91524          * Visits the body of a CatchClause to hoist declarations.
91525          *
91526          * @param node The node to visit.
91527          */
91528         function visitCatchClause(node) {
91529             var savedEnclosingBlockScopedContainer = enclosingBlockScopedContainer;
91530             enclosingBlockScopedContainer = node;
91531             node = ts.updateCatchClause(node, node.variableDeclaration, ts.visitNode(node.block, nestedElementVisitor, ts.isBlock));
91532             enclosingBlockScopedContainer = savedEnclosingBlockScopedContainer;
91533             return node;
91534         }
91535         /**
91536          * Visits the body of a Block to hoist declarations.
91537          *
91538          * @param node The node to visit.
91539          */
91540         function visitBlock(node) {
91541             var savedEnclosingBlockScopedContainer = enclosingBlockScopedContainer;
91542             enclosingBlockScopedContainer = node;
91543             node = ts.visitEachChild(node, nestedElementVisitor, context);
91544             enclosingBlockScopedContainer = savedEnclosingBlockScopedContainer;
91545             return node;
91546         }
91547         //
91548         // Destructuring Assignment Visitors
91549         //
91550         /**
91551          * Visit nodes to flatten destructuring assignments to exported symbols.
91552          *
91553          * @param node The node to visit.
91554          */
91555         function destructuringAndImportCallVisitor(node) {
91556             if (ts.isDestructuringAssignment(node)) {
91557                 return visitDestructuringAssignment(node);
91558             }
91559             else if (ts.isImportCall(node)) {
91560                 return visitImportCallExpression(node);
91561             }
91562             else if ((node.transformFlags & 1024 /* ContainsDestructuringAssignment */) || (node.transformFlags & 2097152 /* ContainsDynamicImport */)) {
91563                 return ts.visitEachChild(node, destructuringAndImportCallVisitor, context);
91564             }
91565             else {
91566                 return node;
91567             }
91568         }
91569         function visitImportCallExpression(node) {
91570             // import("./blah")
91571             // emit as
91572             // System.register([], function (_export, _context) {
91573             //     return {
91574             //         setters: [],
91575             //         execute: () => {
91576             //             _context.import('./blah');
91577             //         }
91578             //     };
91579             // });
91580             return ts.createCall(ts.createPropertyAccess(contextObject, ts.createIdentifier("import")), 
91581             /*typeArguments*/ undefined, ts.some(node.arguments) ? [ts.visitNode(node.arguments[0], destructuringAndImportCallVisitor)] : []);
91582         }
91583         /**
91584          * Visits a DestructuringAssignment to flatten destructuring to exported symbols.
91585          *
91586          * @param node The node to visit.
91587          */
91588         function visitDestructuringAssignment(node) {
91589             if (hasExportedReferenceInDestructuringTarget(node.left)) {
91590                 return ts.flattenDestructuringAssignment(node, destructuringAndImportCallVisitor, context, 0 /* All */, 
91591                 /*needsValue*/ true);
91592             }
91593             return ts.visitEachChild(node, destructuringAndImportCallVisitor, context);
91594         }
91595         /**
91596          * Determines whether the target of a destructuring assigment refers to an exported symbol.
91597          *
91598          * @param node The destructuring target.
91599          */
91600         function hasExportedReferenceInDestructuringTarget(node) {
91601             if (ts.isAssignmentExpression(node, /*excludeCompoundAssignment*/ true)) {
91602                 return hasExportedReferenceInDestructuringTarget(node.left);
91603             }
91604             else if (ts.isSpreadElement(node)) {
91605                 return hasExportedReferenceInDestructuringTarget(node.expression);
91606             }
91607             else if (ts.isObjectLiteralExpression(node)) {
91608                 return ts.some(node.properties, hasExportedReferenceInDestructuringTarget);
91609             }
91610             else if (ts.isArrayLiteralExpression(node)) {
91611                 return ts.some(node.elements, hasExportedReferenceInDestructuringTarget);
91612             }
91613             else if (ts.isShorthandPropertyAssignment(node)) {
91614                 return hasExportedReferenceInDestructuringTarget(node.name);
91615             }
91616             else if (ts.isPropertyAssignment(node)) {
91617                 return hasExportedReferenceInDestructuringTarget(node.initializer);
91618             }
91619             else if (ts.isIdentifier(node)) {
91620                 var container = resolver.getReferencedExportContainer(node);
91621                 return container !== undefined && container.kind === 290 /* SourceFile */;
91622             }
91623             else {
91624                 return false;
91625             }
91626         }
91627         //
91628         // Modifier Visitors
91629         //
91630         /**
91631          * Visit nodes to elide module-specific modifiers.
91632          *
91633          * @param node The node to visit.
91634          */
91635         function modifierVisitor(node) {
91636             switch (node.kind) {
91637                 case 89 /* ExportKeyword */:
91638                 case 84 /* DefaultKeyword */:
91639                     return undefined;
91640             }
91641             return node;
91642         }
91643         //
91644         // Emit Notification
91645         //
91646         /**
91647          * Hook for node emit notifications.
91648          *
91649          * @param hint A hint as to the intended usage of the node.
91650          * @param node The node to emit.
91651          * @param emitCallback A callback used to emit the node in the printer.
91652          */
91653         function onEmitNode(hint, node, emitCallback) {
91654             if (node.kind === 290 /* SourceFile */) {
91655                 var id = ts.getOriginalNodeId(node);
91656                 currentSourceFile = node;
91657                 moduleInfo = moduleInfoMap[id];
91658                 exportFunction = exportFunctionsMap[id];
91659                 noSubstitution = noSubstitutionMap[id];
91660                 contextObject = contextObjectMap[id];
91661                 if (noSubstitution) {
91662                     delete noSubstitutionMap[id];
91663                 }
91664                 previousOnEmitNode(hint, node, emitCallback);
91665                 currentSourceFile = undefined;
91666                 moduleInfo = undefined;
91667                 exportFunction = undefined;
91668                 contextObject = undefined;
91669                 noSubstitution = undefined;
91670             }
91671             else {
91672                 previousOnEmitNode(hint, node, emitCallback);
91673             }
91674         }
91675         //
91676         // Substitutions
91677         //
91678         /**
91679          * Hooks node substitutions.
91680          *
91681          * @param hint A hint as to the intended usage of the node.
91682          * @param node The node to substitute.
91683          */
91684         function onSubstituteNode(hint, node) {
91685             node = previousOnSubstituteNode(hint, node);
91686             if (isSubstitutionPrevented(node)) {
91687                 return node;
91688             }
91689             if (hint === 1 /* Expression */) {
91690                 return substituteExpression(node);
91691             }
91692             else if (hint === 4 /* Unspecified */) {
91693                 return substituteUnspecified(node);
91694             }
91695             return node;
91696         }
91697         /**
91698          * Substitute the node, if necessary.
91699          *
91700          * @param node The node to substitute.
91701          */
91702         function substituteUnspecified(node) {
91703             switch (node.kind) {
91704                 case 282 /* ShorthandPropertyAssignment */:
91705                     return substituteShorthandPropertyAssignment(node);
91706             }
91707             return node;
91708         }
91709         /**
91710          * Substitution for a ShorthandPropertyAssignment whose name that may contain an imported or exported symbol.
91711          *
91712          * @param node The node to substitute.
91713          */
91714         function substituteShorthandPropertyAssignment(node) {
91715             var name = node.name;
91716             if (!ts.isGeneratedIdentifier(name) && !ts.isLocalName(name)) {
91717                 var importDeclaration = resolver.getReferencedImportDeclaration(name);
91718                 if (importDeclaration) {
91719                     if (ts.isImportClause(importDeclaration)) {
91720                         return ts.setTextRange(ts.createPropertyAssignment(ts.getSynthesizedClone(name), ts.createPropertyAccess(ts.getGeneratedNameForNode(importDeclaration.parent), ts.createIdentifier("default"))), 
91721                         /*location*/ node);
91722                     }
91723                     else if (ts.isImportSpecifier(importDeclaration)) {
91724                         return ts.setTextRange(ts.createPropertyAssignment(ts.getSynthesizedClone(name), ts.createPropertyAccess(ts.getGeneratedNameForNode(importDeclaration.parent.parent.parent), ts.getSynthesizedClone(importDeclaration.propertyName || importDeclaration.name))), 
91725                         /*location*/ node);
91726                     }
91727                 }
91728             }
91729             return node;
91730         }
91731         /**
91732          * Substitute the expression, if necessary.
91733          *
91734          * @param node The node to substitute.
91735          */
91736         function substituteExpression(node) {
91737             switch (node.kind) {
91738                 case 75 /* Identifier */:
91739                     return substituteExpressionIdentifier(node);
91740                 case 209 /* BinaryExpression */:
91741                     return substituteBinaryExpression(node);
91742                 case 207 /* PrefixUnaryExpression */:
91743                 case 208 /* PostfixUnaryExpression */:
91744                     return substituteUnaryExpression(node);
91745                 case 219 /* MetaProperty */:
91746                     return substituteMetaProperty(node);
91747             }
91748             return node;
91749         }
91750         /**
91751          * Substitution for an Identifier expression that may contain an imported or exported symbol.
91752          *
91753          * @param node The node to substitute.
91754          */
91755         function substituteExpressionIdentifier(node) {
91756             if (ts.getEmitFlags(node) & 4096 /* HelperName */) {
91757                 var externalHelpersModuleName = ts.getExternalHelpersModuleName(currentSourceFile);
91758                 if (externalHelpersModuleName) {
91759                     return ts.createPropertyAccess(externalHelpersModuleName, node);
91760                 }
91761                 return node;
91762             }
91763             // When we see an identifier in an expression position that
91764             // points to an imported symbol, we should substitute a qualified
91765             // reference to the imported symbol if one is needed.
91766             //
91767             // - We do not substitute generated identifiers for any reason.
91768             // - We do not substitute identifiers tagged with the LocalName flag.
91769             if (!ts.isGeneratedIdentifier(node) && !ts.isLocalName(node)) {
91770                 var importDeclaration = resolver.getReferencedImportDeclaration(node);
91771                 if (importDeclaration) {
91772                     if (ts.isImportClause(importDeclaration)) {
91773                         return ts.setTextRange(ts.createPropertyAccess(ts.getGeneratedNameForNode(importDeclaration.parent), ts.createIdentifier("default")), 
91774                         /*location*/ node);
91775                     }
91776                     else if (ts.isImportSpecifier(importDeclaration)) {
91777                         return ts.setTextRange(ts.createPropertyAccess(ts.getGeneratedNameForNode(importDeclaration.parent.parent.parent), ts.getSynthesizedClone(importDeclaration.propertyName || importDeclaration.name)), 
91778                         /*location*/ node);
91779                     }
91780                 }
91781             }
91782             return node;
91783         }
91784         /**
91785          * Substitution for a BinaryExpression that may contain an imported or exported symbol.
91786          *
91787          * @param node The node to substitute.
91788          */
91789         function substituteBinaryExpression(node) {
91790             // When we see an assignment expression whose left-hand side is an exported symbol,
91791             // we should ensure all exports of that symbol are updated with the correct value.
91792             //
91793             // - We do not substitute generated identifiers for any reason.
91794             // - We do not substitute identifiers tagged with the LocalName flag.
91795             // - We do not substitute identifiers that were originally the name of an enum or
91796             //   namespace due to how they are transformed in TypeScript.
91797             // - We only substitute identifiers that are exported at the top level.
91798             if (ts.isAssignmentOperator(node.operatorToken.kind)
91799                 && ts.isIdentifier(node.left)
91800                 && !ts.isGeneratedIdentifier(node.left)
91801                 && !ts.isLocalName(node.left)
91802                 && !ts.isDeclarationNameOfEnumOrNamespace(node.left)) {
91803                 var exportedNames = getExports(node.left);
91804                 if (exportedNames) {
91805                     // For each additional export of the declaration, apply an export assignment.
91806                     var expression = node;
91807                     for (var _i = 0, exportedNames_4 = exportedNames; _i < exportedNames_4.length; _i++) {
91808                         var exportName = exportedNames_4[_i];
91809                         expression = createExportExpression(exportName, preventSubstitution(expression));
91810                     }
91811                     return expression;
91812                 }
91813             }
91814             return node;
91815         }
91816         /**
91817          * Substitution for a UnaryExpression that may contain an imported or exported symbol.
91818          *
91819          * @param node The node to substitute.
91820          */
91821         function substituteUnaryExpression(node) {
91822             // When we see a prefix or postfix increment expression whose operand is an exported
91823             // symbol, we should ensure all exports of that symbol are updated with the correct
91824             // value.
91825             //
91826             // - We do not substitute generated identifiers for any reason.
91827             // - We do not substitute identifiers tagged with the LocalName flag.
91828             // - We do not substitute identifiers that were originally the name of an enum or
91829             //   namespace due to how they are transformed in TypeScript.
91830             // - We only substitute identifiers that are exported at the top level.
91831             if ((node.operator === 45 /* PlusPlusToken */ || node.operator === 46 /* MinusMinusToken */)
91832                 && ts.isIdentifier(node.operand)
91833                 && !ts.isGeneratedIdentifier(node.operand)
91834                 && !ts.isLocalName(node.operand)
91835                 && !ts.isDeclarationNameOfEnumOrNamespace(node.operand)) {
91836                 var exportedNames = getExports(node.operand);
91837                 if (exportedNames) {
91838                     var expression = node.kind === 208 /* PostfixUnaryExpression */
91839                         ? ts.setTextRange(ts.createPrefix(node.operator, node.operand), node)
91840                         : node;
91841                     for (var _i = 0, exportedNames_5 = exportedNames; _i < exportedNames_5.length; _i++) {
91842                         var exportName = exportedNames_5[_i];
91843                         expression = createExportExpression(exportName, preventSubstitution(expression));
91844                     }
91845                     if (node.kind === 208 /* PostfixUnaryExpression */) {
91846                         expression = node.operator === 45 /* PlusPlusToken */
91847                             ? ts.createSubtract(preventSubstitution(expression), ts.createLiteral(1))
91848                             : ts.createAdd(preventSubstitution(expression), ts.createLiteral(1));
91849                     }
91850                     return expression;
91851                 }
91852             }
91853             return node;
91854         }
91855         function substituteMetaProperty(node) {
91856             if (ts.isImportMeta(node)) {
91857                 return ts.createPropertyAccess(contextObject, ts.createIdentifier("meta"));
91858             }
91859             return node;
91860         }
91861         /**
91862          * Gets the exports of a name.
91863          *
91864          * @param name The name.
91865          */
91866         function getExports(name) {
91867             var exportedNames;
91868             if (!ts.isGeneratedIdentifier(name)) {
91869                 var valueDeclaration = resolver.getReferencedImportDeclaration(name)
91870                     || resolver.getReferencedValueDeclaration(name);
91871                 if (valueDeclaration) {
91872                     var exportContainer = resolver.getReferencedExportContainer(name, /*prefixLocals*/ false);
91873                     if (exportContainer && exportContainer.kind === 290 /* SourceFile */) {
91874                         exportedNames = ts.append(exportedNames, ts.getDeclarationName(valueDeclaration));
91875                     }
91876                     exportedNames = ts.addRange(exportedNames, moduleInfo && moduleInfo.exportedBindings[ts.getOriginalNodeId(valueDeclaration)]);
91877                 }
91878             }
91879             return exportedNames;
91880         }
91881         /**
91882          * Prevent substitution of a node for this transformer.
91883          *
91884          * @param node The node which should not be substituted.
91885          */
91886         function preventSubstitution(node) {
91887             if (noSubstitution === undefined)
91888                 noSubstitution = [];
91889             noSubstitution[ts.getNodeId(node)] = true;
91890             return node;
91891         }
91892         /**
91893          * Determines whether a node should not be substituted.
91894          *
91895          * @param node The node to test.
91896          */
91897         function isSubstitutionPrevented(node) {
91898             return noSubstitution && node.id && noSubstitution[node.id];
91899         }
91900     }
91901     ts.transformSystemModule = transformSystemModule;
91902 })(ts || (ts = {}));
91903 /*@internal*/
91904 var ts;
91905 (function (ts) {
91906     function transformECMAScriptModule(context) {
91907         var compilerOptions = context.getCompilerOptions();
91908         var previousOnEmitNode = context.onEmitNode;
91909         var previousOnSubstituteNode = context.onSubstituteNode;
91910         context.onEmitNode = onEmitNode;
91911         context.onSubstituteNode = onSubstituteNode;
91912         context.enableEmitNotification(290 /* SourceFile */);
91913         context.enableSubstitution(75 /* Identifier */);
91914         var helperNameSubstitutions;
91915         return ts.chainBundle(transformSourceFile);
91916         function transformSourceFile(node) {
91917             if (node.isDeclarationFile) {
91918                 return node;
91919             }
91920             if (ts.isExternalModule(node) || compilerOptions.isolatedModules) {
91921                 var externalHelpersImportDeclaration = ts.createExternalHelpersImportDeclarationIfNeeded(node, compilerOptions);
91922                 if (externalHelpersImportDeclaration) {
91923                     var statements = [];
91924                     var statementOffset = ts.addPrologue(statements, node.statements);
91925                     ts.append(statements, externalHelpersImportDeclaration);
91926                     ts.addRange(statements, ts.visitNodes(node.statements, visitor, ts.isStatement, statementOffset));
91927                     return ts.updateSourceFileNode(node, ts.setTextRange(ts.createNodeArray(statements), node.statements));
91928                 }
91929                 else {
91930                     return ts.visitEachChild(node, visitor, context);
91931                 }
91932             }
91933             return node;
91934         }
91935         function visitor(node) {
91936             switch (node.kind) {
91937                 case 253 /* ImportEqualsDeclaration */:
91938                     // Elide `import=` as it is not legal with --module ES6
91939                     return undefined;
91940                 case 259 /* ExportAssignment */:
91941                     return visitExportAssignment(node);
91942                 case 260 /* ExportDeclaration */:
91943                     var exportDecl = node;
91944                     return visitExportDeclaration(exportDecl);
91945             }
91946             return node;
91947         }
91948         function visitExportAssignment(node) {
91949             // Elide `export=` as it is not legal with --module ES6
91950             return node.isExportEquals ? undefined : node;
91951         }
91952         function visitExportDeclaration(node) {
91953             // `export * as ns` only needs to be transformed in ES2015
91954             if (compilerOptions.module !== undefined && compilerOptions.module > ts.ModuleKind.ES2015) {
91955                 return node;
91956             }
91957             // Either ill-formed or don't need to be tranformed.
91958             if (!node.exportClause || !ts.isNamespaceExport(node.exportClause) || !node.moduleSpecifier) {
91959                 return node;
91960             }
91961             var oldIdentifier = node.exportClause.name;
91962             var synthName = ts.getGeneratedNameForNode(oldIdentifier);
91963             var importDecl = ts.createImportDeclaration(
91964             /*decorators*/ undefined, 
91965             /*modifiers*/ undefined, ts.createImportClause(/*name*/ undefined, ts.createNamespaceImport(synthName)), node.moduleSpecifier);
91966             ts.setOriginalNode(importDecl, node.exportClause);
91967             var exportDecl = ts.createExportDeclaration(
91968             /*decorators*/ undefined, 
91969             /*modifiers*/ undefined, ts.createNamedExports([ts.createExportSpecifier(synthName, oldIdentifier)]));
91970             ts.setOriginalNode(exportDecl, node);
91971             return [importDecl, exportDecl];
91972         }
91973         //
91974         // Emit Notification
91975         //
91976         /**
91977          * Hook for node emit.
91978          *
91979          * @param hint A hint as to the intended usage of the node.
91980          * @param node The node to emit.
91981          * @param emit A callback used to emit the node in the printer.
91982          */
91983         function onEmitNode(hint, node, emitCallback) {
91984             if (ts.isSourceFile(node)) {
91985                 if ((ts.isExternalModule(node) || compilerOptions.isolatedModules) && compilerOptions.importHelpers) {
91986                     helperNameSubstitutions = ts.createMap();
91987                 }
91988                 previousOnEmitNode(hint, node, emitCallback);
91989                 helperNameSubstitutions = undefined;
91990             }
91991             else {
91992                 previousOnEmitNode(hint, node, emitCallback);
91993             }
91994         }
91995         //
91996         // Substitutions
91997         //
91998         /**
91999          * Hooks node substitutions.
92000          *
92001          * @param hint A hint as to the intended usage of the node.
92002          * @param node The node to substitute.
92003          */
92004         function onSubstituteNode(hint, node) {
92005             node = previousOnSubstituteNode(hint, node);
92006             if (helperNameSubstitutions && ts.isIdentifier(node) && ts.getEmitFlags(node) & 4096 /* HelperName */) {
92007                 return substituteHelperName(node);
92008             }
92009             return node;
92010         }
92011         function substituteHelperName(node) {
92012             var name = ts.idText(node);
92013             var substitution = helperNameSubstitutions.get(name);
92014             if (!substitution) {
92015                 helperNameSubstitutions.set(name, substitution = ts.createFileLevelUniqueName(name));
92016             }
92017             return substitution;
92018         }
92019     }
92020     ts.transformECMAScriptModule = transformECMAScriptModule;
92021 })(ts || (ts = {}));
92022 /* @internal */
92023 var ts;
92024 (function (ts) {
92025     function canProduceDiagnostics(node) {
92026         return ts.isVariableDeclaration(node) ||
92027             ts.isPropertyDeclaration(node) ||
92028             ts.isPropertySignature(node) ||
92029             ts.isBindingElement(node) ||
92030             ts.isSetAccessor(node) ||
92031             ts.isGetAccessor(node) ||
92032             ts.isConstructSignatureDeclaration(node) ||
92033             ts.isCallSignatureDeclaration(node) ||
92034             ts.isMethodDeclaration(node) ||
92035             ts.isMethodSignature(node) ||
92036             ts.isFunctionDeclaration(node) ||
92037             ts.isParameter(node) ||
92038             ts.isTypeParameterDeclaration(node) ||
92039             ts.isExpressionWithTypeArguments(node) ||
92040             ts.isImportEqualsDeclaration(node) ||
92041             ts.isTypeAliasDeclaration(node) ||
92042             ts.isConstructorDeclaration(node) ||
92043             ts.isIndexSignatureDeclaration(node) ||
92044             ts.isPropertyAccessExpression(node);
92045     }
92046     ts.canProduceDiagnostics = canProduceDiagnostics;
92047     function createGetSymbolAccessibilityDiagnosticForNodeName(node) {
92048         if (ts.isSetAccessor(node) || ts.isGetAccessor(node)) {
92049             return getAccessorNameVisibilityError;
92050         }
92051         else if (ts.isMethodSignature(node) || ts.isMethodDeclaration(node)) {
92052             return getMethodNameVisibilityError;
92053         }
92054         else {
92055             return createGetSymbolAccessibilityDiagnosticForNode(node);
92056         }
92057         function getAccessorNameVisibilityError(symbolAccessibilityResult) {
92058             var diagnosticMessage = getAccessorNameVisibilityDiagnosticMessage(symbolAccessibilityResult);
92059             return diagnosticMessage !== undefined ? {
92060                 diagnosticMessage: diagnosticMessage,
92061                 errorNode: node,
92062                 typeName: node.name
92063             } : undefined;
92064         }
92065         function getAccessorNameVisibilityDiagnosticMessage(symbolAccessibilityResult) {
92066             if (ts.hasModifier(node, 32 /* Static */)) {
92067                 return symbolAccessibilityResult.errorModuleName ?
92068                     symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ?
92069                         ts.Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named :
92070                         ts.Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2 :
92071                     ts.Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_private_name_1;
92072             }
92073             else if (node.parent.kind === 245 /* ClassDeclaration */) {
92074                 return symbolAccessibilityResult.errorModuleName ?
92075                     symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ?
92076                         ts.Diagnostics.Public_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named :
92077                         ts.Diagnostics.Public_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2 :
92078                     ts.Diagnostics.Public_property_0_of_exported_class_has_or_is_using_private_name_1;
92079             }
92080             else {
92081                 return symbolAccessibilityResult.errorModuleName ?
92082                     ts.Diagnostics.Property_0_of_exported_interface_has_or_is_using_name_1_from_private_module_2 :
92083                     ts.Diagnostics.Property_0_of_exported_interface_has_or_is_using_private_name_1;
92084             }
92085         }
92086         function getMethodNameVisibilityError(symbolAccessibilityResult) {
92087             var diagnosticMessage = getMethodNameVisibilityDiagnosticMessage(symbolAccessibilityResult);
92088             return diagnosticMessage !== undefined ? {
92089                 diagnosticMessage: diagnosticMessage,
92090                 errorNode: node,
92091                 typeName: node.name
92092             } : undefined;
92093         }
92094         function getMethodNameVisibilityDiagnosticMessage(symbolAccessibilityResult) {
92095             if (ts.hasModifier(node, 32 /* Static */)) {
92096                 return symbolAccessibilityResult.errorModuleName ?
92097                     symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ?
92098                         ts.Diagnostics.Public_static_method_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named :
92099                         ts.Diagnostics.Public_static_method_0_of_exported_class_has_or_is_using_name_1_from_private_module_2 :
92100                     ts.Diagnostics.Public_static_method_0_of_exported_class_has_or_is_using_private_name_1;
92101             }
92102             else if (node.parent.kind === 245 /* ClassDeclaration */) {
92103                 return symbolAccessibilityResult.errorModuleName ?
92104                     symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ?
92105                         ts.Diagnostics.Public_method_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named :
92106                         ts.Diagnostics.Public_method_0_of_exported_class_has_or_is_using_name_1_from_private_module_2 :
92107                     ts.Diagnostics.Public_method_0_of_exported_class_has_or_is_using_private_name_1;
92108             }
92109             else {
92110                 return symbolAccessibilityResult.errorModuleName ?
92111                     ts.Diagnostics.Method_0_of_exported_interface_has_or_is_using_name_1_from_private_module_2 :
92112                     ts.Diagnostics.Method_0_of_exported_interface_has_or_is_using_private_name_1;
92113             }
92114         }
92115     }
92116     ts.createGetSymbolAccessibilityDiagnosticForNodeName = createGetSymbolAccessibilityDiagnosticForNodeName;
92117     function createGetSymbolAccessibilityDiagnosticForNode(node) {
92118         if (ts.isVariableDeclaration(node) || ts.isPropertyDeclaration(node) || ts.isPropertySignature(node) || ts.isPropertyAccessExpression(node) || ts.isBindingElement(node) || ts.isConstructorDeclaration(node)) {
92119             return getVariableDeclarationTypeVisibilityError;
92120         }
92121         else if (ts.isSetAccessor(node) || ts.isGetAccessor(node)) {
92122             return getAccessorDeclarationTypeVisibilityError;
92123         }
92124         else if (ts.isConstructSignatureDeclaration(node) || ts.isCallSignatureDeclaration(node) || ts.isMethodDeclaration(node) || ts.isMethodSignature(node) || ts.isFunctionDeclaration(node) || ts.isIndexSignatureDeclaration(node)) {
92125             return getReturnTypeVisibilityError;
92126         }
92127         else if (ts.isParameter(node)) {
92128             if (ts.isParameterPropertyDeclaration(node, node.parent) && ts.hasModifier(node.parent, 8 /* Private */)) {
92129                 return getVariableDeclarationTypeVisibilityError;
92130             }
92131             return getParameterDeclarationTypeVisibilityError;
92132         }
92133         else if (ts.isTypeParameterDeclaration(node)) {
92134             return getTypeParameterConstraintVisibilityError;
92135         }
92136         else if (ts.isExpressionWithTypeArguments(node)) {
92137             return getHeritageClauseVisibilityError;
92138         }
92139         else if (ts.isImportEqualsDeclaration(node)) {
92140             return getImportEntityNameVisibilityError;
92141         }
92142         else if (ts.isTypeAliasDeclaration(node)) {
92143             return getTypeAliasDeclarationVisibilityError;
92144         }
92145         else {
92146             return ts.Debug.assertNever(node, "Attempted to set a declaration diagnostic context for unhandled node kind: " + ts.SyntaxKind[node.kind]);
92147         }
92148         function getVariableDeclarationTypeVisibilityDiagnosticMessage(symbolAccessibilityResult) {
92149             if (node.kind === 242 /* VariableDeclaration */ || node.kind === 191 /* BindingElement */) {
92150                 return symbolAccessibilityResult.errorModuleName ?
92151                     symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ?
92152                         ts.Diagnostics.Exported_variable_0_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named :
92153                         ts.Diagnostics.Exported_variable_0_has_or_is_using_name_1_from_private_module_2 :
92154                     ts.Diagnostics.Exported_variable_0_has_or_is_using_private_name_1;
92155             }
92156             // This check is to ensure we don't report error on constructor parameter property as that error would be reported during parameter emit
92157             // The only exception here is if the constructor was marked as private. we are not emitting the constructor parameters at all.
92158             else if (node.kind === 159 /* PropertyDeclaration */ || node.kind === 194 /* PropertyAccessExpression */ || node.kind === 158 /* PropertySignature */ ||
92159                 (node.kind === 156 /* Parameter */ && ts.hasModifier(node.parent, 8 /* Private */))) {
92160                 // TODO(jfreeman): Deal with computed properties in error reporting.
92161                 if (ts.hasModifier(node, 32 /* Static */)) {
92162                     return symbolAccessibilityResult.errorModuleName ?
92163                         symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ?
92164                             ts.Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named :
92165                             ts.Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2 :
92166                         ts.Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_private_name_1;
92167                 }
92168                 else if (node.parent.kind === 245 /* ClassDeclaration */ || node.kind === 156 /* Parameter */) {
92169                     return symbolAccessibilityResult.errorModuleName ?
92170                         symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ?
92171                             ts.Diagnostics.Public_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named :
92172                             ts.Diagnostics.Public_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2 :
92173                         ts.Diagnostics.Public_property_0_of_exported_class_has_or_is_using_private_name_1;
92174                 }
92175                 else {
92176                     // Interfaces cannot have types that cannot be named
92177                     return symbolAccessibilityResult.errorModuleName ?
92178                         ts.Diagnostics.Property_0_of_exported_interface_has_or_is_using_name_1_from_private_module_2 :
92179                         ts.Diagnostics.Property_0_of_exported_interface_has_or_is_using_private_name_1;
92180                 }
92181             }
92182         }
92183         function getVariableDeclarationTypeVisibilityError(symbolAccessibilityResult) {
92184             var diagnosticMessage = getVariableDeclarationTypeVisibilityDiagnosticMessage(symbolAccessibilityResult);
92185             return diagnosticMessage !== undefined ? {
92186                 diagnosticMessage: diagnosticMessage,
92187                 errorNode: node,
92188                 typeName: node.name
92189             } : undefined;
92190         }
92191         function getAccessorDeclarationTypeVisibilityError(symbolAccessibilityResult) {
92192             var diagnosticMessage;
92193             if (node.kind === 164 /* SetAccessor */) {
92194                 // Getters can infer the return type from the returned expression, but setters cannot, so the
92195                 // "_from_external_module_1_but_cannot_be_named" case cannot occur.
92196                 if (ts.hasModifier(node, 32 /* Static */)) {
92197                     diagnosticMessage = symbolAccessibilityResult.errorModuleName ?
92198                         ts.Diagnostics.Parameter_type_of_public_static_setter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2 :
92199                         ts.Diagnostics.Parameter_type_of_public_static_setter_0_from_exported_class_has_or_is_using_private_name_1;
92200                 }
92201                 else {
92202                     diagnosticMessage = symbolAccessibilityResult.errorModuleName ?
92203                         ts.Diagnostics.Parameter_type_of_public_setter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2 :
92204                         ts.Diagnostics.Parameter_type_of_public_setter_0_from_exported_class_has_or_is_using_private_name_1;
92205                 }
92206             }
92207             else {
92208                 if (ts.hasModifier(node, 32 /* Static */)) {
92209                     diagnosticMessage = symbolAccessibilityResult.errorModuleName ?
92210                         symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ?
92211                             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 :
92212                             ts.Diagnostics.Return_type_of_public_static_getter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2 :
92213                         ts.Diagnostics.Return_type_of_public_static_getter_0_from_exported_class_has_or_is_using_private_name_1;
92214                 }
92215                 else {
92216                     diagnosticMessage = symbolAccessibilityResult.errorModuleName ?
92217                         symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ?
92218                             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 :
92219                             ts.Diagnostics.Return_type_of_public_getter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2 :
92220                         ts.Diagnostics.Return_type_of_public_getter_0_from_exported_class_has_or_is_using_private_name_1;
92221                 }
92222             }
92223             return {
92224                 diagnosticMessage: diagnosticMessage,
92225                 errorNode: node.name,
92226                 typeName: node.name
92227             };
92228         }
92229         function getReturnTypeVisibilityError(symbolAccessibilityResult) {
92230             var diagnosticMessage;
92231             switch (node.kind) {
92232                 case 166 /* ConstructSignature */:
92233                     // Interfaces cannot have return types that cannot be named
92234                     diagnosticMessage = symbolAccessibilityResult.errorModuleName ?
92235                         ts.Diagnostics.Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1 :
92236                         ts.Diagnostics.Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_0;
92237                     break;
92238                 case 165 /* CallSignature */:
92239                     // Interfaces cannot have return types that cannot be named
92240                     diagnosticMessage = symbolAccessibilityResult.errorModuleName ?
92241                         ts.Diagnostics.Return_type_of_call_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1 :
92242                         ts.Diagnostics.Return_type_of_call_signature_from_exported_interface_has_or_is_using_private_name_0;
92243                     break;
92244                 case 167 /* IndexSignature */:
92245                     // Interfaces cannot have return types that cannot be named
92246                     diagnosticMessage = symbolAccessibilityResult.errorModuleName ?
92247                         ts.Diagnostics.Return_type_of_index_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1 :
92248                         ts.Diagnostics.Return_type_of_index_signature_from_exported_interface_has_or_is_using_private_name_0;
92249                     break;
92250                 case 161 /* MethodDeclaration */:
92251                 case 160 /* MethodSignature */:
92252                     if (ts.hasModifier(node, 32 /* Static */)) {
92253                         diagnosticMessage = symbolAccessibilityResult.errorModuleName ?
92254                             symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ?
92255                                 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 :
92256                                 ts.Diagnostics.Return_type_of_public_static_method_from_exported_class_has_or_is_using_name_0_from_private_module_1 :
92257                             ts.Diagnostics.Return_type_of_public_static_method_from_exported_class_has_or_is_using_private_name_0;
92258                     }
92259                     else if (node.parent.kind === 245 /* ClassDeclaration */) {
92260                         diagnosticMessage = symbolAccessibilityResult.errorModuleName ?
92261                             symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ?
92262                                 ts.Diagnostics.Return_type_of_public_method_from_exported_class_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named :
92263                                 ts.Diagnostics.Return_type_of_public_method_from_exported_class_has_or_is_using_name_0_from_private_module_1 :
92264                             ts.Diagnostics.Return_type_of_public_method_from_exported_class_has_or_is_using_private_name_0;
92265                     }
92266                     else {
92267                         // Interfaces cannot have return types that cannot be named
92268                         diagnosticMessage = symbolAccessibilityResult.errorModuleName ?
92269                             ts.Diagnostics.Return_type_of_method_from_exported_interface_has_or_is_using_name_0_from_private_module_1 :
92270                             ts.Diagnostics.Return_type_of_method_from_exported_interface_has_or_is_using_private_name_0;
92271                     }
92272                     break;
92273                 case 244 /* FunctionDeclaration */:
92274                     diagnosticMessage = symbolAccessibilityResult.errorModuleName ?
92275                         symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ?
92276                             ts.Diagnostics.Return_type_of_exported_function_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named :
92277                             ts.Diagnostics.Return_type_of_exported_function_has_or_is_using_name_0_from_private_module_1 :
92278                         ts.Diagnostics.Return_type_of_exported_function_has_or_is_using_private_name_0;
92279                     break;
92280                 default:
92281                     return ts.Debug.fail("This is unknown kind for signature: " + node.kind);
92282             }
92283             return {
92284                 diagnosticMessage: diagnosticMessage,
92285                 errorNode: node.name || node
92286             };
92287         }
92288         function getParameterDeclarationTypeVisibilityError(symbolAccessibilityResult) {
92289             var diagnosticMessage = getParameterDeclarationTypeVisibilityDiagnosticMessage(symbolAccessibilityResult);
92290             return diagnosticMessage !== undefined ? {
92291                 diagnosticMessage: diagnosticMessage,
92292                 errorNode: node,
92293                 typeName: node.name
92294             } : undefined;
92295         }
92296         function getParameterDeclarationTypeVisibilityDiagnosticMessage(symbolAccessibilityResult) {
92297             switch (node.parent.kind) {
92298                 case 162 /* Constructor */:
92299                     return symbolAccessibilityResult.errorModuleName ?
92300                         symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ?
92301                             ts.Diagnostics.Parameter_0_of_constructor_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named :
92302                             ts.Diagnostics.Parameter_0_of_constructor_from_exported_class_has_or_is_using_name_1_from_private_module_2 :
92303                         ts.Diagnostics.Parameter_0_of_constructor_from_exported_class_has_or_is_using_private_name_1;
92304                 case 166 /* ConstructSignature */:
92305                 case 171 /* ConstructorType */:
92306                     // Interfaces cannot have parameter types that cannot be named
92307                     return symbolAccessibilityResult.errorModuleName ?
92308                         ts.Diagnostics.Parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2 :
92309                         ts.Diagnostics.Parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1;
92310                 case 165 /* CallSignature */:
92311                     // Interfaces cannot have parameter types that cannot be named
92312                     return symbolAccessibilityResult.errorModuleName ?
92313                         ts.Diagnostics.Parameter_0_of_call_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2 :
92314                         ts.Diagnostics.Parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1;
92315                 case 167 /* IndexSignature */:
92316                     // Interfaces cannot have parameter types that cannot be named
92317                     return symbolAccessibilityResult.errorModuleName ?
92318                         ts.Diagnostics.Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2 :
92319                         ts.Diagnostics.Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_private_name_1;
92320                 case 161 /* MethodDeclaration */:
92321                 case 160 /* MethodSignature */:
92322                     if (ts.hasModifier(node.parent, 32 /* Static */)) {
92323                         return symbolAccessibilityResult.errorModuleName ?
92324                             symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ?
92325                                 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 :
92326                                 ts.Diagnostics.Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_name_1_from_private_module_2 :
92327                             ts.Diagnostics.Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_name_1;
92328                     }
92329                     else if (node.parent.parent.kind === 245 /* ClassDeclaration */) {
92330                         return symbolAccessibilityResult.errorModuleName ?
92331                             symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ?
92332                                 ts.Diagnostics.Parameter_0_of_public_method_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named :
92333                                 ts.Diagnostics.Parameter_0_of_public_method_from_exported_class_has_or_is_using_name_1_from_private_module_2 :
92334                             ts.Diagnostics.Parameter_0_of_public_method_from_exported_class_has_or_is_using_private_name_1;
92335                     }
92336                     else {
92337                         // Interfaces cannot have parameter types that cannot be named
92338                         return symbolAccessibilityResult.errorModuleName ?
92339                             ts.Diagnostics.Parameter_0_of_method_from_exported_interface_has_or_is_using_name_1_from_private_module_2 :
92340                             ts.Diagnostics.Parameter_0_of_method_from_exported_interface_has_or_is_using_private_name_1;
92341                     }
92342                 case 244 /* FunctionDeclaration */:
92343                 case 170 /* FunctionType */:
92344                     return symbolAccessibilityResult.errorModuleName ?
92345                         symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ?
92346                             ts.Diagnostics.Parameter_0_of_exported_function_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named :
92347                             ts.Diagnostics.Parameter_0_of_exported_function_has_or_is_using_name_1_from_private_module_2 :
92348                         ts.Diagnostics.Parameter_0_of_exported_function_has_or_is_using_private_name_1;
92349                 case 164 /* SetAccessor */:
92350                 case 163 /* GetAccessor */:
92351                     return symbolAccessibilityResult.errorModuleName ?
92352                         symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ?
92353                             ts.Diagnostics.Parameter_0_of_accessor_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named :
92354                             ts.Diagnostics.Parameter_0_of_accessor_has_or_is_using_name_1_from_private_module_2 :
92355                         ts.Diagnostics.Parameter_0_of_accessor_has_or_is_using_private_name_1;
92356                 default:
92357                     return ts.Debug.fail("Unknown parent for parameter: " + ts.SyntaxKind[node.parent.kind]);
92358             }
92359         }
92360         function getTypeParameterConstraintVisibilityError() {
92361             // Type parameter constraints are named by user so we should always be able to name it
92362             var diagnosticMessage;
92363             switch (node.parent.kind) {
92364                 case 245 /* ClassDeclaration */:
92365                     diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_class_has_or_is_using_private_name_1;
92366                     break;
92367                 case 246 /* InterfaceDeclaration */:
92368                     diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1;
92369                     break;
92370                 case 186 /* MappedType */:
92371                     diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_mapped_object_type_is_using_private_name_1;
92372                     break;
92373                 case 171 /* ConstructorType */:
92374                 case 166 /* ConstructSignature */:
92375                     diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1;
92376                     break;
92377                 case 165 /* CallSignature */:
92378                     diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1;
92379                     break;
92380                 case 161 /* MethodDeclaration */:
92381                 case 160 /* MethodSignature */:
92382                     if (ts.hasModifier(node.parent, 32 /* Static */)) {
92383                         diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_name_1;
92384                     }
92385                     else if (node.parent.parent.kind === 245 /* ClassDeclaration */) {
92386                         diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_public_method_from_exported_class_has_or_is_using_private_name_1;
92387                     }
92388                     else {
92389                         diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_method_from_exported_interface_has_or_is_using_private_name_1;
92390                     }
92391                     break;
92392                 case 170 /* FunctionType */:
92393                 case 244 /* FunctionDeclaration */:
92394                     diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_function_has_or_is_using_private_name_1;
92395                     break;
92396                 case 247 /* TypeAliasDeclaration */:
92397                     diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_type_alias_has_or_is_using_private_name_1;
92398                     break;
92399                 default:
92400                     return ts.Debug.fail("This is unknown parent for type parameter: " + node.parent.kind);
92401             }
92402             return {
92403                 diagnosticMessage: diagnosticMessage,
92404                 errorNode: node,
92405                 typeName: node.name
92406             };
92407         }
92408         function getHeritageClauseVisibilityError() {
92409             var diagnosticMessage;
92410             // Heritage clause is written by user so it can always be named
92411             if (node.parent.parent.kind === 245 /* ClassDeclaration */) {
92412                 // Class or Interface implemented/extended is inaccessible
92413                 diagnosticMessage = ts.isHeritageClause(node.parent) && node.parent.token === 113 /* ImplementsKeyword */ ?
92414                     ts.Diagnostics.Implements_clause_of_exported_class_0_has_or_is_using_private_name_1 :
92415                     ts.Diagnostics.extends_clause_of_exported_class_0_has_or_is_using_private_name_1;
92416             }
92417             else {
92418                 // interface is inaccessible
92419                 diagnosticMessage = ts.Diagnostics.extends_clause_of_exported_interface_0_has_or_is_using_private_name_1;
92420             }
92421             return {
92422                 diagnosticMessage: diagnosticMessage,
92423                 errorNode: node,
92424                 typeName: ts.getNameOfDeclaration(node.parent.parent)
92425             };
92426         }
92427         function getImportEntityNameVisibilityError() {
92428             return {
92429                 diagnosticMessage: ts.Diagnostics.Import_declaration_0_is_using_private_name_1,
92430                 errorNode: node,
92431                 typeName: node.name
92432             };
92433         }
92434         function getTypeAliasDeclarationVisibilityError() {
92435             return {
92436                 diagnosticMessage: ts.Diagnostics.Exported_type_alias_0_has_or_is_using_private_name_1,
92437                 errorNode: node.type,
92438                 typeName: node.name
92439             };
92440         }
92441     }
92442     ts.createGetSymbolAccessibilityDiagnosticForNode = createGetSymbolAccessibilityDiagnosticForNode;
92443 })(ts || (ts = {}));
92444 /*@internal*/
92445 var ts;
92446 (function (ts) {
92447     function getDeclarationDiagnostics(host, resolver, file) {
92448         if (file && ts.isJsonSourceFile(file)) {
92449             return []; // No declaration diagnostics for json for now
92450         }
92451         var compilerOptions = host.getCompilerOptions();
92452         var result = ts.transformNodes(resolver, host, compilerOptions, file ? [file] : ts.filter(host.getSourceFiles(), ts.isSourceFileNotJson), [transformDeclarations], /*allowDtsFiles*/ false);
92453         return result.diagnostics;
92454     }
92455     ts.getDeclarationDiagnostics = getDeclarationDiagnostics;
92456     function hasInternalAnnotation(range, currentSourceFile) {
92457         var comment = currentSourceFile.text.substring(range.pos, range.end);
92458         return ts.stringContains(comment, "@internal");
92459     }
92460     function isInternalDeclaration(node, currentSourceFile) {
92461         var parseTreeNode = ts.getParseTreeNode(node);
92462         if (parseTreeNode && parseTreeNode.kind === 156 /* Parameter */) {
92463             var paramIdx = parseTreeNode.parent.parameters.indexOf(parseTreeNode);
92464             var previousSibling = paramIdx > 0 ? parseTreeNode.parent.parameters[paramIdx - 1] : undefined;
92465             var text = currentSourceFile.text;
92466             var commentRanges = previousSibling
92467                 ? ts.concatenate(
92468                 // to handle
92469                 // ... parameters, /* @internal */
92470                 // public param: string
92471                 ts.getTrailingCommentRanges(text, ts.skipTrivia(text, previousSibling.end + 1, /* stopAfterLineBreak */ false, /* stopAtComments */ true)), ts.getLeadingCommentRanges(text, node.pos))
92472                 : ts.getTrailingCommentRanges(text, ts.skipTrivia(text, node.pos, /* stopAfterLineBreak */ false, /* stopAtComments */ true));
92473             return commentRanges && commentRanges.length && hasInternalAnnotation(ts.last(commentRanges), currentSourceFile);
92474         }
92475         var leadingCommentRanges = parseTreeNode && ts.getLeadingCommentRangesOfNode(parseTreeNode, currentSourceFile);
92476         return !!ts.forEach(leadingCommentRanges, function (range) {
92477             return hasInternalAnnotation(range, currentSourceFile);
92478         });
92479     }
92480     ts.isInternalDeclaration = isInternalDeclaration;
92481     var declarationEmitNodeBuilderFlags = 1024 /* MultilineObjectLiterals */ |
92482         2048 /* WriteClassExpressionAsTypeLiteral */ |
92483         4096 /* UseTypeOfFunction */ |
92484         8 /* UseStructuralFallback */ |
92485         524288 /* AllowEmptyTuple */ |
92486         4 /* GenerateNamesForShadowedTypeParams */ |
92487         1 /* NoTruncation */;
92488     /**
92489      * Transforms a ts file into a .d.ts file
92490      * This process requires type information, which is retrieved through the emit resolver. Because of this,
92491      * in many places this transformer assumes it will be operating on parse tree nodes directly.
92492      * This means that _no transforms should be allowed to occur before this one_.
92493      */
92494     function transformDeclarations(context) {
92495         var throwDiagnostic = function () { return ts.Debug.fail("Diagnostic emitted without context"); };
92496         var getSymbolAccessibilityDiagnostic = throwDiagnostic;
92497         var needsDeclare = true;
92498         var isBundledEmit = false;
92499         var resultHasExternalModuleIndicator = false;
92500         var needsScopeFixMarker = false;
92501         var resultHasScopeMarker = false;
92502         var enclosingDeclaration;
92503         var necessaryTypeReferences;
92504         var lateMarkedStatements;
92505         var lateStatementReplacementMap;
92506         var suppressNewDiagnosticContexts;
92507         var exportedModulesFromDeclarationEmit;
92508         var host = context.getEmitHost();
92509         var symbolTracker = {
92510             trackSymbol: trackSymbol,
92511             reportInaccessibleThisError: reportInaccessibleThisError,
92512             reportInaccessibleUniqueSymbolError: reportInaccessibleUniqueSymbolError,
92513             reportCyclicStructureError: reportCyclicStructureError,
92514             reportPrivateInBaseOfClassExpression: reportPrivateInBaseOfClassExpression,
92515             reportLikelyUnsafeImportRequiredError: reportLikelyUnsafeImportRequiredError,
92516             moduleResolverHost: host,
92517             trackReferencedAmbientModule: trackReferencedAmbientModule,
92518             trackExternalModuleSymbolOfImportTypeNode: trackExternalModuleSymbolOfImportTypeNode,
92519             reportNonlocalAugmentation: reportNonlocalAugmentation
92520         };
92521         var errorNameNode;
92522         var currentSourceFile;
92523         var refs;
92524         var libs;
92525         var emittedImports; // must be declared in container so it can be `undefined` while transformer's first pass
92526         var resolver = context.getEmitResolver();
92527         var options = context.getCompilerOptions();
92528         var noResolve = options.noResolve, stripInternal = options.stripInternal;
92529         return transformRoot;
92530         function recordTypeReferenceDirectivesIfNecessary(typeReferenceDirectives) {
92531             if (!typeReferenceDirectives) {
92532                 return;
92533             }
92534             necessaryTypeReferences = necessaryTypeReferences || ts.createMap();
92535             for (var _i = 0, typeReferenceDirectives_2 = typeReferenceDirectives; _i < typeReferenceDirectives_2.length; _i++) {
92536                 var ref = typeReferenceDirectives_2[_i];
92537                 necessaryTypeReferences.set(ref, true);
92538             }
92539         }
92540         function trackReferencedAmbientModule(node, symbol) {
92541             // If it is visible via `// <reference types="..."/>`, then we should just use that
92542             var directives = resolver.getTypeReferenceDirectivesForSymbol(symbol, 67108863 /* All */);
92543             if (ts.length(directives)) {
92544                 return recordTypeReferenceDirectivesIfNecessary(directives);
92545             }
92546             // Otherwise we should emit a path-based reference
92547             var container = ts.getSourceFileOfNode(node);
92548             refs.set("" + ts.getOriginalNodeId(container), container);
92549         }
92550         function handleSymbolAccessibilityError(symbolAccessibilityResult) {
92551             if (symbolAccessibilityResult.accessibility === 0 /* Accessible */) {
92552                 // Add aliases back onto the possible imports list if they're not there so we can try them again with updated visibility info
92553                 if (symbolAccessibilityResult && symbolAccessibilityResult.aliasesToMakeVisible) {
92554                     if (!lateMarkedStatements) {
92555                         lateMarkedStatements = symbolAccessibilityResult.aliasesToMakeVisible;
92556                     }
92557                     else {
92558                         for (var _i = 0, _a = symbolAccessibilityResult.aliasesToMakeVisible; _i < _a.length; _i++) {
92559                             var ref = _a[_i];
92560                             ts.pushIfUnique(lateMarkedStatements, ref);
92561                         }
92562                     }
92563                 }
92564                 // TODO: Do all these accessibility checks inside/after the first pass in the checker when declarations are enabled, if possible
92565             }
92566             else {
92567                 // Report error
92568                 var errorInfo = getSymbolAccessibilityDiagnostic(symbolAccessibilityResult);
92569                 if (errorInfo) {
92570                     if (errorInfo.typeName) {
92571                         context.addDiagnostic(ts.createDiagnosticForNode(symbolAccessibilityResult.errorNode || errorInfo.errorNode, errorInfo.diagnosticMessage, ts.getTextOfNode(errorInfo.typeName), symbolAccessibilityResult.errorSymbolName, symbolAccessibilityResult.errorModuleName));
92572                     }
92573                     else {
92574                         context.addDiagnostic(ts.createDiagnosticForNode(symbolAccessibilityResult.errorNode || errorInfo.errorNode, errorInfo.diagnosticMessage, symbolAccessibilityResult.errorSymbolName, symbolAccessibilityResult.errorModuleName));
92575                     }
92576                 }
92577             }
92578         }
92579         function trackExternalModuleSymbolOfImportTypeNode(symbol) {
92580             if (!isBundledEmit) {
92581                 (exportedModulesFromDeclarationEmit || (exportedModulesFromDeclarationEmit = [])).push(symbol);
92582             }
92583         }
92584         function trackSymbol(symbol, enclosingDeclaration, meaning) {
92585             if (symbol.flags & 262144 /* TypeParameter */)
92586                 return;
92587             handleSymbolAccessibilityError(resolver.isSymbolAccessible(symbol, enclosingDeclaration, meaning, /*shouldComputeAliasesToMakeVisible*/ true));
92588             recordTypeReferenceDirectivesIfNecessary(resolver.getTypeReferenceDirectivesForSymbol(symbol, meaning));
92589         }
92590         function reportPrivateInBaseOfClassExpression(propertyName) {
92591             if (errorNameNode) {
92592                 context.addDiagnostic(ts.createDiagnosticForNode(errorNameNode, ts.Diagnostics.Property_0_of_exported_class_expression_may_not_be_private_or_protected, propertyName));
92593             }
92594         }
92595         function reportInaccessibleUniqueSymbolError() {
92596             if (errorNameNode) {
92597                 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"));
92598             }
92599         }
92600         function reportCyclicStructureError() {
92601             if (errorNameNode) {
92602                 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)));
92603             }
92604         }
92605         function reportInaccessibleThisError() {
92606             if (errorNameNode) {
92607                 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"));
92608             }
92609         }
92610         function reportLikelyUnsafeImportRequiredError(specifier) {
92611             if (errorNameNode) {
92612                 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));
92613             }
92614         }
92615         function reportNonlocalAugmentation(containingFile, parentSymbol, symbol) {
92616             var primaryDeclaration = ts.find(parentSymbol.declarations, function (d) { return ts.getSourceFileOfNode(d) === containingFile; });
92617             var augmentingDeclarations = ts.filter(symbol.declarations, function (d) { return ts.getSourceFileOfNode(d) !== containingFile; });
92618             for (var _i = 0, augmentingDeclarations_1 = augmentingDeclarations; _i < augmentingDeclarations_1.length; _i++) {
92619                 var augmentations = augmentingDeclarations_1[_i];
92620                 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)));
92621             }
92622         }
92623         function transformDeclarationsForJS(sourceFile, bundled) {
92624             var oldDiag = getSymbolAccessibilityDiagnostic;
92625             getSymbolAccessibilityDiagnostic = function (s) { return ({
92626                 diagnosticMessage: s.errorModuleName
92627                     ? ts.Diagnostics.Declaration_emit_for_this_file_requires_using_private_name_0_from_module_1_An_explicit_type_annotation_may_unblock_declaration_emit
92628                     : ts.Diagnostics.Declaration_emit_for_this_file_requires_using_private_name_0_An_explicit_type_annotation_may_unblock_declaration_emit,
92629                 errorNode: s.errorNode || sourceFile
92630             }); };
92631             var result = resolver.getDeclarationStatementsForSourceFile(sourceFile, declarationEmitNodeBuilderFlags, symbolTracker, bundled);
92632             getSymbolAccessibilityDiagnostic = oldDiag;
92633             return result;
92634         }
92635         function transformRoot(node) {
92636             if (node.kind === 290 /* SourceFile */ && node.isDeclarationFile) {
92637                 return node;
92638             }
92639             if (node.kind === 291 /* Bundle */) {
92640                 isBundledEmit = true;
92641                 refs = ts.createMap();
92642                 libs = ts.createMap();
92643                 var hasNoDefaultLib_1 = false;
92644                 var bundle = ts.createBundle(ts.map(node.sourceFiles, function (sourceFile) {
92645                     if (sourceFile.isDeclarationFile)
92646                         return undefined; // Omit declaration files from bundle results, too // TODO: GH#18217
92647                     hasNoDefaultLib_1 = hasNoDefaultLib_1 || sourceFile.hasNoDefaultLib;
92648                     currentSourceFile = sourceFile;
92649                     enclosingDeclaration = sourceFile;
92650                     lateMarkedStatements = undefined;
92651                     suppressNewDiagnosticContexts = false;
92652                     lateStatementReplacementMap = ts.createMap();
92653                     getSymbolAccessibilityDiagnostic = throwDiagnostic;
92654                     needsScopeFixMarker = false;
92655                     resultHasScopeMarker = false;
92656                     collectReferences(sourceFile, refs);
92657                     collectLibs(sourceFile, libs);
92658                     if (ts.isExternalOrCommonJsModule(sourceFile) || ts.isJsonSourceFile(sourceFile)) {
92659                         resultHasExternalModuleIndicator = false; // unused in external module bundle emit (all external modules are within module blocks, therefore are known to be modules)
92660                         needsDeclare = false;
92661                         var statements = ts.isSourceFileJS(sourceFile) ? ts.createNodeArray(transformDeclarationsForJS(sourceFile, /*bundled*/ true)) : ts.visitNodes(sourceFile.statements, visitDeclarationStatements);
92662                         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*/ []);
92663                         return newFile;
92664                     }
92665                     needsDeclare = true;
92666                     var updated = ts.isSourceFileJS(sourceFile) ? ts.createNodeArray(transformDeclarationsForJS(sourceFile)) : ts.visitNodes(sourceFile.statements, visitDeclarationStatements);
92667                     return ts.updateSourceFileNode(sourceFile, transformAndReplaceLatePaintedStatements(updated), /*isDeclarationFile*/ true, /*referencedFiles*/ [], /*typeReferences*/ [], /*hasNoDefaultLib*/ false, /*libReferences*/ []);
92668                 }), ts.mapDefined(node.prepends, function (prepend) {
92669                     if (prepend.kind === 293 /* InputFiles */) {
92670                         var sourceFile = ts.createUnparsedSourceFile(prepend, "dts", stripInternal);
92671                         hasNoDefaultLib_1 = hasNoDefaultLib_1 || !!sourceFile.hasNoDefaultLib;
92672                         collectReferences(sourceFile, refs);
92673                         recordTypeReferenceDirectivesIfNecessary(sourceFile.typeReferenceDirectives);
92674                         collectLibs(sourceFile, libs);
92675                         return sourceFile;
92676                     }
92677                     return prepend;
92678                 }));
92679                 bundle.syntheticFileReferences = [];
92680                 bundle.syntheticTypeReferences = getFileReferencesForUsedTypeReferences();
92681                 bundle.syntheticLibReferences = getLibReferences();
92682                 bundle.hasNoDefaultLib = hasNoDefaultLib_1;
92683                 var outputFilePath_1 = ts.getDirectoryPath(ts.normalizeSlashes(ts.getOutputPathsFor(node, host, /*forceDtsPaths*/ true).declarationFilePath));
92684                 var referenceVisitor_1 = mapReferencesIntoArray(bundle.syntheticFileReferences, outputFilePath_1);
92685                 refs.forEach(referenceVisitor_1);
92686                 return bundle;
92687             }
92688             // Single source file
92689             needsDeclare = true;
92690             needsScopeFixMarker = false;
92691             resultHasScopeMarker = false;
92692             enclosingDeclaration = node;
92693             currentSourceFile = node;
92694             getSymbolAccessibilityDiagnostic = throwDiagnostic;
92695             isBundledEmit = false;
92696             resultHasExternalModuleIndicator = false;
92697             suppressNewDiagnosticContexts = false;
92698             lateMarkedStatements = undefined;
92699             lateStatementReplacementMap = ts.createMap();
92700             necessaryTypeReferences = undefined;
92701             refs = collectReferences(currentSourceFile, ts.createMap());
92702             libs = collectLibs(currentSourceFile, ts.createMap());
92703             var references = [];
92704             var outputFilePath = ts.getDirectoryPath(ts.normalizeSlashes(ts.getOutputPathsFor(node, host, /*forceDtsPaths*/ true).declarationFilePath));
92705             var referenceVisitor = mapReferencesIntoArray(references, outputFilePath);
92706             var combinedStatements;
92707             if (ts.isSourceFileJS(currentSourceFile)) {
92708                 combinedStatements = ts.createNodeArray(transformDeclarationsForJS(node));
92709                 refs.forEach(referenceVisitor);
92710                 emittedImports = ts.filter(combinedStatements, ts.isAnyImportSyntax);
92711             }
92712             else {
92713                 var statements = ts.visitNodes(node.statements, visitDeclarationStatements);
92714                 combinedStatements = ts.setTextRange(ts.createNodeArray(transformAndReplaceLatePaintedStatements(statements)), node.statements);
92715                 refs.forEach(referenceVisitor);
92716                 emittedImports = ts.filter(combinedStatements, ts.isAnyImportSyntax);
92717                 if (ts.isExternalModule(node) && (!resultHasExternalModuleIndicator || (needsScopeFixMarker && !resultHasScopeMarker))) {
92718                     combinedStatements = ts.setTextRange(ts.createNodeArray(__spreadArrays(combinedStatements, [ts.createEmptyExports()])), combinedStatements);
92719                 }
92720             }
92721             var updated = ts.updateSourceFileNode(node, combinedStatements, /*isDeclarationFile*/ true, references, getFileReferencesForUsedTypeReferences(), node.hasNoDefaultLib, getLibReferences());
92722             updated.exportedModulesFromDeclarationEmit = exportedModulesFromDeclarationEmit;
92723             return updated;
92724             function getLibReferences() {
92725                 return ts.map(ts.arrayFrom(libs.keys()), function (lib) { return ({ fileName: lib, pos: -1, end: -1 }); });
92726             }
92727             function getFileReferencesForUsedTypeReferences() {
92728                 return necessaryTypeReferences ? ts.mapDefined(ts.arrayFrom(necessaryTypeReferences.keys()), getFileReferenceForTypeName) : [];
92729             }
92730             function getFileReferenceForTypeName(typeName) {
92731                 // Elide type references for which we have imports
92732                 if (emittedImports) {
92733                     for (var _i = 0, emittedImports_1 = emittedImports; _i < emittedImports_1.length; _i++) {
92734                         var importStatement = emittedImports_1[_i];
92735                         if (ts.isImportEqualsDeclaration(importStatement) && ts.isExternalModuleReference(importStatement.moduleReference)) {
92736                             var expr = importStatement.moduleReference.expression;
92737                             if (ts.isStringLiteralLike(expr) && expr.text === typeName) {
92738                                 return undefined;
92739                             }
92740                         }
92741                         else if (ts.isImportDeclaration(importStatement) && ts.isStringLiteral(importStatement.moduleSpecifier) && importStatement.moduleSpecifier.text === typeName) {
92742                             return undefined;
92743                         }
92744                     }
92745                 }
92746                 return { fileName: typeName, pos: -1, end: -1 };
92747             }
92748             function mapReferencesIntoArray(references, outputFilePath) {
92749                 return function (file) {
92750                     var declFileName;
92751                     if (file.isDeclarationFile) { // Neither decl files or js should have their refs changed
92752                         declFileName = file.fileName;
92753                     }
92754                     else {
92755                         if (isBundledEmit && ts.contains(node.sourceFiles, file))
92756                             return; // Omit references to files which are being merged
92757                         var paths = ts.getOutputPathsFor(file, host, /*forceDtsPaths*/ true);
92758                         declFileName = paths.declarationFilePath || paths.jsFilePath || file.fileName;
92759                     }
92760                     if (declFileName) {
92761                         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, 
92762                         /*preferences*/ undefined);
92763                         if (!ts.pathIsRelative(specifier)) {
92764                             // If some compiler option/symlink/whatever allows access to the file containing the ambient module declaration
92765                             // via a non-relative name, emit a type reference directive to that non-relative name, rather than
92766                             // a relative path to the declaration file
92767                             recordTypeReferenceDirectivesIfNecessary([specifier]);
92768                             return;
92769                         }
92770                         var fileName = ts.getRelativePathToDirectoryOrUrl(outputFilePath, declFileName, host.getCurrentDirectory(), host.getCanonicalFileName, 
92771                         /*isAbsolutePathAnUrl*/ false);
92772                         if (ts.startsWith(fileName, "./") && ts.hasExtension(fileName)) {
92773                             fileName = fileName.substring(2);
92774                         }
92775                         // omit references to files from node_modules (npm may disambiguate module
92776                         // references when installing this package, making the path is unreliable).
92777                         if (ts.startsWith(fileName, "node_modules/") || ts.pathContainsNodeModules(fileName)) {
92778                             return;
92779                         }
92780                         references.push({ pos: -1, end: -1, fileName: fileName });
92781                     }
92782                 };
92783             }
92784         }
92785         function collectReferences(sourceFile, ret) {
92786             if (noResolve || (!ts.isUnparsedSource(sourceFile) && ts.isSourceFileJS(sourceFile)))
92787                 return ret;
92788             ts.forEach(sourceFile.referencedFiles, function (f) {
92789                 var elem = host.getSourceFileFromReference(sourceFile, f);
92790                 if (elem) {
92791                     ret.set("" + ts.getOriginalNodeId(elem), elem);
92792                 }
92793             });
92794             return ret;
92795         }
92796         function collectLibs(sourceFile, ret) {
92797             ts.forEach(sourceFile.libReferenceDirectives, function (ref) {
92798                 var lib = host.getLibFileFromReference(ref);
92799                 if (lib) {
92800                     ret.set(ts.toFileNameLowerCase(ref.fileName), true);
92801                 }
92802             });
92803             return ret;
92804         }
92805         function filterBindingPatternInitializers(name) {
92806             if (name.kind === 75 /* Identifier */) {
92807                 return name;
92808             }
92809             else {
92810                 if (name.kind === 190 /* ArrayBindingPattern */) {
92811                     return ts.updateArrayBindingPattern(name, ts.visitNodes(name.elements, visitBindingElement));
92812                 }
92813                 else {
92814                     return ts.updateObjectBindingPattern(name, ts.visitNodes(name.elements, visitBindingElement));
92815                 }
92816             }
92817             function visitBindingElement(elem) {
92818                 if (elem.kind === 215 /* OmittedExpression */) {
92819                     return elem;
92820                 }
92821                 return ts.updateBindingElement(elem, elem.dotDotDotToken, elem.propertyName, filterBindingPatternInitializers(elem.name), shouldPrintWithInitializer(elem) ? elem.initializer : undefined);
92822             }
92823         }
92824         function ensureParameter(p, modifierMask, type) {
92825             var oldDiag;
92826             if (!suppressNewDiagnosticContexts) {
92827                 oldDiag = getSymbolAccessibilityDiagnostic;
92828                 getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNode(p);
92829             }
92830             var newParam = ts.updateParameter(p, 
92831             /*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
92832             ensureNoInitializer(p));
92833             if (!suppressNewDiagnosticContexts) {
92834                 getSymbolAccessibilityDiagnostic = oldDiag;
92835             }
92836             return newParam;
92837         }
92838         function shouldPrintWithInitializer(node) {
92839             return canHaveLiteralInitializer(node) && resolver.isLiteralConstDeclaration(ts.getParseTreeNode(node)); // TODO: Make safe
92840         }
92841         function ensureNoInitializer(node) {
92842             if (shouldPrintWithInitializer(node)) {
92843                 return resolver.createLiteralConstValue(ts.getParseTreeNode(node), symbolTracker); // TODO: Make safe
92844             }
92845             return undefined;
92846         }
92847         function ensureType(node, type, ignorePrivate) {
92848             if (!ignorePrivate && ts.hasModifier(node, 8 /* Private */)) {
92849                 // Private nodes emit no types (except private parameter properties, whose parameter types are actually visible)
92850                 return;
92851             }
92852             if (shouldPrintWithInitializer(node)) {
92853                 // Literal const declarations will have an initializer ensured rather than a type
92854                 return;
92855             }
92856             var shouldUseResolverType = node.kind === 156 /* Parameter */ &&
92857                 (resolver.isRequiredInitializedParameter(node) ||
92858                     resolver.isOptionalUninitializedParameterProperty(node));
92859             if (type && !shouldUseResolverType) {
92860                 return ts.visitNode(type, visitDeclarationSubtree);
92861             }
92862             if (!ts.getParseTreeNode(node)) {
92863                 return type ? ts.visitNode(type, visitDeclarationSubtree) : ts.createKeywordTypeNode(125 /* AnyKeyword */);
92864             }
92865             if (node.kind === 164 /* SetAccessor */) {
92866                 // 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
92867                 // (The inferred type here will be void, but the old declaration emitter printed `any`, so this replicates that)
92868                 return ts.createKeywordTypeNode(125 /* AnyKeyword */);
92869             }
92870             errorNameNode = node.name;
92871             var oldDiag;
92872             if (!suppressNewDiagnosticContexts) {
92873                 oldDiag = getSymbolAccessibilityDiagnostic;
92874                 getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNode(node);
92875             }
92876             if (node.kind === 242 /* VariableDeclaration */ || node.kind === 191 /* BindingElement */) {
92877                 return cleanup(resolver.createTypeOfDeclaration(node, enclosingDeclaration, declarationEmitNodeBuilderFlags, symbolTracker));
92878             }
92879             if (node.kind === 156 /* Parameter */
92880                 || node.kind === 159 /* PropertyDeclaration */
92881                 || node.kind === 158 /* PropertySignature */) {
92882                 if (!node.initializer)
92883                     return cleanup(resolver.createTypeOfDeclaration(node, enclosingDeclaration, declarationEmitNodeBuilderFlags, symbolTracker, shouldUseResolverType));
92884                 return cleanup(resolver.createTypeOfDeclaration(node, enclosingDeclaration, declarationEmitNodeBuilderFlags, symbolTracker, shouldUseResolverType) || resolver.createTypeOfExpression(node.initializer, enclosingDeclaration, declarationEmitNodeBuilderFlags, symbolTracker));
92885             }
92886             return cleanup(resolver.createReturnTypeOfSignatureDeclaration(node, enclosingDeclaration, declarationEmitNodeBuilderFlags, symbolTracker));
92887             function cleanup(returnValue) {
92888                 errorNameNode = undefined;
92889                 if (!suppressNewDiagnosticContexts) {
92890                     getSymbolAccessibilityDiagnostic = oldDiag;
92891                 }
92892                 return returnValue || ts.createKeywordTypeNode(125 /* AnyKeyword */);
92893             }
92894         }
92895         function isDeclarationAndNotVisible(node) {
92896             node = ts.getParseTreeNode(node);
92897             switch (node.kind) {
92898                 case 244 /* FunctionDeclaration */:
92899                 case 249 /* ModuleDeclaration */:
92900                 case 246 /* InterfaceDeclaration */:
92901                 case 245 /* ClassDeclaration */:
92902                 case 247 /* TypeAliasDeclaration */:
92903                 case 248 /* EnumDeclaration */:
92904                     return !resolver.isDeclarationVisible(node);
92905                 // The following should be doing their own visibility checks based on filtering their members
92906                 case 242 /* VariableDeclaration */:
92907                     return !getBindingNameVisible(node);
92908                 case 253 /* ImportEqualsDeclaration */:
92909                 case 254 /* ImportDeclaration */:
92910                 case 260 /* ExportDeclaration */:
92911                 case 259 /* ExportAssignment */:
92912                     return false;
92913             }
92914             return false;
92915         }
92916         function getBindingNameVisible(elem) {
92917             if (ts.isOmittedExpression(elem)) {
92918                 return false;
92919             }
92920             if (ts.isBindingPattern(elem.name)) {
92921                 // If any child binding pattern element has been marked visible (usually by collect linked aliases), then this is visible
92922                 return ts.some(elem.name.elements, getBindingNameVisible);
92923             }
92924             else {
92925                 return resolver.isDeclarationVisible(elem);
92926             }
92927         }
92928         function updateParamsList(node, params, modifierMask) {
92929             if (ts.hasModifier(node, 8 /* Private */)) {
92930                 return undefined; // TODO: GH#18217
92931             }
92932             var newParams = ts.map(params, function (p) { return ensureParameter(p, modifierMask); });
92933             if (!newParams) {
92934                 return undefined; // TODO: GH#18217
92935             }
92936             return ts.createNodeArray(newParams, params.hasTrailingComma);
92937         }
92938         function updateAccessorParamsList(input, isPrivate) {
92939             var newParams;
92940             if (!isPrivate) {
92941                 var thisParameter = ts.getThisParameter(input);
92942                 if (thisParameter) {
92943                     newParams = [ensureParameter(thisParameter)];
92944                 }
92945             }
92946             if (ts.isSetAccessorDeclaration(input)) {
92947                 var newValueParameter = void 0;
92948                 if (!isPrivate) {
92949                     var valueParameter = ts.getSetAccessorValueParameter(input);
92950                     if (valueParameter) {
92951                         var accessorType = getTypeAnnotationFromAllAccessorDeclarations(input, resolver.getAllAccessorDeclarations(input));
92952                         newValueParameter = ensureParameter(valueParameter, /*modifierMask*/ undefined, accessorType);
92953                     }
92954                 }
92955                 if (!newValueParameter) {
92956                     newValueParameter = ts.createParameter(
92957                     /*decorators*/ undefined, 
92958                     /*modifiers*/ undefined, 
92959                     /*dotDotDotToken*/ undefined, "value");
92960                 }
92961                 newParams = ts.append(newParams, newValueParameter);
92962             }
92963             return ts.createNodeArray(newParams || ts.emptyArray);
92964         }
92965         function ensureTypeParams(node, params) {
92966             return ts.hasModifier(node, 8 /* Private */) ? undefined : ts.visitNodes(params, visitDeclarationSubtree);
92967         }
92968         function isEnclosingDeclaration(node) {
92969             return ts.isSourceFile(node)
92970                 || ts.isTypeAliasDeclaration(node)
92971                 || ts.isModuleDeclaration(node)
92972                 || ts.isClassDeclaration(node)
92973                 || ts.isInterfaceDeclaration(node)
92974                 || ts.isFunctionLike(node)
92975                 || ts.isIndexSignatureDeclaration(node)
92976                 || ts.isMappedTypeNode(node);
92977         }
92978         function checkEntityNameVisibility(entityName, enclosingDeclaration) {
92979             var visibilityResult = resolver.isEntityNameVisible(entityName, enclosingDeclaration);
92980             handleSymbolAccessibilityError(visibilityResult);
92981             recordTypeReferenceDirectivesIfNecessary(resolver.getTypeReferenceDirectivesForEntityName(entityName));
92982         }
92983         function preserveJsDoc(updated, original) {
92984             if (ts.hasJSDocNodes(updated) && ts.hasJSDocNodes(original)) {
92985                 updated.jsDoc = original.jsDoc;
92986             }
92987             return ts.setCommentRange(updated, ts.getCommentRange(original));
92988         }
92989         function rewriteModuleSpecifier(parent, input) {
92990             if (!input)
92991                 return undefined; // TODO: GH#18217
92992             resultHasExternalModuleIndicator = resultHasExternalModuleIndicator || (parent.kind !== 249 /* ModuleDeclaration */ && parent.kind !== 188 /* ImportType */);
92993             if (ts.isStringLiteralLike(input)) {
92994                 if (isBundledEmit) {
92995                     var newName = ts.getExternalModuleNameFromDeclaration(context.getEmitHost(), resolver, parent);
92996                     if (newName) {
92997                         return ts.createLiteral(newName);
92998                     }
92999                 }
93000                 else {
93001                     var symbol = resolver.getSymbolOfExternalModuleSpecifier(input);
93002                     if (symbol) {
93003                         (exportedModulesFromDeclarationEmit || (exportedModulesFromDeclarationEmit = [])).push(symbol);
93004                     }
93005                 }
93006             }
93007             return input;
93008         }
93009         function transformImportEqualsDeclaration(decl) {
93010             if (!resolver.isDeclarationVisible(decl))
93011                 return;
93012             if (decl.moduleReference.kind === 265 /* ExternalModuleReference */) {
93013                 // Rewrite external module names if necessary
93014                 var specifier = ts.getExternalModuleImportEqualsDeclarationExpression(decl);
93015                 return ts.updateImportEqualsDeclaration(decl, 
93016                 /*decorators*/ undefined, decl.modifiers, decl.name, ts.updateExternalModuleReference(decl.moduleReference, rewriteModuleSpecifier(decl, specifier)));
93017             }
93018             else {
93019                 var oldDiag = getSymbolAccessibilityDiagnostic;
93020                 getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNode(decl);
93021                 checkEntityNameVisibility(decl.moduleReference, enclosingDeclaration);
93022                 getSymbolAccessibilityDiagnostic = oldDiag;
93023                 return decl;
93024             }
93025         }
93026         function transformImportDeclaration(decl) {
93027             if (!decl.importClause) {
93028                 // import "mod" - possibly needed for side effects? (global interface patches, module augmentations, etc)
93029                 return ts.updateImportDeclaration(decl, 
93030                 /*decorators*/ undefined, decl.modifiers, decl.importClause, rewriteModuleSpecifier(decl, decl.moduleSpecifier));
93031             }
93032             // The `importClause` visibility corresponds to the default's visibility.
93033             var visibleDefaultBinding = decl.importClause && decl.importClause.name && resolver.isDeclarationVisible(decl.importClause) ? decl.importClause.name : undefined;
93034             if (!decl.importClause.namedBindings) {
93035                 // No named bindings (either namespace or list), meaning the import is just default or should be elided
93036                 return visibleDefaultBinding && ts.updateImportDeclaration(decl, /*decorators*/ undefined, decl.modifiers, ts.updateImportClause(decl.importClause, visibleDefaultBinding, 
93037                 /*namedBindings*/ undefined, decl.importClause.isTypeOnly), rewriteModuleSpecifier(decl, decl.moduleSpecifier));
93038             }
93039             if (decl.importClause.namedBindings.kind === 256 /* NamespaceImport */) {
93040                 // Namespace import (optionally with visible default)
93041                 var namedBindings = resolver.isDeclarationVisible(decl.importClause.namedBindings) ? decl.importClause.namedBindings : /*namedBindings*/ undefined;
93042                 return visibleDefaultBinding || namedBindings ? ts.updateImportDeclaration(decl, /*decorators*/ undefined, decl.modifiers, ts.updateImportClause(decl.importClause, visibleDefaultBinding, namedBindings, decl.importClause.isTypeOnly), rewriteModuleSpecifier(decl, decl.moduleSpecifier)) : undefined;
93043             }
93044             // Named imports (optionally with visible default)
93045             var bindingList = ts.mapDefined(decl.importClause.namedBindings.elements, function (b) { return resolver.isDeclarationVisible(b) ? b : undefined; });
93046             if ((bindingList && bindingList.length) || visibleDefaultBinding) {
93047                 return ts.updateImportDeclaration(decl, 
93048                 /*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));
93049             }
93050             // Augmentation of export depends on import
93051             if (resolver.isImportRequiredByAugmentation(decl)) {
93052                 return ts.updateImportDeclaration(decl, 
93053                 /*decorators*/ undefined, decl.modifiers, 
93054                 /*importClause*/ undefined, rewriteModuleSpecifier(decl, decl.moduleSpecifier));
93055             }
93056             // Nothing visible
93057         }
93058         function transformAndReplaceLatePaintedStatements(statements) {
93059             // This is a `while` loop because `handleSymbolAccessibilityError` can see additional import aliases marked as visible during
93060             // error handling which must now be included in the output and themselves checked for errors.
93061             // For example:
93062             // ```
93063             // module A {
93064             //   export module Q {}
93065             //   import B = Q;
93066             //   import C = B;
93067             //   export import D = C;
93068             // }
93069             // ```
93070             // 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
93071             // 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
93072             // dependent imports and allowing a valid declaration file output. Today, this dependent alias marking only happens for internal import aliases.
93073             while (ts.length(lateMarkedStatements)) {
93074                 var i = lateMarkedStatements.shift();
93075                 if (!ts.isLateVisibilityPaintedStatement(i)) {
93076                     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));
93077                 }
93078                 var priorNeedsDeclare = needsDeclare;
93079                 needsDeclare = i.parent && ts.isSourceFile(i.parent) && !(ts.isExternalModule(i.parent) && isBundledEmit);
93080                 var result = transformTopLevelDeclaration(i);
93081                 needsDeclare = priorNeedsDeclare;
93082                 lateStatementReplacementMap.set("" + ts.getOriginalNodeId(i), result);
93083             }
93084             // And lastly, we need to get the final form of all those indetermine import declarations from before and add them to the output list
93085             // (and remove them from the set to examine for outter declarations)
93086             return ts.visitNodes(statements, visitLateVisibilityMarkedStatements);
93087             function visitLateVisibilityMarkedStatements(statement) {
93088                 if (ts.isLateVisibilityPaintedStatement(statement)) {
93089                     var key = "" + ts.getOriginalNodeId(statement);
93090                     if (lateStatementReplacementMap.has(key)) {
93091                         var result = lateStatementReplacementMap.get(key);
93092                         lateStatementReplacementMap.delete(key);
93093                         if (result) {
93094                             if (ts.isArray(result) ? ts.some(result, ts.needsScopeMarker) : ts.needsScopeMarker(result)) {
93095                                 // Top-level declarations in .d.ts files are always considered exported even without a modifier unless there's an export assignment or specifier
93096                                 needsScopeFixMarker = true;
93097                             }
93098                             if (ts.isSourceFile(statement.parent) && (ts.isArray(result) ? ts.some(result, ts.isExternalModuleIndicator) : ts.isExternalModuleIndicator(result))) {
93099                                 resultHasExternalModuleIndicator = true;
93100                             }
93101                         }
93102                         return result;
93103                     }
93104                 }
93105                 return statement;
93106             }
93107         }
93108         function visitDeclarationSubtree(input) {
93109             if (shouldStripInternal(input))
93110                 return;
93111             if (ts.isDeclaration(input)) {
93112                 if (isDeclarationAndNotVisible(input))
93113                     return;
93114                 if (ts.hasDynamicName(input) && !resolver.isLateBound(ts.getParseTreeNode(input))) {
93115                     return;
93116                 }
93117             }
93118             // Elide implementation signatures from overload sets
93119             if (ts.isFunctionLike(input) && resolver.isImplementationOfOverload(input))
93120                 return;
93121             // Elide semicolon class statements
93122             if (ts.isSemicolonClassElement(input))
93123                 return;
93124             var previousEnclosingDeclaration;
93125             if (isEnclosingDeclaration(input)) {
93126                 previousEnclosingDeclaration = enclosingDeclaration;
93127                 enclosingDeclaration = input;
93128             }
93129             var oldDiag = getSymbolAccessibilityDiagnostic;
93130             // Setup diagnostic-related flags before first potential `cleanup` call, otherwise
93131             // We'd see a TDZ violation at runtime
93132             var canProduceDiagnostic = ts.canProduceDiagnostics(input);
93133             var oldWithinObjectLiteralType = suppressNewDiagnosticContexts;
93134             var shouldEnterSuppressNewDiagnosticsContextContext = ((input.kind === 173 /* TypeLiteral */ || input.kind === 186 /* MappedType */) && input.parent.kind !== 247 /* TypeAliasDeclaration */);
93135             // Emit methods which are private as properties with no type information
93136             if (ts.isMethodDeclaration(input) || ts.isMethodSignature(input)) {
93137                 if (ts.hasModifier(input, 8 /* Private */)) {
93138                     if (input.symbol && input.symbol.declarations && input.symbol.declarations[0] !== input)
93139                         return; // Elide all but the first overload
93140                     return cleanup(ts.createProperty(/*decorators*/ undefined, ensureModifiers(input), input.name, /*questionToken*/ undefined, /*type*/ undefined, /*initializer*/ undefined));
93141                 }
93142             }
93143             if (canProduceDiagnostic && !suppressNewDiagnosticContexts) {
93144                 getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNode(input);
93145             }
93146             if (ts.isTypeQueryNode(input)) {
93147                 checkEntityNameVisibility(input.exprName, enclosingDeclaration);
93148             }
93149             if (shouldEnterSuppressNewDiagnosticsContextContext) {
93150                 // 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.
93151                 suppressNewDiagnosticContexts = true;
93152             }
93153             if (isProcessedComponent(input)) {
93154                 switch (input.kind) {
93155                     case 216 /* ExpressionWithTypeArguments */: {
93156                         if ((ts.isEntityName(input.expression) || ts.isEntityNameExpression(input.expression))) {
93157                             checkEntityNameVisibility(input.expression, enclosingDeclaration);
93158                         }
93159                         var node = ts.visitEachChild(input, visitDeclarationSubtree, context);
93160                         return cleanup(ts.updateExpressionWithTypeArguments(node, ts.parenthesizeTypeParameters(node.typeArguments), node.expression));
93161                     }
93162                     case 169 /* TypeReference */: {
93163                         checkEntityNameVisibility(input.typeName, enclosingDeclaration);
93164                         var node = ts.visitEachChild(input, visitDeclarationSubtree, context);
93165                         return cleanup(ts.updateTypeReferenceNode(node, node.typeName, ts.parenthesizeTypeParameters(node.typeArguments)));
93166                     }
93167                     case 166 /* ConstructSignature */:
93168                         return cleanup(ts.updateConstructSignature(input, ensureTypeParams(input, input.typeParameters), updateParamsList(input, input.parameters), ensureType(input, input.type)));
93169                     case 162 /* Constructor */: {
93170                         // A constructor declaration may not have a type annotation
93171                         var ctor = ts.createSignatureDeclaration(162 /* Constructor */, ensureTypeParams(input, input.typeParameters), updateParamsList(input, input.parameters, 0 /* None */), 
93172                         /*type*/ undefined);
93173                         ctor.modifiers = ts.createNodeArray(ensureModifiers(input));
93174                         return cleanup(ctor);
93175                     }
93176                     case 161 /* MethodDeclaration */: {
93177                         if (ts.isPrivateIdentifier(input.name)) {
93178                             return cleanup(/*returnValue*/ undefined);
93179                         }
93180                         var sig = ts.createSignatureDeclaration(160 /* MethodSignature */, ensureTypeParams(input, input.typeParameters), updateParamsList(input, input.parameters), ensureType(input, input.type));
93181                         sig.name = input.name;
93182                         sig.modifiers = ts.createNodeArray(ensureModifiers(input));
93183                         sig.questionToken = input.questionToken;
93184                         return cleanup(sig);
93185                     }
93186                     case 163 /* GetAccessor */: {
93187                         if (ts.isPrivateIdentifier(input.name)) {
93188                             return cleanup(/*returnValue*/ undefined);
93189                         }
93190                         var accessorType = getTypeAnnotationFromAllAccessorDeclarations(input, resolver.getAllAccessorDeclarations(input));
93191                         return cleanup(ts.updateGetAccessor(input, 
93192                         /*decorators*/ undefined, ensureModifiers(input), input.name, updateAccessorParamsList(input, ts.hasModifier(input, 8 /* Private */)), ensureType(input, accessorType), 
93193                         /*body*/ undefined));
93194                     }
93195                     case 164 /* SetAccessor */: {
93196                         if (ts.isPrivateIdentifier(input.name)) {
93197                             return cleanup(/*returnValue*/ undefined);
93198                         }
93199                         return cleanup(ts.updateSetAccessor(input, 
93200                         /*decorators*/ undefined, ensureModifiers(input), input.name, updateAccessorParamsList(input, ts.hasModifier(input, 8 /* Private */)), 
93201                         /*body*/ undefined));
93202                     }
93203                     case 159 /* PropertyDeclaration */:
93204                         if (ts.isPrivateIdentifier(input.name)) {
93205                             return cleanup(/*returnValue*/ undefined);
93206                         }
93207                         return cleanup(ts.updateProperty(input, 
93208                         /*decorators*/ undefined, ensureModifiers(input), input.name, input.questionToken, ensureType(input, input.type), ensureNoInitializer(input)));
93209                     case 158 /* PropertySignature */:
93210                         if (ts.isPrivateIdentifier(input.name)) {
93211                             return cleanup(/*returnValue*/ undefined);
93212                         }
93213                         return cleanup(ts.updatePropertySignature(input, ensureModifiers(input), input.name, input.questionToken, ensureType(input, input.type), ensureNoInitializer(input)));
93214                     case 160 /* MethodSignature */: {
93215                         if (ts.isPrivateIdentifier(input.name)) {
93216                             return cleanup(/*returnValue*/ undefined);
93217                         }
93218                         return cleanup(ts.updateMethodSignature(input, ensureTypeParams(input, input.typeParameters), updateParamsList(input, input.parameters), ensureType(input, input.type), input.name, input.questionToken));
93219                     }
93220                     case 165 /* CallSignature */: {
93221                         return cleanup(ts.updateCallSignature(input, ensureTypeParams(input, input.typeParameters), updateParamsList(input, input.parameters), ensureType(input, input.type)));
93222                     }
93223                     case 167 /* IndexSignature */: {
93224                         return cleanup(ts.updateIndexSignature(input, 
93225                         /*decorators*/ undefined, ensureModifiers(input), updateParamsList(input, input.parameters), ts.visitNode(input.type, visitDeclarationSubtree) || ts.createKeywordTypeNode(125 /* AnyKeyword */)));
93226                     }
93227                     case 242 /* VariableDeclaration */: {
93228                         if (ts.isBindingPattern(input.name)) {
93229                             return recreateBindingPattern(input.name);
93230                         }
93231                         shouldEnterSuppressNewDiagnosticsContextContext = true;
93232                         suppressNewDiagnosticContexts = true; // Variable declaration types also suppress new diagnostic contexts, provided the contexts wouldn't be made for binding pattern types
93233                         return cleanup(ts.updateTypeScriptVariableDeclaration(input, input.name, /*exclaimationToken*/ undefined, ensureType(input, input.type), ensureNoInitializer(input)));
93234                     }
93235                     case 155 /* TypeParameter */: {
93236                         if (isPrivateMethodTypeParameter(input) && (input.default || input.constraint)) {
93237                             return cleanup(ts.updateTypeParameterDeclaration(input, input.name, /*constraint*/ undefined, /*defaultType*/ undefined));
93238                         }
93239                         return cleanup(ts.visitEachChild(input, visitDeclarationSubtree, context));
93240                     }
93241                     case 180 /* ConditionalType */: {
93242                         // We have to process conditional types in a special way because for visibility purposes we need to push a new enclosingDeclaration
93243                         // just for the `infer` types in the true branch. It's an implicit declaration scope that only applies to _part_ of the type.
93244                         var checkType = ts.visitNode(input.checkType, visitDeclarationSubtree);
93245                         var extendsType = ts.visitNode(input.extendsType, visitDeclarationSubtree);
93246                         var oldEnclosingDecl = enclosingDeclaration;
93247                         enclosingDeclaration = input.trueType;
93248                         var trueType = ts.visitNode(input.trueType, visitDeclarationSubtree);
93249                         enclosingDeclaration = oldEnclosingDecl;
93250                         var falseType = ts.visitNode(input.falseType, visitDeclarationSubtree);
93251                         return cleanup(ts.updateConditionalTypeNode(input, checkType, extendsType, trueType, falseType));
93252                     }
93253                     case 170 /* FunctionType */: {
93254                         return cleanup(ts.updateFunctionTypeNode(input, ts.visitNodes(input.typeParameters, visitDeclarationSubtree), updateParamsList(input, input.parameters), ts.visitNode(input.type, visitDeclarationSubtree)));
93255                     }
93256                     case 171 /* ConstructorType */: {
93257                         return cleanup(ts.updateConstructorTypeNode(input, ts.visitNodes(input.typeParameters, visitDeclarationSubtree), updateParamsList(input, input.parameters), ts.visitNode(input.type, visitDeclarationSubtree)));
93258                     }
93259                     case 188 /* ImportType */: {
93260                         if (!ts.isLiteralImportTypeNode(input))
93261                             return cleanup(input);
93262                         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));
93263                     }
93264                     default: ts.Debug.assertNever(input, "Attempted to process unhandled node kind: " + ts.SyntaxKind[input.kind]);
93265                 }
93266             }
93267             return cleanup(ts.visitEachChild(input, visitDeclarationSubtree, context));
93268             function cleanup(returnValue) {
93269                 if (returnValue && canProduceDiagnostic && ts.hasDynamicName(input)) {
93270                     checkName(input);
93271                 }
93272                 if (isEnclosingDeclaration(input)) {
93273                     enclosingDeclaration = previousEnclosingDeclaration;
93274                 }
93275                 if (canProduceDiagnostic && !suppressNewDiagnosticContexts) {
93276                     getSymbolAccessibilityDiagnostic = oldDiag;
93277                 }
93278                 if (shouldEnterSuppressNewDiagnosticsContextContext) {
93279                     suppressNewDiagnosticContexts = oldWithinObjectLiteralType;
93280                 }
93281                 if (returnValue === input) {
93282                     return returnValue;
93283                 }
93284                 return returnValue && ts.setOriginalNode(preserveJsDoc(returnValue, input), input);
93285             }
93286         }
93287         function isPrivateMethodTypeParameter(node) {
93288             return node.parent.kind === 161 /* MethodDeclaration */ && ts.hasModifier(node.parent, 8 /* Private */);
93289         }
93290         function visitDeclarationStatements(input) {
93291             if (!isPreservedDeclarationStatement(input)) {
93292                 // return undefined for unmatched kinds to omit them from the tree
93293                 return;
93294             }
93295             if (shouldStripInternal(input))
93296                 return;
93297             switch (input.kind) {
93298                 case 260 /* ExportDeclaration */: {
93299                     if (ts.isSourceFile(input.parent)) {
93300                         resultHasExternalModuleIndicator = true;
93301                     }
93302                     resultHasScopeMarker = true;
93303                     // Always visible if the parent node isn't dropped for being not visible
93304                     // Rewrite external module names if necessary
93305                     return ts.updateExportDeclaration(input, 
93306                     /*decorators*/ undefined, input.modifiers, input.exportClause, rewriteModuleSpecifier(input, input.moduleSpecifier), input.isTypeOnly);
93307                 }
93308                 case 259 /* ExportAssignment */: {
93309                     // Always visible if the parent node isn't dropped for being not visible
93310                     if (ts.isSourceFile(input.parent)) {
93311                         resultHasExternalModuleIndicator = true;
93312                     }
93313                     resultHasScopeMarker = true;
93314                     if (input.expression.kind === 75 /* Identifier */) {
93315                         return input;
93316                     }
93317                     else {
93318                         var newId = ts.createOptimisticUniqueName("_default");
93319                         getSymbolAccessibilityDiagnostic = function () { return ({
93320                             diagnosticMessage: ts.Diagnostics.Default_export_of_the_module_has_or_is_using_private_name_0,
93321                             errorNode: input
93322                         }); };
93323                         var varDecl = ts.createVariableDeclaration(newId, resolver.createTypeOfExpression(input.expression, input, declarationEmitNodeBuilderFlags, symbolTracker), /*initializer*/ undefined);
93324                         var statement = ts.createVariableStatement(needsDeclare ? [ts.createModifier(130 /* DeclareKeyword */)] : [], ts.createVariableDeclarationList([varDecl], 2 /* Const */));
93325                         return [statement, ts.updateExportAssignment(input, input.decorators, input.modifiers, newId)];
93326                     }
93327                 }
93328             }
93329             var result = transformTopLevelDeclaration(input);
93330             // Don't actually transform yet; just leave as original node - will be elided/swapped by late pass
93331             lateStatementReplacementMap.set("" + ts.getOriginalNodeId(input), result);
93332             return input;
93333         }
93334         function stripExportModifiers(statement) {
93335             if (ts.isImportEqualsDeclaration(statement) || ts.hasModifier(statement, 512 /* Default */)) {
93336                 // `export import` statements should remain as-is, as imports are _not_ implicitly exported in an ambient namespace
93337                 // Likewise, `export default` classes and the like and just be `default`, so we preserve their `export` modifiers, too
93338                 return statement;
93339             }
93340             var clone = ts.getMutableClone(statement);
93341             var modifiers = ts.createModifiersFromModifierFlags(ts.getModifierFlags(statement) & (3071 /* All */ ^ 1 /* Export */));
93342             clone.modifiers = modifiers.length ? ts.createNodeArray(modifiers) : undefined;
93343             return clone;
93344         }
93345         function transformTopLevelDeclaration(input) {
93346             if (shouldStripInternal(input))
93347                 return;
93348             switch (input.kind) {
93349                 case 253 /* ImportEqualsDeclaration */: {
93350                     return transformImportEqualsDeclaration(input);
93351                 }
93352                 case 254 /* ImportDeclaration */: {
93353                     return transformImportDeclaration(input);
93354                 }
93355             }
93356             if (ts.isDeclaration(input) && isDeclarationAndNotVisible(input))
93357                 return;
93358             // Elide implementation signatures from overload sets
93359             if (ts.isFunctionLike(input) && resolver.isImplementationOfOverload(input))
93360                 return;
93361             var previousEnclosingDeclaration;
93362             if (isEnclosingDeclaration(input)) {
93363                 previousEnclosingDeclaration = enclosingDeclaration;
93364                 enclosingDeclaration = input;
93365             }
93366             var canProdiceDiagnostic = ts.canProduceDiagnostics(input);
93367             var oldDiag = getSymbolAccessibilityDiagnostic;
93368             if (canProdiceDiagnostic) {
93369                 getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNode(input);
93370             }
93371             var previousNeedsDeclare = needsDeclare;
93372             switch (input.kind) {
93373                 case 247 /* TypeAliasDeclaration */: // Type aliases get `declare`d if need be (for legacy support), but that's all
93374                     return cleanup(ts.updateTypeAliasDeclaration(input, 
93375                     /*decorators*/ undefined, ensureModifiers(input), input.name, ts.visitNodes(input.typeParameters, visitDeclarationSubtree, ts.isTypeParameterDeclaration), ts.visitNode(input.type, visitDeclarationSubtree, ts.isTypeNode)));
93376                 case 246 /* InterfaceDeclaration */: {
93377                     return cleanup(ts.updateInterfaceDeclaration(input, 
93378                     /*decorators*/ undefined, ensureModifiers(input), input.name, ensureTypeParams(input, input.typeParameters), transformHeritageClauses(input.heritageClauses), ts.visitNodes(input.members, visitDeclarationSubtree)));
93379                 }
93380                 case 244 /* FunctionDeclaration */: {
93381                     // Generators lose their generator-ness, excepting their return type
93382                     var clean = cleanup(ts.updateFunctionDeclaration(input, 
93383                     /*decorators*/ undefined, ensureModifiers(input), 
93384                     /*asteriskToken*/ undefined, input.name, ensureTypeParams(input, input.typeParameters), updateParamsList(input, input.parameters), ensureType(input, input.type), 
93385                     /*body*/ undefined));
93386                     if (clean && resolver.isExpandoFunctionDeclaration(input)) {
93387                         var props = resolver.getPropertiesOfContainerFunction(input);
93388                         var fakespace_1 = ts.createModuleDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, clean.name || ts.createIdentifier("_default"), ts.createModuleBlock([]), 16 /* Namespace */);
93389                         fakespace_1.flags ^= 8 /* Synthesized */; // unset synthesized so it is usable as an enclosing declaration
93390                         fakespace_1.parent = enclosingDeclaration;
93391                         fakespace_1.locals = ts.createSymbolTable(props);
93392                         fakespace_1.symbol = props[0].parent;
93393                         var declarations = ts.mapDefined(props, function (p) {
93394                             if (!ts.isPropertyAccessExpression(p.valueDeclaration)) {
93395                                 return undefined; // TODO GH#33569: Handle element access expressions that created late bound names (rather than silently omitting them)
93396                             }
93397                             getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNode(p.valueDeclaration);
93398                             var type = resolver.createTypeOfDeclaration(p.valueDeclaration, fakespace_1, declarationEmitNodeBuilderFlags, symbolTracker);
93399                             getSymbolAccessibilityDiagnostic = oldDiag;
93400                             var varDecl = ts.createVariableDeclaration(ts.unescapeLeadingUnderscores(p.escapedName), type, /*initializer*/ undefined);
93401                             return ts.createVariableStatement(/*modifiers*/ undefined, ts.createVariableDeclarationList([varDecl]));
93402                         });
93403                         var namespaceDecl = ts.createModuleDeclaration(/*decorators*/ undefined, ensureModifiers(input), input.name, ts.createModuleBlock(declarations), 16 /* Namespace */);
93404                         if (!ts.hasModifier(clean, 512 /* Default */)) {
93405                             return [clean, namespaceDecl];
93406                         }
93407                         var modifiers = ts.createModifiersFromModifierFlags((ts.getModifierFlags(clean) & ~513 /* ExportDefault */) | 2 /* Ambient */);
93408                         var cleanDeclaration = ts.updateFunctionDeclaration(clean, 
93409                         /*decorators*/ undefined, modifiers, 
93410                         /*asteriskToken*/ undefined, clean.name, clean.typeParameters, clean.parameters, clean.type, 
93411                         /*body*/ undefined);
93412                         var namespaceDeclaration = ts.updateModuleDeclaration(namespaceDecl, 
93413                         /*decorators*/ undefined, modifiers, namespaceDecl.name, namespaceDecl.body);
93414                         var exportDefaultDeclaration = ts.createExportAssignment(
93415                         /*decorators*/ undefined, 
93416                         /*modifiers*/ undefined, 
93417                         /*isExportEquals*/ false, namespaceDecl.name);
93418                         if (ts.isSourceFile(input.parent)) {
93419                             resultHasExternalModuleIndicator = true;
93420                         }
93421                         resultHasScopeMarker = true;
93422                         return [cleanDeclaration, namespaceDeclaration, exportDefaultDeclaration];
93423                     }
93424                     else {
93425                         return clean;
93426                     }
93427                 }
93428                 case 249 /* ModuleDeclaration */: {
93429                     needsDeclare = false;
93430                     var inner = input.body;
93431                     if (inner && inner.kind === 250 /* ModuleBlock */) {
93432                         var oldNeedsScopeFix = needsScopeFixMarker;
93433                         var oldHasScopeFix = resultHasScopeMarker;
93434                         resultHasScopeMarker = false;
93435                         needsScopeFixMarker = false;
93436                         var statements = ts.visitNodes(inner.statements, visitDeclarationStatements);
93437                         var lateStatements = transformAndReplaceLatePaintedStatements(statements);
93438                         if (input.flags & 8388608 /* Ambient */) {
93439                             needsScopeFixMarker = false; // If it was `declare`'d everything is implicitly exported already, ignore late printed "privates"
93440                         }
93441                         // With the final list of statements, there are 3 possibilities:
93442                         // 1. There's an export assignment or export declaration in the namespace - do nothing
93443                         // 2. Everything is exported and there are no export assignments or export declarations - strip all export modifiers
93444                         // 3. Some things are exported, some are not, and there's no marker - add an empty marker
93445                         if (!ts.isGlobalScopeAugmentation(input) && !hasScopeMarker(lateStatements) && !resultHasScopeMarker) {
93446                             if (needsScopeFixMarker) {
93447                                 lateStatements = ts.createNodeArray(__spreadArrays(lateStatements, [ts.createEmptyExports()]));
93448                             }
93449                             else {
93450                                 lateStatements = ts.visitNodes(lateStatements, stripExportModifiers);
93451                             }
93452                         }
93453                         var body = ts.updateModuleBlock(inner, lateStatements);
93454                         needsDeclare = previousNeedsDeclare;
93455                         needsScopeFixMarker = oldNeedsScopeFix;
93456                         resultHasScopeMarker = oldHasScopeFix;
93457                         var mods = ensureModifiers(input);
93458                         return cleanup(ts.updateModuleDeclaration(input, 
93459                         /*decorators*/ undefined, mods, ts.isExternalModuleAugmentation(input) ? rewriteModuleSpecifier(input, input.name) : input.name, body));
93460                     }
93461                     else {
93462                         needsDeclare = previousNeedsDeclare;
93463                         var mods = ensureModifiers(input);
93464                         needsDeclare = false;
93465                         ts.visitNode(inner, visitDeclarationStatements);
93466                         // eagerly transform nested namespaces (the nesting doesn't need any elision or painting done)
93467                         var id = "" + ts.getOriginalNodeId(inner); // TODO: GH#18217
93468                         var body = lateStatementReplacementMap.get(id);
93469                         lateStatementReplacementMap.delete(id);
93470                         return cleanup(ts.updateModuleDeclaration(input, 
93471                         /*decorators*/ undefined, mods, input.name, body));
93472                     }
93473                 }
93474                 case 245 /* ClassDeclaration */: {
93475                     var modifiers = ts.createNodeArray(ensureModifiers(input));
93476                     var typeParameters = ensureTypeParams(input, input.typeParameters);
93477                     var ctor = ts.getFirstConstructorWithBody(input);
93478                     var parameterProperties = void 0;
93479                     if (ctor) {
93480                         var oldDiag_1 = getSymbolAccessibilityDiagnostic;
93481                         parameterProperties = ts.compact(ts.flatMap(ctor.parameters, function (param) {
93482                             if (!ts.hasModifier(param, 92 /* ParameterPropertyModifier */) || shouldStripInternal(param))
93483                                 return;
93484                             getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNode(param);
93485                             if (param.name.kind === 75 /* Identifier */) {
93486                                 return preserveJsDoc(ts.createProperty(
93487                                 /*decorators*/ undefined, ensureModifiers(param), param.name, param.questionToken, ensureType(param, param.type), ensureNoInitializer(param)), param);
93488                             }
93489                             else {
93490                                 // Pattern - this is currently an error, but we emit declarations for it somewhat correctly
93491                                 return walkBindingPattern(param.name);
93492                             }
93493                             function walkBindingPattern(pattern) {
93494                                 var elems;
93495                                 for (var _i = 0, _a = pattern.elements; _i < _a.length; _i++) {
93496                                     var elem = _a[_i];
93497                                     if (ts.isOmittedExpression(elem))
93498                                         continue;
93499                                     if (ts.isBindingPattern(elem.name)) {
93500                                         elems = ts.concatenate(elems, walkBindingPattern(elem.name));
93501                                     }
93502                                     elems = elems || [];
93503                                     elems.push(ts.createProperty(
93504                                     /*decorators*/ undefined, ensureModifiers(param), elem.name, 
93505                                     /*questionToken*/ undefined, ensureType(elem, /*type*/ undefined), 
93506                                     /*initializer*/ undefined));
93507                                 }
93508                                 return elems;
93509                             }
93510                         }));
93511                         getSymbolAccessibilityDiagnostic = oldDiag_1;
93512                     }
93513                     var hasPrivateIdentifier = ts.some(input.members, function (member) { return !!member.name && ts.isPrivateIdentifier(member.name); });
93514                     var privateIdentifier = hasPrivateIdentifier ? [
93515                         ts.createProperty(
93516                         /*decorators*/ undefined, 
93517                         /*modifiers*/ undefined, ts.createPrivateIdentifier("#private"), 
93518                         /*questionToken*/ undefined, 
93519                         /*type*/ undefined, 
93520                         /*initializer*/ undefined)
93521                     ] : undefined;
93522                     var memberNodes = ts.concatenate(ts.concatenate(privateIdentifier, parameterProperties), ts.visitNodes(input.members, visitDeclarationSubtree));
93523                     var members = ts.createNodeArray(memberNodes);
93524                     var extendsClause_1 = ts.getEffectiveBaseTypeNode(input);
93525                     if (extendsClause_1 && !ts.isEntityNameExpression(extendsClause_1.expression) && extendsClause_1.expression.kind !== 100 /* NullKeyword */) {
93526                         // We must add a temporary declaration for the extends clause expression
93527                         var oldId = input.name ? ts.unescapeLeadingUnderscores(input.name.escapedText) : "default";
93528                         var newId_1 = ts.createOptimisticUniqueName(oldId + "_base");
93529                         getSymbolAccessibilityDiagnostic = function () { return ({
93530                             diagnosticMessage: ts.Diagnostics.extends_clause_of_exported_class_0_has_or_is_using_private_name_1,
93531                             errorNode: extendsClause_1,
93532                             typeName: input.name
93533                         }); };
93534                         var varDecl = ts.createVariableDeclaration(newId_1, resolver.createTypeOfExpression(extendsClause_1.expression, input, declarationEmitNodeBuilderFlags, symbolTracker), /*initializer*/ undefined);
93535                         var statement = ts.createVariableStatement(needsDeclare ? [ts.createModifier(130 /* DeclareKeyword */)] : [], ts.createVariableDeclarationList([varDecl], 2 /* Const */));
93536                         var heritageClauses = ts.createNodeArray(ts.map(input.heritageClauses, function (clause) {
93537                             if (clause.token === 90 /* ExtendsKeyword */) {
93538                                 var oldDiag_2 = getSymbolAccessibilityDiagnostic;
93539                                 getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNode(clause.types[0]);
93540                                 var newClause = ts.updateHeritageClause(clause, ts.map(clause.types, function (t) { return ts.updateExpressionWithTypeArguments(t, ts.visitNodes(t.typeArguments, visitDeclarationSubtree), newId_1); }));
93541                                 getSymbolAccessibilityDiagnostic = oldDiag_2;
93542                                 return newClause;
93543                             }
93544                             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));
93545                         }));
93546                         return [statement, cleanup(ts.updateClassDeclaration(input, 
93547                             /*decorators*/ undefined, modifiers, input.name, typeParameters, heritageClauses, members))]; // TODO: GH#18217
93548                     }
93549                     else {
93550                         var heritageClauses = transformHeritageClauses(input.heritageClauses);
93551                         return cleanup(ts.updateClassDeclaration(input, 
93552                         /*decorators*/ undefined, modifiers, input.name, typeParameters, heritageClauses, members));
93553                     }
93554                 }
93555                 case 225 /* VariableStatement */: {
93556                     return cleanup(transformVariableStatement(input));
93557                 }
93558                 case 248 /* EnumDeclaration */: {
93559                     return cleanup(ts.updateEnumDeclaration(input, /*decorators*/ undefined, ts.createNodeArray(ensureModifiers(input)), input.name, ts.createNodeArray(ts.mapDefined(input.members, function (m) {
93560                         if (shouldStripInternal(m))
93561                             return;
93562                         // Rewrite enum values to their constants, if available
93563                         var constValue = resolver.getConstantValue(m);
93564                         return preserveJsDoc(ts.updateEnumMember(m, m.name, constValue !== undefined ? ts.createLiteral(constValue) : undefined), m);
93565                     }))));
93566                 }
93567             }
93568             // Anything left unhandled is an error, so this should be unreachable
93569             return ts.Debug.assertNever(input, "Unhandled top-level node in declaration emit: " + ts.SyntaxKind[input.kind]);
93570             function cleanup(node) {
93571                 if (isEnclosingDeclaration(input)) {
93572                     enclosingDeclaration = previousEnclosingDeclaration;
93573                 }
93574                 if (canProdiceDiagnostic) {
93575                     getSymbolAccessibilityDiagnostic = oldDiag;
93576                 }
93577                 if (input.kind === 249 /* ModuleDeclaration */) {
93578                     needsDeclare = previousNeedsDeclare;
93579                 }
93580                 if (node === input) {
93581                     return node;
93582                 }
93583                 return node && ts.setOriginalNode(preserveJsDoc(node, input), input);
93584             }
93585         }
93586         function transformVariableStatement(input) {
93587             if (!ts.forEach(input.declarationList.declarations, getBindingNameVisible))
93588                 return;
93589             var nodes = ts.visitNodes(input.declarationList.declarations, visitDeclarationSubtree);
93590             if (!ts.length(nodes))
93591                 return;
93592             return ts.updateVariableStatement(input, ts.createNodeArray(ensureModifiers(input)), ts.updateVariableDeclarationList(input.declarationList, nodes));
93593         }
93594         function recreateBindingPattern(d) {
93595             return ts.flatten(ts.mapDefined(d.elements, function (e) { return recreateBindingElement(e); }));
93596         }
93597         function recreateBindingElement(e) {
93598             if (e.kind === 215 /* OmittedExpression */) {
93599                 return;
93600             }
93601             if (e.name) {
93602                 if (!getBindingNameVisible(e))
93603                     return;
93604                 if (ts.isBindingPattern(e.name)) {
93605                     return recreateBindingPattern(e.name);
93606                 }
93607                 else {
93608                     return ts.createVariableDeclaration(e.name, ensureType(e, /*type*/ undefined), /*initializer*/ undefined);
93609                 }
93610             }
93611         }
93612         function checkName(node) {
93613             var oldDiag;
93614             if (!suppressNewDiagnosticContexts) {
93615                 oldDiag = getSymbolAccessibilityDiagnostic;
93616                 getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNodeName(node);
93617             }
93618             errorNameNode = node.name;
93619             ts.Debug.assert(resolver.isLateBound(ts.getParseTreeNode(node))); // Should only be called with dynamic names
93620             var decl = node;
93621             var entityName = decl.name.expression;
93622             checkEntityNameVisibility(entityName, enclosingDeclaration);
93623             if (!suppressNewDiagnosticContexts) {
93624                 getSymbolAccessibilityDiagnostic = oldDiag;
93625             }
93626             errorNameNode = undefined;
93627         }
93628         function shouldStripInternal(node) {
93629             return !!stripInternal && !!node && isInternalDeclaration(node, currentSourceFile);
93630         }
93631         function isScopeMarker(node) {
93632             return ts.isExportAssignment(node) || ts.isExportDeclaration(node);
93633         }
93634         function hasScopeMarker(statements) {
93635             return ts.some(statements, isScopeMarker);
93636         }
93637         function ensureModifiers(node) {
93638             var currentFlags = ts.getModifierFlags(node);
93639             var newFlags = ensureModifierFlags(node);
93640             if (currentFlags === newFlags) {
93641                 return node.modifiers;
93642             }
93643             return ts.createModifiersFromModifierFlags(newFlags);
93644         }
93645         function ensureModifierFlags(node) {
93646             var mask = 3071 /* All */ ^ (4 /* Public */ | 256 /* Async */); // No async modifiers in declaration files
93647             var additions = (needsDeclare && !isAlwaysType(node)) ? 2 /* Ambient */ : 0 /* None */;
93648             var parentIsFile = node.parent.kind === 290 /* SourceFile */;
93649             if (!parentIsFile || (isBundledEmit && parentIsFile && ts.isExternalModule(node.parent))) {
93650                 mask ^= 2 /* Ambient */;
93651                 additions = 0 /* None */;
93652             }
93653             return maskModifierFlags(node, mask, additions);
93654         }
93655         function getTypeAnnotationFromAllAccessorDeclarations(node, accessors) {
93656             var accessorType = getTypeAnnotationFromAccessor(node);
93657             if (!accessorType && node !== accessors.firstAccessor) {
93658                 accessorType = getTypeAnnotationFromAccessor(accessors.firstAccessor);
93659                 // 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
93660                 getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNode(accessors.firstAccessor);
93661             }
93662             if (!accessorType && accessors.secondAccessor && node !== accessors.secondAccessor) {
93663                 accessorType = getTypeAnnotationFromAccessor(accessors.secondAccessor);
93664                 // 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
93665                 getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNode(accessors.secondAccessor);
93666             }
93667             return accessorType;
93668         }
93669         function transformHeritageClauses(nodes) {
93670             return ts.createNodeArray(ts.filter(ts.map(nodes, function (clause) { return ts.updateHeritageClause(clause, ts.visitNodes(ts.createNodeArray(ts.filter(clause.types, function (t) {
93671                 return ts.isEntityNameExpression(t.expression) || (clause.token === 90 /* ExtendsKeyword */ && t.expression.kind === 100 /* NullKeyword */);
93672             })), visitDeclarationSubtree)); }), function (clause) { return clause.types && !!clause.types.length; }));
93673         }
93674     }
93675     ts.transformDeclarations = transformDeclarations;
93676     function isAlwaysType(node) {
93677         if (node.kind === 246 /* InterfaceDeclaration */) {
93678             return true;
93679         }
93680         return false;
93681     }
93682     // Elide "public" modifier, as it is the default
93683     function maskModifiers(node, modifierMask, modifierAdditions) {
93684         return ts.createModifiersFromModifierFlags(maskModifierFlags(node, modifierMask, modifierAdditions));
93685     }
93686     function maskModifierFlags(node, modifierMask, modifierAdditions) {
93687         if (modifierMask === void 0) { modifierMask = 3071 /* All */ ^ 4 /* Public */; }
93688         if (modifierAdditions === void 0) { modifierAdditions = 0 /* None */; }
93689         var flags = (ts.getModifierFlags(node) & modifierMask) | modifierAdditions;
93690         if (flags & 512 /* Default */ && !(flags & 1 /* Export */)) {
93691             // A non-exported default is a nonsequitor - we usually try to remove all export modifiers
93692             // from statements in ambient declarations; but a default export must retain its export modifier to be syntactically valid
93693             flags ^= 1 /* Export */;
93694         }
93695         if (flags & 512 /* Default */ && flags & 2 /* Ambient */) {
93696             flags ^= 2 /* Ambient */; // `declare` is never required alongside `default` (and would be an error if printed)
93697         }
93698         return flags;
93699     }
93700     function getTypeAnnotationFromAccessor(accessor) {
93701         if (accessor) {
93702             return accessor.kind === 163 /* GetAccessor */
93703                 ? accessor.type // Getter - return type
93704                 : accessor.parameters.length > 0
93705                     ? accessor.parameters[0].type // Setter parameter type
93706                     : undefined;
93707         }
93708     }
93709     function canHaveLiteralInitializer(node) {
93710         switch (node.kind) {
93711             case 159 /* PropertyDeclaration */:
93712             case 158 /* PropertySignature */:
93713                 return !ts.hasModifier(node, 8 /* Private */);
93714             case 156 /* Parameter */:
93715             case 242 /* VariableDeclaration */:
93716                 return true;
93717         }
93718         return false;
93719     }
93720     function isPreservedDeclarationStatement(node) {
93721         switch (node.kind) {
93722             case 244 /* FunctionDeclaration */:
93723             case 249 /* ModuleDeclaration */:
93724             case 253 /* ImportEqualsDeclaration */:
93725             case 246 /* InterfaceDeclaration */:
93726             case 245 /* ClassDeclaration */:
93727             case 247 /* TypeAliasDeclaration */:
93728             case 248 /* EnumDeclaration */:
93729             case 225 /* VariableStatement */:
93730             case 254 /* ImportDeclaration */:
93731             case 260 /* ExportDeclaration */:
93732             case 259 /* ExportAssignment */:
93733                 return true;
93734         }
93735         return false;
93736     }
93737     function isProcessedComponent(node) {
93738         switch (node.kind) {
93739             case 166 /* ConstructSignature */:
93740             case 162 /* Constructor */:
93741             case 161 /* MethodDeclaration */:
93742             case 163 /* GetAccessor */:
93743             case 164 /* SetAccessor */:
93744             case 159 /* PropertyDeclaration */:
93745             case 158 /* PropertySignature */:
93746             case 160 /* MethodSignature */:
93747             case 165 /* CallSignature */:
93748             case 167 /* IndexSignature */:
93749             case 242 /* VariableDeclaration */:
93750             case 155 /* TypeParameter */:
93751             case 216 /* ExpressionWithTypeArguments */:
93752             case 169 /* TypeReference */:
93753             case 180 /* ConditionalType */:
93754             case 170 /* FunctionType */:
93755             case 171 /* ConstructorType */:
93756             case 188 /* ImportType */:
93757                 return true;
93758         }
93759         return false;
93760     }
93761 })(ts || (ts = {}));
93762 /* @internal */
93763 var ts;
93764 (function (ts) {
93765     function getModuleTransformer(moduleKind) {
93766         switch (moduleKind) {
93767             case ts.ModuleKind.ESNext:
93768             case ts.ModuleKind.ES2020:
93769             case ts.ModuleKind.ES2015:
93770                 return ts.transformECMAScriptModule;
93771             case ts.ModuleKind.System:
93772                 return ts.transformSystemModule;
93773             default:
93774                 return ts.transformModule;
93775         }
93776     }
93777     var TransformationState;
93778     (function (TransformationState) {
93779         TransformationState[TransformationState["Uninitialized"] = 0] = "Uninitialized";
93780         TransformationState[TransformationState["Initialized"] = 1] = "Initialized";
93781         TransformationState[TransformationState["Completed"] = 2] = "Completed";
93782         TransformationState[TransformationState["Disposed"] = 3] = "Disposed";
93783     })(TransformationState || (TransformationState = {}));
93784     var SyntaxKindFeatureFlags;
93785     (function (SyntaxKindFeatureFlags) {
93786         SyntaxKindFeatureFlags[SyntaxKindFeatureFlags["Substitution"] = 1] = "Substitution";
93787         SyntaxKindFeatureFlags[SyntaxKindFeatureFlags["EmitNotifications"] = 2] = "EmitNotifications";
93788     })(SyntaxKindFeatureFlags || (SyntaxKindFeatureFlags = {}));
93789     ts.noTransformers = { scriptTransformers: ts.emptyArray, declarationTransformers: ts.emptyArray };
93790     function getTransformers(compilerOptions, customTransformers, emitOnlyDtsFiles) {
93791         return {
93792             scriptTransformers: getScriptTransformers(compilerOptions, customTransformers, emitOnlyDtsFiles),
93793             declarationTransformers: getDeclarationTransformers(customTransformers),
93794         };
93795     }
93796     ts.getTransformers = getTransformers;
93797     function getScriptTransformers(compilerOptions, customTransformers, emitOnlyDtsFiles) {
93798         if (emitOnlyDtsFiles)
93799             return ts.emptyArray;
93800         var jsx = compilerOptions.jsx;
93801         var languageVersion = ts.getEmitScriptTarget(compilerOptions);
93802         var moduleKind = ts.getEmitModuleKind(compilerOptions);
93803         var transformers = [];
93804         ts.addRange(transformers, customTransformers && ts.map(customTransformers.before, wrapScriptTransformerFactory));
93805         transformers.push(ts.transformTypeScript);
93806         transformers.push(ts.transformClassFields);
93807         if (jsx === 2 /* React */) {
93808             transformers.push(ts.transformJsx);
93809         }
93810         if (languageVersion < 99 /* ESNext */) {
93811             transformers.push(ts.transformESNext);
93812         }
93813         if (languageVersion < 7 /* ES2020 */) {
93814             transformers.push(ts.transformES2020);
93815         }
93816         if (languageVersion < 6 /* ES2019 */) {
93817             transformers.push(ts.transformES2019);
93818         }
93819         if (languageVersion < 5 /* ES2018 */) {
93820             transformers.push(ts.transformES2018);
93821         }
93822         if (languageVersion < 4 /* ES2017 */) {
93823             transformers.push(ts.transformES2017);
93824         }
93825         if (languageVersion < 3 /* ES2016 */) {
93826             transformers.push(ts.transformES2016);
93827         }
93828         if (languageVersion < 2 /* ES2015 */) {
93829             transformers.push(ts.transformES2015);
93830             transformers.push(ts.transformGenerators);
93831         }
93832         transformers.push(getModuleTransformer(moduleKind));
93833         // The ES5 transformer is last so that it can substitute expressions like `exports.default`
93834         // for ES3.
93835         if (languageVersion < 1 /* ES5 */) {
93836             transformers.push(ts.transformES5);
93837         }
93838         ts.addRange(transformers, customTransformers && ts.map(customTransformers.after, wrapScriptTransformerFactory));
93839         return transformers;
93840     }
93841     function getDeclarationTransformers(customTransformers) {
93842         var transformers = [];
93843         transformers.push(ts.transformDeclarations);
93844         ts.addRange(transformers, customTransformers && ts.map(customTransformers.afterDeclarations, wrapDeclarationTransformerFactory));
93845         return transformers;
93846     }
93847     /**
93848      * Wrap a custom script or declaration transformer object in a `Transformer` callback with fallback support for transforming bundles.
93849      */
93850     function wrapCustomTransformer(transformer) {
93851         return function (node) { return ts.isBundle(node) ? transformer.transformBundle(node) : transformer.transformSourceFile(node); };
93852     }
93853     /**
93854      * Wrap a transformer factory that may return a custom script or declaration transformer object.
93855      */
93856     function wrapCustomTransformerFactory(transformer, handleDefault) {
93857         return function (context) {
93858             var customTransformer = transformer(context);
93859             return typeof customTransformer === "function"
93860                 ? handleDefault(customTransformer)
93861                 : wrapCustomTransformer(customTransformer);
93862         };
93863     }
93864     function wrapScriptTransformerFactory(transformer) {
93865         return wrapCustomTransformerFactory(transformer, ts.chainBundle);
93866     }
93867     function wrapDeclarationTransformerFactory(transformer) {
93868         return wrapCustomTransformerFactory(transformer, ts.identity);
93869     }
93870     function noEmitSubstitution(_hint, node) {
93871         return node;
93872     }
93873     ts.noEmitSubstitution = noEmitSubstitution;
93874     function noEmitNotification(hint, node, callback) {
93875         callback(hint, node);
93876     }
93877     ts.noEmitNotification = noEmitNotification;
93878     /**
93879      * Transforms an array of SourceFiles by passing them through each transformer.
93880      *
93881      * @param resolver The emit resolver provided by the checker.
93882      * @param host The emit host object used to interact with the file system.
93883      * @param options Compiler options to surface in the `TransformationContext`.
93884      * @param nodes An array of nodes to transform.
93885      * @param transforms An array of `TransformerFactory` callbacks.
93886      * @param allowDtsFiles A value indicating whether to allow the transformation of .d.ts files.
93887      */
93888     function transformNodes(resolver, host, options, nodes, transformers, allowDtsFiles) {
93889         var enabledSyntaxKindFeatures = new Array(331 /* Count */);
93890         var lexicalEnvironmentVariableDeclarations;
93891         var lexicalEnvironmentFunctionDeclarations;
93892         var lexicalEnvironmentStatements;
93893         var lexicalEnvironmentFlags = 0 /* None */;
93894         var lexicalEnvironmentVariableDeclarationsStack = [];
93895         var lexicalEnvironmentFunctionDeclarationsStack = [];
93896         var lexicalEnvironmentStatementsStack = [];
93897         var lexicalEnvironmentFlagsStack = [];
93898         var lexicalEnvironmentStackOffset = 0;
93899         var lexicalEnvironmentSuspended = false;
93900         var emitHelpers;
93901         var onSubstituteNode = noEmitSubstitution;
93902         var onEmitNode = noEmitNotification;
93903         var state = 0 /* Uninitialized */;
93904         var diagnostics = [];
93905         // The transformation context is provided to each transformer as part of transformer
93906         // initialization.
93907         var context = {
93908             getCompilerOptions: function () { return options; },
93909             getEmitResolver: function () { return resolver; },
93910             getEmitHost: function () { return host; },
93911             startLexicalEnvironment: startLexicalEnvironment,
93912             suspendLexicalEnvironment: suspendLexicalEnvironment,
93913             resumeLexicalEnvironment: resumeLexicalEnvironment,
93914             endLexicalEnvironment: endLexicalEnvironment,
93915             setLexicalEnvironmentFlags: setLexicalEnvironmentFlags,
93916             getLexicalEnvironmentFlags: getLexicalEnvironmentFlags,
93917             hoistVariableDeclaration: hoistVariableDeclaration,
93918             hoistFunctionDeclaration: hoistFunctionDeclaration,
93919             addInitializationStatement: addInitializationStatement,
93920             requestEmitHelper: requestEmitHelper,
93921             readEmitHelpers: readEmitHelpers,
93922             enableSubstitution: enableSubstitution,
93923             enableEmitNotification: enableEmitNotification,
93924             isSubstitutionEnabled: isSubstitutionEnabled,
93925             isEmitNotificationEnabled: isEmitNotificationEnabled,
93926             get onSubstituteNode() { return onSubstituteNode; },
93927             set onSubstituteNode(value) {
93928                 ts.Debug.assert(state < 1 /* Initialized */, "Cannot modify transformation hooks after initialization has completed.");
93929                 ts.Debug.assert(value !== undefined, "Value must not be 'undefined'");
93930                 onSubstituteNode = value;
93931             },
93932             get onEmitNode() { return onEmitNode; },
93933             set onEmitNode(value) {
93934                 ts.Debug.assert(state < 1 /* Initialized */, "Cannot modify transformation hooks after initialization has completed.");
93935                 ts.Debug.assert(value !== undefined, "Value must not be 'undefined'");
93936                 onEmitNode = value;
93937             },
93938             addDiagnostic: function (diag) {
93939                 diagnostics.push(diag);
93940             }
93941         };
93942         // Ensure the parse tree is clean before applying transformations
93943         for (var _i = 0, nodes_4 = nodes; _i < nodes_4.length; _i++) {
93944             var node = nodes_4[_i];
93945             ts.disposeEmitNodes(ts.getSourceFileOfNode(ts.getParseTreeNode(node)));
93946         }
93947         ts.performance.mark("beforeTransform");
93948         // Chain together and initialize each transformer.
93949         var transformersWithContext = transformers.map(function (t) { return t(context); });
93950         var transformation = function (node) {
93951             for (var _i = 0, transformersWithContext_1 = transformersWithContext; _i < transformersWithContext_1.length; _i++) {
93952                 var transform = transformersWithContext_1[_i];
93953                 node = transform(node);
93954             }
93955             return node;
93956         };
93957         // prevent modification of transformation hooks.
93958         state = 1 /* Initialized */;
93959         // Transform each node.
93960         var transformed = ts.map(nodes, allowDtsFiles ? transformation : transformRoot);
93961         // prevent modification of the lexical environment.
93962         state = 2 /* Completed */;
93963         ts.performance.mark("afterTransform");
93964         ts.performance.measure("transformTime", "beforeTransform", "afterTransform");
93965         return {
93966             transformed: transformed,
93967             substituteNode: substituteNode,
93968             emitNodeWithNotification: emitNodeWithNotification,
93969             isEmitNotificationEnabled: isEmitNotificationEnabled,
93970             dispose: dispose,
93971             diagnostics: diagnostics
93972         };
93973         function transformRoot(node) {
93974             return node && (!ts.isSourceFile(node) || !node.isDeclarationFile) ? transformation(node) : node;
93975         }
93976         /**
93977          * Enables expression substitutions in the pretty printer for the provided SyntaxKind.
93978          */
93979         function enableSubstitution(kind) {
93980             ts.Debug.assert(state < 2 /* Completed */, "Cannot modify the transformation context after transformation has completed.");
93981             enabledSyntaxKindFeatures[kind] |= 1 /* Substitution */;
93982         }
93983         /**
93984          * Determines whether expression substitutions are enabled for the provided node.
93985          */
93986         function isSubstitutionEnabled(node) {
93987             return (enabledSyntaxKindFeatures[node.kind] & 1 /* Substitution */) !== 0
93988                 && (ts.getEmitFlags(node) & 4 /* NoSubstitution */) === 0;
93989         }
93990         /**
93991          * Emits a node with possible substitution.
93992          *
93993          * @param hint A hint as to the intended usage of the node.
93994          * @param node The node to emit.
93995          * @param emitCallback The callback used to emit the node or its substitute.
93996          */
93997         function substituteNode(hint, node) {
93998             ts.Debug.assert(state < 3 /* Disposed */, "Cannot substitute a node after the result is disposed.");
93999             return node && isSubstitutionEnabled(node) && onSubstituteNode(hint, node) || node;
94000         }
94001         /**
94002          * Enables before/after emit notifications in the pretty printer for the provided SyntaxKind.
94003          */
94004         function enableEmitNotification(kind) {
94005             ts.Debug.assert(state < 2 /* Completed */, "Cannot modify the transformation context after transformation has completed.");
94006             enabledSyntaxKindFeatures[kind] |= 2 /* EmitNotifications */;
94007         }
94008         /**
94009          * Determines whether before/after emit notifications should be raised in the pretty
94010          * printer when it emits a node.
94011          */
94012         function isEmitNotificationEnabled(node) {
94013             return (enabledSyntaxKindFeatures[node.kind] & 2 /* EmitNotifications */) !== 0
94014                 || (ts.getEmitFlags(node) & 2 /* AdviseOnEmitNode */) !== 0;
94015         }
94016         /**
94017          * Emits a node with possible emit notification.
94018          *
94019          * @param hint A hint as to the intended usage of the node.
94020          * @param node The node to emit.
94021          * @param emitCallback The callback used to emit the node.
94022          */
94023         function emitNodeWithNotification(hint, node, emitCallback) {
94024             ts.Debug.assert(state < 3 /* Disposed */, "Cannot invoke TransformationResult callbacks after the result is disposed.");
94025             if (node) {
94026                 // TODO: Remove check and unconditionally use onEmitNode when API is breakingly changed
94027                 // (see https://github.com/microsoft/TypeScript/pull/36248/files/5062623f39120171b98870c71344b3242eb03d23#r369766739)
94028                 if (isEmitNotificationEnabled(node)) {
94029                     onEmitNode(hint, node, emitCallback);
94030                 }
94031                 else {
94032                     emitCallback(hint, node);
94033                 }
94034             }
94035         }
94036         /**
94037          * Records a hoisted variable declaration for the provided name within a lexical environment.
94038          */
94039         function hoistVariableDeclaration(name) {
94040             ts.Debug.assert(state > 0 /* Uninitialized */, "Cannot modify the lexical environment during initialization.");
94041             ts.Debug.assert(state < 2 /* Completed */, "Cannot modify the lexical environment after transformation has completed.");
94042             var decl = ts.setEmitFlags(ts.createVariableDeclaration(name), 64 /* NoNestedSourceMaps */);
94043             if (!lexicalEnvironmentVariableDeclarations) {
94044                 lexicalEnvironmentVariableDeclarations = [decl];
94045             }
94046             else {
94047                 lexicalEnvironmentVariableDeclarations.push(decl);
94048             }
94049             if (lexicalEnvironmentFlags & 1 /* InParameters */) {
94050                 lexicalEnvironmentFlags |= 2 /* VariablesHoistedInParameters */;
94051             }
94052         }
94053         /**
94054          * Records a hoisted function declaration within a lexical environment.
94055          */
94056         function hoistFunctionDeclaration(func) {
94057             ts.Debug.assert(state > 0 /* Uninitialized */, "Cannot modify the lexical environment during initialization.");
94058             ts.Debug.assert(state < 2 /* Completed */, "Cannot modify the lexical environment after transformation has completed.");
94059             ts.setEmitFlags(func, 1048576 /* CustomPrologue */);
94060             if (!lexicalEnvironmentFunctionDeclarations) {
94061                 lexicalEnvironmentFunctionDeclarations = [func];
94062             }
94063             else {
94064                 lexicalEnvironmentFunctionDeclarations.push(func);
94065             }
94066         }
94067         /**
94068          * Adds an initialization statement to the top of the lexical environment.
94069          */
94070         function addInitializationStatement(node) {
94071             ts.Debug.assert(state > 0 /* Uninitialized */, "Cannot modify the lexical environment during initialization.");
94072             ts.Debug.assert(state < 2 /* Completed */, "Cannot modify the lexical environment after transformation has completed.");
94073             ts.setEmitFlags(node, 1048576 /* CustomPrologue */);
94074             if (!lexicalEnvironmentStatements) {
94075                 lexicalEnvironmentStatements = [node];
94076             }
94077             else {
94078                 lexicalEnvironmentStatements.push(node);
94079             }
94080         }
94081         /**
94082          * Starts a new lexical environment. Any existing hoisted variable or function declarations
94083          * are pushed onto a stack, and the related storage variables are reset.
94084          */
94085         function startLexicalEnvironment() {
94086             ts.Debug.assert(state > 0 /* Uninitialized */, "Cannot modify the lexical environment during initialization.");
94087             ts.Debug.assert(state < 2 /* Completed */, "Cannot modify the lexical environment after transformation has completed.");
94088             ts.Debug.assert(!lexicalEnvironmentSuspended, "Lexical environment is suspended.");
94089             // Save the current lexical environment. Rather than resizing the array we adjust the
94090             // stack size variable. This allows us to reuse existing array slots we've
94091             // already allocated between transformations to avoid allocation and GC overhead during
94092             // transformation.
94093             lexicalEnvironmentVariableDeclarationsStack[lexicalEnvironmentStackOffset] = lexicalEnvironmentVariableDeclarations;
94094             lexicalEnvironmentFunctionDeclarationsStack[lexicalEnvironmentStackOffset] = lexicalEnvironmentFunctionDeclarations;
94095             lexicalEnvironmentStatementsStack[lexicalEnvironmentStackOffset] = lexicalEnvironmentStatements;
94096             lexicalEnvironmentFlagsStack[lexicalEnvironmentStackOffset] = lexicalEnvironmentFlags;
94097             lexicalEnvironmentStackOffset++;
94098             lexicalEnvironmentVariableDeclarations = undefined;
94099             lexicalEnvironmentFunctionDeclarations = undefined;
94100             lexicalEnvironmentStatements = undefined;
94101             lexicalEnvironmentFlags = 0 /* None */;
94102         }
94103         /** Suspends the current lexical environment, usually after visiting a parameter list. */
94104         function suspendLexicalEnvironment() {
94105             ts.Debug.assert(state > 0 /* Uninitialized */, "Cannot modify the lexical environment during initialization.");
94106             ts.Debug.assert(state < 2 /* Completed */, "Cannot modify the lexical environment after transformation has completed.");
94107             ts.Debug.assert(!lexicalEnvironmentSuspended, "Lexical environment is already suspended.");
94108             lexicalEnvironmentSuspended = true;
94109         }
94110         /** Resumes a suspended lexical environment, usually before visiting a function body. */
94111         function resumeLexicalEnvironment() {
94112             ts.Debug.assert(state > 0 /* Uninitialized */, "Cannot modify the lexical environment during initialization.");
94113             ts.Debug.assert(state < 2 /* Completed */, "Cannot modify the lexical environment after transformation has completed.");
94114             ts.Debug.assert(lexicalEnvironmentSuspended, "Lexical environment is not suspended.");
94115             lexicalEnvironmentSuspended = false;
94116         }
94117         /**
94118          * Ends a lexical environment. The previous set of hoisted declarations are restored and
94119          * any hoisted declarations added in this environment are returned.
94120          */
94121         function endLexicalEnvironment() {
94122             ts.Debug.assert(state > 0 /* Uninitialized */, "Cannot modify the lexical environment during initialization.");
94123             ts.Debug.assert(state < 2 /* Completed */, "Cannot modify the lexical environment after transformation has completed.");
94124             ts.Debug.assert(!lexicalEnvironmentSuspended, "Lexical environment is suspended.");
94125             var statements;
94126             if (lexicalEnvironmentVariableDeclarations ||
94127                 lexicalEnvironmentFunctionDeclarations ||
94128                 lexicalEnvironmentStatements) {
94129                 if (lexicalEnvironmentFunctionDeclarations) {
94130                     statements = __spreadArrays(lexicalEnvironmentFunctionDeclarations);
94131                 }
94132                 if (lexicalEnvironmentVariableDeclarations) {
94133                     var statement = ts.createVariableStatement(
94134                     /*modifiers*/ undefined, ts.createVariableDeclarationList(lexicalEnvironmentVariableDeclarations));
94135                     ts.setEmitFlags(statement, 1048576 /* CustomPrologue */);
94136                     if (!statements) {
94137                         statements = [statement];
94138                     }
94139                     else {
94140                         statements.push(statement);
94141                     }
94142                 }
94143                 if (lexicalEnvironmentStatements) {
94144                     if (!statements) {
94145                         statements = __spreadArrays(lexicalEnvironmentStatements);
94146                     }
94147                     else {
94148                         statements = __spreadArrays(statements, lexicalEnvironmentStatements);
94149                     }
94150                 }
94151             }
94152             // Restore the previous lexical environment.
94153             lexicalEnvironmentStackOffset--;
94154             lexicalEnvironmentVariableDeclarations = lexicalEnvironmentVariableDeclarationsStack[lexicalEnvironmentStackOffset];
94155             lexicalEnvironmentFunctionDeclarations = lexicalEnvironmentFunctionDeclarationsStack[lexicalEnvironmentStackOffset];
94156             lexicalEnvironmentStatements = lexicalEnvironmentStatementsStack[lexicalEnvironmentStackOffset];
94157             lexicalEnvironmentFlags = lexicalEnvironmentFlagsStack[lexicalEnvironmentStackOffset];
94158             if (lexicalEnvironmentStackOffset === 0) {
94159                 lexicalEnvironmentVariableDeclarationsStack = [];
94160                 lexicalEnvironmentFunctionDeclarationsStack = [];
94161                 lexicalEnvironmentStatementsStack = [];
94162                 lexicalEnvironmentFlagsStack = [];
94163             }
94164             return statements;
94165         }
94166         function setLexicalEnvironmentFlags(flags, value) {
94167             lexicalEnvironmentFlags = value ?
94168                 lexicalEnvironmentFlags | flags :
94169                 lexicalEnvironmentFlags & ~flags;
94170         }
94171         function getLexicalEnvironmentFlags() {
94172             return lexicalEnvironmentFlags;
94173         }
94174         function requestEmitHelper(helper) {
94175             ts.Debug.assert(state > 0 /* Uninitialized */, "Cannot modify the transformation context during initialization.");
94176             ts.Debug.assert(state < 2 /* Completed */, "Cannot modify the transformation context after transformation has completed.");
94177             ts.Debug.assert(!helper.scoped, "Cannot request a scoped emit helper.");
94178             if (helper.dependencies) {
94179                 for (var _i = 0, _a = helper.dependencies; _i < _a.length; _i++) {
94180                     var h = _a[_i];
94181                     requestEmitHelper(h);
94182                 }
94183             }
94184             emitHelpers = ts.append(emitHelpers, helper);
94185         }
94186         function readEmitHelpers() {
94187             ts.Debug.assert(state > 0 /* Uninitialized */, "Cannot modify the transformation context during initialization.");
94188             ts.Debug.assert(state < 2 /* Completed */, "Cannot modify the transformation context after transformation has completed.");
94189             var helpers = emitHelpers;
94190             emitHelpers = undefined;
94191             return helpers;
94192         }
94193         function dispose() {
94194             if (state < 3 /* Disposed */) {
94195                 // Clean up emit nodes on parse tree
94196                 for (var _i = 0, nodes_5 = nodes; _i < nodes_5.length; _i++) {
94197                     var node = nodes_5[_i];
94198                     ts.disposeEmitNodes(ts.getSourceFileOfNode(ts.getParseTreeNode(node)));
94199                 }
94200                 // Release references to external entries for GC purposes.
94201                 lexicalEnvironmentVariableDeclarations = undefined;
94202                 lexicalEnvironmentVariableDeclarationsStack = undefined;
94203                 lexicalEnvironmentFunctionDeclarations = undefined;
94204                 lexicalEnvironmentFunctionDeclarationsStack = undefined;
94205                 onSubstituteNode = undefined;
94206                 onEmitNode = undefined;
94207                 emitHelpers = undefined;
94208                 // Prevent further use of the transformation result.
94209                 state = 3 /* Disposed */;
94210             }
94211         }
94212     }
94213     ts.transformNodes = transformNodes;
94214 })(ts || (ts = {}));
94215 var ts;
94216 (function (ts) {
94217     var brackets = createBracketsMap();
94218     var syntheticParent = { pos: -1, end: -1 };
94219     /*@internal*/
94220     function isBuildInfoFile(file) {
94221         return ts.fileExtensionIs(file, ".tsbuildinfo" /* TsBuildInfo */);
94222     }
94223     ts.isBuildInfoFile = isBuildInfoFile;
94224     /*@internal*/
94225     /**
94226      * Iterates over the source files that are expected to have an emit output.
94227      *
94228      * @param host An EmitHost.
94229      * @param action The action to execute.
94230      * @param sourceFilesOrTargetSourceFile
94231      *   If an array, the full list of source files to emit.
94232      *   Else, calls `getSourceFilesToEmit` with the (optional) target source file to determine the list of source files to emit.
94233      */
94234     function forEachEmittedFile(host, action, sourceFilesOrTargetSourceFile, forceDtsEmit, onlyBuildInfo, includeBuildInfo) {
94235         if (forceDtsEmit === void 0) { forceDtsEmit = false; }
94236         var sourceFiles = ts.isArray(sourceFilesOrTargetSourceFile) ? sourceFilesOrTargetSourceFile : ts.getSourceFilesToEmit(host, sourceFilesOrTargetSourceFile, forceDtsEmit);
94237         var options = host.getCompilerOptions();
94238         if (options.outFile || options.out) {
94239             var prepends = host.getPrependNodes();
94240             if (sourceFiles.length || prepends.length) {
94241                 var bundle = ts.createBundle(sourceFiles, prepends);
94242                 var result = action(getOutputPathsFor(bundle, host, forceDtsEmit), bundle);
94243                 if (result) {
94244                     return result;
94245                 }
94246             }
94247         }
94248         else {
94249             if (!onlyBuildInfo) {
94250                 for (var _a = 0, sourceFiles_1 = sourceFiles; _a < sourceFiles_1.length; _a++) {
94251                     var sourceFile = sourceFiles_1[_a];
94252                     var result = action(getOutputPathsFor(sourceFile, host, forceDtsEmit), sourceFile);
94253                     if (result) {
94254                         return result;
94255                     }
94256                 }
94257             }
94258             if (includeBuildInfo) {
94259                 var buildInfoPath = getTsBuildInfoEmitOutputFilePath(host.getCompilerOptions());
94260                 if (buildInfoPath)
94261                     return action({ buildInfoPath: buildInfoPath }, /*sourceFileOrBundle*/ undefined);
94262             }
94263         }
94264     }
94265     ts.forEachEmittedFile = forEachEmittedFile;
94266     function getTsBuildInfoEmitOutputFilePath(options) {
94267         var configFile = options.configFilePath;
94268         if (!ts.isIncrementalCompilation(options))
94269             return undefined;
94270         if (options.tsBuildInfoFile)
94271             return options.tsBuildInfoFile;
94272         var outPath = options.outFile || options.out;
94273         var buildInfoExtensionLess;
94274         if (outPath) {
94275             buildInfoExtensionLess = ts.removeFileExtension(outPath);
94276         }
94277         else {
94278             if (!configFile)
94279                 return undefined;
94280             var configFileExtensionLess = ts.removeFileExtension(configFile);
94281             buildInfoExtensionLess = options.outDir ?
94282                 options.rootDir ?
94283                     ts.resolvePath(options.outDir, ts.getRelativePathFromDirectory(options.rootDir, configFileExtensionLess, /*ignoreCase*/ true)) :
94284                     ts.combinePaths(options.outDir, ts.getBaseFileName(configFileExtensionLess)) :
94285                 configFileExtensionLess;
94286         }
94287         return buildInfoExtensionLess + ".tsbuildinfo" /* TsBuildInfo */;
94288     }
94289     ts.getTsBuildInfoEmitOutputFilePath = getTsBuildInfoEmitOutputFilePath;
94290     /*@internal*/
94291     function getOutputPathsForBundle(options, forceDtsPaths) {
94292         var outPath = options.outFile || options.out;
94293         var jsFilePath = options.emitDeclarationOnly ? undefined : outPath;
94294         var sourceMapFilePath = jsFilePath && getSourceMapFilePath(jsFilePath, options);
94295         var declarationFilePath = (forceDtsPaths || ts.getEmitDeclarations(options)) ? ts.removeFileExtension(outPath) + ".d.ts" /* Dts */ : undefined;
94296         var declarationMapPath = declarationFilePath && ts.getAreDeclarationMapsEnabled(options) ? declarationFilePath + ".map" : undefined;
94297         var buildInfoPath = getTsBuildInfoEmitOutputFilePath(options);
94298         return { jsFilePath: jsFilePath, sourceMapFilePath: sourceMapFilePath, declarationFilePath: declarationFilePath, declarationMapPath: declarationMapPath, buildInfoPath: buildInfoPath };
94299     }
94300     ts.getOutputPathsForBundle = getOutputPathsForBundle;
94301     /*@internal*/
94302     function getOutputPathsFor(sourceFile, host, forceDtsPaths) {
94303         var options = host.getCompilerOptions();
94304         if (sourceFile.kind === 291 /* Bundle */) {
94305             return getOutputPathsForBundle(options, forceDtsPaths);
94306         }
94307         else {
94308             var ownOutputFilePath = ts.getOwnEmitOutputFilePath(sourceFile.fileName, host, getOutputExtension(sourceFile, options));
94309             var isJsonFile = ts.isJsonSourceFile(sourceFile);
94310             // If json file emits to the same location skip writing it, if emitDeclarationOnly skip writing it
94311             var isJsonEmittedToSameLocation = isJsonFile &&
94312                 ts.comparePaths(sourceFile.fileName, ownOutputFilePath, host.getCurrentDirectory(), !host.useCaseSensitiveFileNames()) === 0 /* EqualTo */;
94313             var jsFilePath = options.emitDeclarationOnly || isJsonEmittedToSameLocation ? undefined : ownOutputFilePath;
94314             var sourceMapFilePath = !jsFilePath || ts.isJsonSourceFile(sourceFile) ? undefined : getSourceMapFilePath(jsFilePath, options);
94315             var declarationFilePath = (forceDtsPaths || (ts.getEmitDeclarations(options) && !isJsonFile)) ? ts.getDeclarationEmitOutputFilePath(sourceFile.fileName, host) : undefined;
94316             var declarationMapPath = declarationFilePath && ts.getAreDeclarationMapsEnabled(options) ? declarationFilePath + ".map" : undefined;
94317             return { jsFilePath: jsFilePath, sourceMapFilePath: sourceMapFilePath, declarationFilePath: declarationFilePath, declarationMapPath: declarationMapPath, buildInfoPath: undefined };
94318         }
94319     }
94320     ts.getOutputPathsFor = getOutputPathsFor;
94321     function getSourceMapFilePath(jsFilePath, options) {
94322         return (options.sourceMap && !options.inlineSourceMap) ? jsFilePath + ".map" : undefined;
94323     }
94324     // JavaScript files are always LanguageVariant.JSX, as JSX syntax is allowed in .js files also.
94325     // So for JavaScript files, '.jsx' is only emitted if the input was '.jsx', and JsxEmit.Preserve.
94326     // For TypeScript, the only time to emit with a '.jsx' extension, is on JSX input, and JsxEmit.Preserve
94327     /* @internal */
94328     function getOutputExtension(sourceFile, options) {
94329         if (ts.isJsonSourceFile(sourceFile)) {
94330             return ".json" /* Json */;
94331         }
94332         if (options.jsx === 1 /* Preserve */) {
94333             if (ts.isSourceFileJS(sourceFile)) {
94334                 if (ts.fileExtensionIs(sourceFile.fileName, ".jsx" /* Jsx */)) {
94335                     return ".jsx" /* Jsx */;
94336                 }
94337             }
94338             else if (sourceFile.languageVariant === 1 /* JSX */) {
94339                 // TypeScript source file preserving JSX syntax
94340                 return ".jsx" /* Jsx */;
94341             }
94342         }
94343         return ".js" /* Js */;
94344     }
94345     ts.getOutputExtension = getOutputExtension;
94346     function rootDirOfOptions(configFile) {
94347         return configFile.options.rootDir || ts.getDirectoryPath(ts.Debug.checkDefined(configFile.options.configFilePath));
94348     }
94349     function getOutputPathWithoutChangingExt(inputFileName, configFile, ignoreCase, outputDir) {
94350         return outputDir ?
94351             ts.resolvePath(outputDir, ts.getRelativePathFromDirectory(rootDirOfOptions(configFile), inputFileName, ignoreCase)) :
94352             inputFileName;
94353     }
94354     /* @internal */
94355     function getOutputDeclarationFileName(inputFileName, configFile, ignoreCase) {
94356         ts.Debug.assert(!ts.fileExtensionIs(inputFileName, ".d.ts" /* Dts */) && !ts.fileExtensionIs(inputFileName, ".json" /* Json */));
94357         return ts.changeExtension(getOutputPathWithoutChangingExt(inputFileName, configFile, ignoreCase, configFile.options.declarationDir || configFile.options.outDir), ".d.ts" /* Dts */);
94358     }
94359     ts.getOutputDeclarationFileName = getOutputDeclarationFileName;
94360     function getOutputJSFileName(inputFileName, configFile, ignoreCase) {
94361         if (configFile.options.emitDeclarationOnly)
94362             return undefined;
94363         var isJsonFile = ts.fileExtensionIs(inputFileName, ".json" /* Json */);
94364         var outputFileName = ts.changeExtension(getOutputPathWithoutChangingExt(inputFileName, configFile, ignoreCase, configFile.options.outDir), isJsonFile ?
94365             ".json" /* Json */ :
94366             ts.fileExtensionIs(inputFileName, ".tsx" /* Tsx */) && configFile.options.jsx === 1 /* Preserve */ ?
94367                 ".jsx" /* Jsx */ :
94368                 ".js" /* Js */);
94369         return !isJsonFile || ts.comparePaths(inputFileName, outputFileName, ts.Debug.checkDefined(configFile.options.configFilePath), ignoreCase) !== 0 /* EqualTo */ ?
94370             outputFileName :
94371             undefined;
94372     }
94373     function createAddOutput() {
94374         var outputs;
94375         return { addOutput: addOutput, getOutputs: getOutputs };
94376         function addOutput(path) {
94377             if (path) {
94378                 (outputs || (outputs = [])).push(path);
94379             }
94380         }
94381         function getOutputs() {
94382             return outputs || ts.emptyArray;
94383         }
94384     }
94385     function getSingleOutputFileNames(configFile, addOutput) {
94386         var _a = getOutputPathsForBundle(configFile.options, /*forceDtsPaths*/ false), jsFilePath = _a.jsFilePath, sourceMapFilePath = _a.sourceMapFilePath, declarationFilePath = _a.declarationFilePath, declarationMapPath = _a.declarationMapPath, buildInfoPath = _a.buildInfoPath;
94387         addOutput(jsFilePath);
94388         addOutput(sourceMapFilePath);
94389         addOutput(declarationFilePath);
94390         addOutput(declarationMapPath);
94391         addOutput(buildInfoPath);
94392     }
94393     function getOwnOutputFileNames(configFile, inputFileName, ignoreCase, addOutput) {
94394         if (ts.fileExtensionIs(inputFileName, ".d.ts" /* Dts */))
94395             return;
94396         var js = getOutputJSFileName(inputFileName, configFile, ignoreCase);
94397         addOutput(js);
94398         if (ts.fileExtensionIs(inputFileName, ".json" /* Json */))
94399             return;
94400         if (js && configFile.options.sourceMap) {
94401             addOutput(js + ".map");
94402         }
94403         if (ts.getEmitDeclarations(configFile.options)) {
94404             var dts = getOutputDeclarationFileName(inputFileName, configFile, ignoreCase);
94405             addOutput(dts);
94406             if (configFile.options.declarationMap) {
94407                 addOutput(dts + ".map");
94408             }
94409         }
94410     }
94411     /*@internal*/
94412     function getAllProjectOutputs(configFile, ignoreCase) {
94413         var _a = createAddOutput(), addOutput = _a.addOutput, getOutputs = _a.getOutputs;
94414         if (configFile.options.outFile || configFile.options.out) {
94415             getSingleOutputFileNames(configFile, addOutput);
94416         }
94417         else {
94418             for (var _b = 0, _c = configFile.fileNames; _b < _c.length; _b++) {
94419                 var inputFileName = _c[_b];
94420                 getOwnOutputFileNames(configFile, inputFileName, ignoreCase, addOutput);
94421             }
94422             addOutput(getTsBuildInfoEmitOutputFilePath(configFile.options));
94423         }
94424         return getOutputs();
94425     }
94426     ts.getAllProjectOutputs = getAllProjectOutputs;
94427     function getOutputFileNames(commandLine, inputFileName, ignoreCase) {
94428         inputFileName = ts.normalizePath(inputFileName);
94429         ts.Debug.assert(ts.contains(commandLine.fileNames, inputFileName), "Expected fileName to be present in command line");
94430         var _a = createAddOutput(), addOutput = _a.addOutput, getOutputs = _a.getOutputs;
94431         if (commandLine.options.outFile || commandLine.options.out) {
94432             getSingleOutputFileNames(commandLine, addOutput);
94433         }
94434         else {
94435             getOwnOutputFileNames(commandLine, inputFileName, ignoreCase, addOutput);
94436         }
94437         return getOutputs();
94438     }
94439     ts.getOutputFileNames = getOutputFileNames;
94440     /*@internal*/
94441     function getFirstProjectOutput(configFile, ignoreCase) {
94442         if (configFile.options.outFile || configFile.options.out) {
94443             var jsFilePath = getOutputPathsForBundle(configFile.options, /*forceDtsPaths*/ false).jsFilePath;
94444             return ts.Debug.checkDefined(jsFilePath, "project " + configFile.options.configFilePath + " expected to have at least one output");
94445         }
94446         for (var _a = 0, _b = configFile.fileNames; _a < _b.length; _a++) {
94447             var inputFileName = _b[_a];
94448             if (ts.fileExtensionIs(inputFileName, ".d.ts" /* Dts */))
94449                 continue;
94450             var jsFilePath = getOutputJSFileName(inputFileName, configFile, ignoreCase);
94451             if (jsFilePath)
94452                 return jsFilePath;
94453             if (ts.fileExtensionIs(inputFileName, ".json" /* Json */))
94454                 continue;
94455             if (ts.getEmitDeclarations(configFile.options)) {
94456                 return getOutputDeclarationFileName(inputFileName, configFile, ignoreCase);
94457             }
94458         }
94459         var buildInfoPath = getTsBuildInfoEmitOutputFilePath(configFile.options);
94460         if (buildInfoPath)
94461             return buildInfoPath;
94462         return ts.Debug.fail("project " + configFile.options.configFilePath + " expected to have at least one output");
94463     }
94464     ts.getFirstProjectOutput = getFirstProjectOutput;
94465     /*@internal*/
94466     // targetSourceFile is when users only want one file in entire project to be emitted. This is used in compileOnSave feature
94467     function emitFiles(resolver, host, targetSourceFile, _a, emitOnlyDtsFiles, onlyBuildInfo, forceDtsEmit) {
94468         var scriptTransformers = _a.scriptTransformers, declarationTransformers = _a.declarationTransformers;
94469         var compilerOptions = host.getCompilerOptions();
94470         var sourceMapDataList = (compilerOptions.sourceMap || compilerOptions.inlineSourceMap || ts.getAreDeclarationMapsEnabled(compilerOptions)) ? [] : undefined;
94471         var emittedFilesList = compilerOptions.listEmittedFiles ? [] : undefined;
94472         var emitterDiagnostics = ts.createDiagnosticCollection();
94473         var newLine = ts.getNewLineCharacter(compilerOptions, function () { return host.getNewLine(); });
94474         var writer = ts.createTextWriter(newLine);
94475         var _b = ts.performance.createTimer("printTime", "beforePrint", "afterPrint"), enter = _b.enter, exit = _b.exit;
94476         var bundleBuildInfo;
94477         var emitSkipped = false;
94478         var exportedModulesFromDeclarationEmit;
94479         // Emit each output file
94480         enter();
94481         forEachEmittedFile(host, emitSourceFileOrBundle, ts.getSourceFilesToEmit(host, targetSourceFile, forceDtsEmit), forceDtsEmit, onlyBuildInfo, !targetSourceFile);
94482         exit();
94483         return {
94484             emitSkipped: emitSkipped,
94485             diagnostics: emitterDiagnostics.getDiagnostics(),
94486             emittedFiles: emittedFilesList,
94487             sourceMaps: sourceMapDataList,
94488             exportedModulesFromDeclarationEmit: exportedModulesFromDeclarationEmit
94489         };
94490         function emitSourceFileOrBundle(_a, sourceFileOrBundle) {
94491             var jsFilePath = _a.jsFilePath, sourceMapFilePath = _a.sourceMapFilePath, declarationFilePath = _a.declarationFilePath, declarationMapPath = _a.declarationMapPath, buildInfoPath = _a.buildInfoPath;
94492             var buildInfoDirectory;
94493             if (buildInfoPath && sourceFileOrBundle && ts.isBundle(sourceFileOrBundle)) {
94494                 buildInfoDirectory = ts.getDirectoryPath(ts.getNormalizedAbsolutePath(buildInfoPath, host.getCurrentDirectory()));
94495                 bundleBuildInfo = {
94496                     commonSourceDirectory: relativeToBuildInfo(host.getCommonSourceDirectory()),
94497                     sourceFiles: sourceFileOrBundle.sourceFiles.map(function (file) { return relativeToBuildInfo(ts.getNormalizedAbsolutePath(file.fileName, host.getCurrentDirectory())); })
94498                 };
94499             }
94500             emitJsFileOrBundle(sourceFileOrBundle, jsFilePath, sourceMapFilePath, relativeToBuildInfo);
94501             emitDeclarationFileOrBundle(sourceFileOrBundle, declarationFilePath, declarationMapPath, relativeToBuildInfo);
94502             emitBuildInfo(bundleBuildInfo, buildInfoPath);
94503             if (!emitSkipped && emittedFilesList) {
94504                 if (!emitOnlyDtsFiles) {
94505                     if (jsFilePath) {
94506                         emittedFilesList.push(jsFilePath);
94507                     }
94508                     if (sourceMapFilePath) {
94509                         emittedFilesList.push(sourceMapFilePath);
94510                     }
94511                     if (buildInfoPath) {
94512                         emittedFilesList.push(buildInfoPath);
94513                     }
94514                 }
94515                 if (declarationFilePath) {
94516                     emittedFilesList.push(declarationFilePath);
94517                 }
94518                 if (declarationMapPath) {
94519                     emittedFilesList.push(declarationMapPath);
94520                 }
94521             }
94522             function relativeToBuildInfo(path) {
94523                 return ts.ensurePathIsNonModuleName(ts.getRelativePathFromDirectory(buildInfoDirectory, path, host.getCanonicalFileName));
94524             }
94525         }
94526         function emitBuildInfo(bundle, buildInfoPath) {
94527             // Write build information if applicable
94528             if (!buildInfoPath || targetSourceFile || emitSkipped)
94529                 return;
94530             var program = host.getProgramBuildInfo();
94531             if (host.isEmitBlocked(buildInfoPath) || compilerOptions.noEmit) {
94532                 emitSkipped = true;
94533                 return;
94534             }
94535             var version = ts.version; // Extracted into a const so the form is stable between namespace and module
94536             ts.writeFile(host, emitterDiagnostics, buildInfoPath, getBuildInfoText({ bundle: bundle, program: program, version: version }), /*writeByteOrderMark*/ false);
94537         }
94538         function emitJsFileOrBundle(sourceFileOrBundle, jsFilePath, sourceMapFilePath, relativeToBuildInfo) {
94539             if (!sourceFileOrBundle || emitOnlyDtsFiles || !jsFilePath) {
94540                 return;
94541             }
94542             // Make sure not to write js file and source map file if any of them cannot be written
94543             if ((jsFilePath && host.isEmitBlocked(jsFilePath)) || compilerOptions.noEmit) {
94544                 emitSkipped = true;
94545                 return;
94546             }
94547             // Transform the source files
94548             var transform = ts.transformNodes(resolver, host, compilerOptions, [sourceFileOrBundle], scriptTransformers, /*allowDtsFiles*/ false);
94549             var printerOptions = {
94550                 removeComments: compilerOptions.removeComments,
94551                 newLine: compilerOptions.newLine,
94552                 noEmitHelpers: compilerOptions.noEmitHelpers,
94553                 module: compilerOptions.module,
94554                 target: compilerOptions.target,
94555                 sourceMap: compilerOptions.sourceMap,
94556                 inlineSourceMap: compilerOptions.inlineSourceMap,
94557                 inlineSources: compilerOptions.inlineSources,
94558                 extendedDiagnostics: compilerOptions.extendedDiagnostics,
94559                 writeBundleFileInfo: !!bundleBuildInfo,
94560                 relativeToBuildInfo: relativeToBuildInfo
94561             };
94562             // Create a printer to print the nodes
94563             var printer = createPrinter(printerOptions, {
94564                 // resolver hooks
94565                 hasGlobalName: resolver.hasGlobalName,
94566                 // transform hooks
94567                 onEmitNode: transform.emitNodeWithNotification,
94568                 isEmitNotificationEnabled: transform.isEmitNotificationEnabled,
94569                 substituteNode: transform.substituteNode,
94570             });
94571             ts.Debug.assert(transform.transformed.length === 1, "Should only see one output from the transform");
94572             printSourceFileOrBundle(jsFilePath, sourceMapFilePath, transform.transformed[0], printer, compilerOptions);
94573             // Clean up emit nodes on parse tree
94574             transform.dispose();
94575             if (bundleBuildInfo)
94576                 bundleBuildInfo.js = printer.bundleFileInfo;
94577         }
94578         function emitDeclarationFileOrBundle(sourceFileOrBundle, declarationFilePath, declarationMapPath, relativeToBuildInfo) {
94579             if (!sourceFileOrBundle)
94580                 return;
94581             if (!declarationFilePath) {
94582                 if (emitOnlyDtsFiles || compilerOptions.emitDeclarationOnly)
94583                     emitSkipped = true;
94584                 return;
94585             }
94586             var sourceFiles = ts.isSourceFile(sourceFileOrBundle) ? [sourceFileOrBundle] : sourceFileOrBundle.sourceFiles;
94587             var filesForEmit = forceDtsEmit ? sourceFiles : ts.filter(sourceFiles, ts.isSourceFileNotJson);
94588             // Setup and perform the transformation to retrieve declarations from the input files
94589             var inputListOrBundle = (compilerOptions.outFile || compilerOptions.out) ? [ts.createBundle(filesForEmit, !ts.isSourceFile(sourceFileOrBundle) ? sourceFileOrBundle.prepends : undefined)] : filesForEmit;
94590             if (emitOnlyDtsFiles && !ts.getEmitDeclarations(compilerOptions)) {
94591                 // Checker wont collect the linked aliases since thats only done when declaration is enabled.
94592                 // Do that here when emitting only dts files
94593                 filesForEmit.forEach(collectLinkedAliases);
94594             }
94595             var declarationTransform = ts.transformNodes(resolver, host, compilerOptions, inputListOrBundle, declarationTransformers, /*allowDtsFiles*/ false);
94596             if (ts.length(declarationTransform.diagnostics)) {
94597                 for (var _a = 0, _b = declarationTransform.diagnostics; _a < _b.length; _a++) {
94598                     var diagnostic = _b[_a];
94599                     emitterDiagnostics.add(diagnostic);
94600                 }
94601             }
94602             var printerOptions = {
94603                 removeComments: compilerOptions.removeComments,
94604                 newLine: compilerOptions.newLine,
94605                 noEmitHelpers: true,
94606                 module: compilerOptions.module,
94607                 target: compilerOptions.target,
94608                 sourceMap: compilerOptions.sourceMap,
94609                 inlineSourceMap: compilerOptions.inlineSourceMap,
94610                 extendedDiagnostics: compilerOptions.extendedDiagnostics,
94611                 onlyPrintJsDocStyle: true,
94612                 writeBundleFileInfo: !!bundleBuildInfo,
94613                 recordInternalSection: !!bundleBuildInfo,
94614                 relativeToBuildInfo: relativeToBuildInfo
94615             };
94616             var declarationPrinter = createPrinter(printerOptions, {
94617                 // resolver hooks
94618                 hasGlobalName: resolver.hasGlobalName,
94619                 // transform hooks
94620                 onEmitNode: declarationTransform.emitNodeWithNotification,
94621                 isEmitNotificationEnabled: declarationTransform.isEmitNotificationEnabled,
94622                 substituteNode: declarationTransform.substituteNode,
94623             });
94624             var declBlocked = (!!declarationTransform.diagnostics && !!declarationTransform.diagnostics.length) || !!host.isEmitBlocked(declarationFilePath) || !!compilerOptions.noEmit;
94625             emitSkipped = emitSkipped || declBlocked;
94626             if (!declBlocked || forceDtsEmit) {
94627                 ts.Debug.assert(declarationTransform.transformed.length === 1, "Should only see one output from the decl transform");
94628                 printSourceFileOrBundle(declarationFilePath, declarationMapPath, declarationTransform.transformed[0], declarationPrinter, {
94629                     sourceMap: compilerOptions.declarationMap,
94630                     sourceRoot: compilerOptions.sourceRoot,
94631                     mapRoot: compilerOptions.mapRoot,
94632                     extendedDiagnostics: compilerOptions.extendedDiagnostics,
94633                 });
94634                 if (forceDtsEmit && declarationTransform.transformed[0].kind === 290 /* SourceFile */) {
94635                     var sourceFile = declarationTransform.transformed[0];
94636                     exportedModulesFromDeclarationEmit = sourceFile.exportedModulesFromDeclarationEmit;
94637                 }
94638             }
94639             declarationTransform.dispose();
94640             if (bundleBuildInfo)
94641                 bundleBuildInfo.dts = declarationPrinter.bundleFileInfo;
94642         }
94643         function collectLinkedAliases(node) {
94644             if (ts.isExportAssignment(node)) {
94645                 if (node.expression.kind === 75 /* Identifier */) {
94646                     resolver.collectLinkedAliases(node.expression, /*setVisibility*/ true);
94647                 }
94648                 return;
94649             }
94650             else if (ts.isExportSpecifier(node)) {
94651                 resolver.collectLinkedAliases(node.propertyName || node.name, /*setVisibility*/ true);
94652                 return;
94653             }
94654             ts.forEachChild(node, collectLinkedAliases);
94655         }
94656         function printSourceFileOrBundle(jsFilePath, sourceMapFilePath, sourceFileOrBundle, printer, mapOptions) {
94657             var bundle = sourceFileOrBundle.kind === 291 /* Bundle */ ? sourceFileOrBundle : undefined;
94658             var sourceFile = sourceFileOrBundle.kind === 290 /* SourceFile */ ? sourceFileOrBundle : undefined;
94659             var sourceFiles = bundle ? bundle.sourceFiles : [sourceFile];
94660             var sourceMapGenerator;
94661             if (shouldEmitSourceMaps(mapOptions, sourceFileOrBundle)) {
94662                 sourceMapGenerator = ts.createSourceMapGenerator(host, ts.getBaseFileName(ts.normalizeSlashes(jsFilePath)), getSourceRoot(mapOptions), getSourceMapDirectory(mapOptions, jsFilePath, sourceFile), mapOptions);
94663             }
94664             if (bundle) {
94665                 printer.writeBundle(bundle, writer, sourceMapGenerator);
94666             }
94667             else {
94668                 printer.writeFile(sourceFile, writer, sourceMapGenerator);
94669             }
94670             if (sourceMapGenerator) {
94671                 if (sourceMapDataList) {
94672                     sourceMapDataList.push({
94673                         inputSourceFileNames: sourceMapGenerator.getSources(),
94674                         sourceMap: sourceMapGenerator.toJSON()
94675                     });
94676                 }
94677                 var sourceMappingURL = getSourceMappingURL(mapOptions, sourceMapGenerator, jsFilePath, sourceMapFilePath, sourceFile);
94678                 if (sourceMappingURL) {
94679                     if (!writer.isAtStartOfLine())
94680                         writer.rawWrite(newLine);
94681                     writer.writeComment("//# " + "sourceMappingURL" + "=" + sourceMappingURL); // Tools can sometimes see this line as a source mapping url comment
94682                 }
94683                 // Write the source map
94684                 if (sourceMapFilePath) {
94685                     var sourceMap = sourceMapGenerator.toString();
94686                     ts.writeFile(host, emitterDiagnostics, sourceMapFilePath, sourceMap, /*writeByteOrderMark*/ false, sourceFiles);
94687                 }
94688             }
94689             else {
94690                 writer.writeLine();
94691             }
94692             // Write the output file
94693             ts.writeFile(host, emitterDiagnostics, jsFilePath, writer.getText(), !!compilerOptions.emitBOM, sourceFiles);
94694             // Reset state
94695             writer.clear();
94696         }
94697         function shouldEmitSourceMaps(mapOptions, sourceFileOrBundle) {
94698             return (mapOptions.sourceMap || mapOptions.inlineSourceMap)
94699                 && (sourceFileOrBundle.kind !== 290 /* SourceFile */ || !ts.fileExtensionIs(sourceFileOrBundle.fileName, ".json" /* Json */));
94700         }
94701         function getSourceRoot(mapOptions) {
94702             // Normalize source root and make sure it has trailing "/" so that it can be used to combine paths with the
94703             // relative paths of the sources list in the sourcemap
94704             var sourceRoot = ts.normalizeSlashes(mapOptions.sourceRoot || "");
94705             return sourceRoot ? ts.ensureTrailingDirectorySeparator(sourceRoot) : sourceRoot;
94706         }
94707         function getSourceMapDirectory(mapOptions, filePath, sourceFile) {
94708             if (mapOptions.sourceRoot)
94709                 return host.getCommonSourceDirectory();
94710             if (mapOptions.mapRoot) {
94711                 var sourceMapDir = ts.normalizeSlashes(mapOptions.mapRoot);
94712                 if (sourceFile) {
94713                     // For modules or multiple emit files the mapRoot will have directory structure like the sources
94714                     // 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
94715                     sourceMapDir = ts.getDirectoryPath(ts.getSourceFilePathInNewDir(sourceFile.fileName, host, sourceMapDir));
94716                 }
94717                 if (ts.getRootLength(sourceMapDir) === 0) {
94718                     // The relative paths are relative to the common directory
94719                     sourceMapDir = ts.combinePaths(host.getCommonSourceDirectory(), sourceMapDir);
94720                 }
94721                 return sourceMapDir;
94722             }
94723             return ts.getDirectoryPath(ts.normalizePath(filePath));
94724         }
94725         function getSourceMappingURL(mapOptions, sourceMapGenerator, filePath, sourceMapFilePath, sourceFile) {
94726             if (mapOptions.inlineSourceMap) {
94727                 // Encode the sourceMap into the sourceMap url
94728                 var sourceMapText = sourceMapGenerator.toString();
94729                 var base64SourceMapText = ts.base64encode(ts.sys, sourceMapText);
94730                 return "data:application/json;base64," + base64SourceMapText;
94731             }
94732             var sourceMapFile = ts.getBaseFileName(ts.normalizeSlashes(ts.Debug.checkDefined(sourceMapFilePath)));
94733             if (mapOptions.mapRoot) {
94734                 var sourceMapDir = ts.normalizeSlashes(mapOptions.mapRoot);
94735                 if (sourceFile) {
94736                     // For modules or multiple emit files the mapRoot will have directory structure like the sources
94737                     // 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
94738                     sourceMapDir = ts.getDirectoryPath(ts.getSourceFilePathInNewDir(sourceFile.fileName, host, sourceMapDir));
94739                 }
94740                 if (ts.getRootLength(sourceMapDir) === 0) {
94741                     // The relative paths are relative to the common directory
94742                     sourceMapDir = ts.combinePaths(host.getCommonSourceDirectory(), sourceMapDir);
94743                     return ts.getRelativePathToDirectoryOrUrl(ts.getDirectoryPath(ts.normalizePath(filePath)), // get the relative sourceMapDir path based on jsFilePath
94744                     ts.combinePaths(sourceMapDir, sourceMapFile), // this is where user expects to see sourceMap
94745                     host.getCurrentDirectory(), host.getCanonicalFileName, 
94746                     /*isAbsolutePathAnUrl*/ true);
94747                 }
94748                 else {
94749                     return ts.combinePaths(sourceMapDir, sourceMapFile);
94750                 }
94751             }
94752             return sourceMapFile;
94753         }
94754     }
94755     ts.emitFiles = emitFiles;
94756     /*@internal*/
94757     function getBuildInfoText(buildInfo) {
94758         return JSON.stringify(buildInfo, undefined, 2);
94759     }
94760     ts.getBuildInfoText = getBuildInfoText;
94761     /*@internal*/
94762     function getBuildInfo(buildInfoText) {
94763         return JSON.parse(buildInfoText);
94764     }
94765     ts.getBuildInfo = getBuildInfo;
94766     /*@internal*/
94767     ts.notImplementedResolver = {
94768         hasGlobalName: ts.notImplemented,
94769         getReferencedExportContainer: ts.notImplemented,
94770         getReferencedImportDeclaration: ts.notImplemented,
94771         getReferencedDeclarationWithCollidingName: ts.notImplemented,
94772         isDeclarationWithCollidingName: ts.notImplemented,
94773         isValueAliasDeclaration: ts.notImplemented,
94774         isReferencedAliasDeclaration: ts.notImplemented,
94775         isTopLevelValueImportEqualsWithEntityName: ts.notImplemented,
94776         getNodeCheckFlags: ts.notImplemented,
94777         isDeclarationVisible: ts.notImplemented,
94778         isLateBound: function (_node) { return false; },
94779         collectLinkedAliases: ts.notImplemented,
94780         isImplementationOfOverload: ts.notImplemented,
94781         isRequiredInitializedParameter: ts.notImplemented,
94782         isOptionalUninitializedParameterProperty: ts.notImplemented,
94783         isExpandoFunctionDeclaration: ts.notImplemented,
94784         getPropertiesOfContainerFunction: ts.notImplemented,
94785         createTypeOfDeclaration: ts.notImplemented,
94786         createReturnTypeOfSignatureDeclaration: ts.notImplemented,
94787         createTypeOfExpression: ts.notImplemented,
94788         createLiteralConstValue: ts.notImplemented,
94789         isSymbolAccessible: ts.notImplemented,
94790         isEntityNameVisible: ts.notImplemented,
94791         // Returns the constant value this property access resolves to: notImplemented, or 'undefined' for a non-constant
94792         getConstantValue: ts.notImplemented,
94793         getReferencedValueDeclaration: ts.notImplemented,
94794         getTypeReferenceSerializationKind: ts.notImplemented,
94795         isOptionalParameter: ts.notImplemented,
94796         moduleExportsSomeValue: ts.notImplemented,
94797         isArgumentsLocalBinding: ts.notImplemented,
94798         getExternalModuleFileFromDeclaration: ts.notImplemented,
94799         getTypeReferenceDirectivesForEntityName: ts.notImplemented,
94800         getTypeReferenceDirectivesForSymbol: ts.notImplemented,
94801         isLiteralConstDeclaration: ts.notImplemented,
94802         getJsxFactoryEntity: ts.notImplemented,
94803         getAllAccessorDeclarations: ts.notImplemented,
94804         getSymbolOfExternalModuleSpecifier: ts.notImplemented,
94805         isBindingCapturedByNode: ts.notImplemented,
94806         getDeclarationStatementsForSourceFile: ts.notImplemented,
94807         isImportRequiredByAugmentation: ts.notImplemented,
94808     };
94809     function createSourceFilesFromBundleBuildInfo(bundle, buildInfoDirectory, host) {
94810         var sourceFiles = bundle.sourceFiles.map(function (fileName) {
94811             var sourceFile = ts.createNode(290 /* SourceFile */, 0, 0);
94812             sourceFile.fileName = ts.getRelativePathFromDirectory(host.getCurrentDirectory(), ts.getNormalizedAbsolutePath(fileName, buildInfoDirectory), !host.useCaseSensitiveFileNames());
94813             sourceFile.text = "";
94814             sourceFile.statements = ts.createNodeArray();
94815             return sourceFile;
94816         });
94817         var jsBundle = ts.Debug.checkDefined(bundle.js);
94818         ts.forEach(jsBundle.sources && jsBundle.sources.prologues, function (prologueInfo) {
94819             var sourceFile = sourceFiles[prologueInfo.file];
94820             sourceFile.text = prologueInfo.text;
94821             sourceFile.end = prologueInfo.text.length;
94822             sourceFile.statements = ts.createNodeArray(prologueInfo.directives.map(function (directive) {
94823                 var statement = ts.createNode(226 /* ExpressionStatement */, directive.pos, directive.end);
94824                 statement.expression = ts.createNode(10 /* StringLiteral */, directive.expression.pos, directive.expression.end);
94825                 statement.expression.text = directive.expression.text;
94826                 return statement;
94827             }));
94828         });
94829         return sourceFiles;
94830     }
94831     /*@internal*/
94832     function emitUsingBuildInfo(config, host, getCommandLine, customTransformers) {
94833         var _a = getOutputPathsForBundle(config.options, /*forceDtsPaths*/ false), buildInfoPath = _a.buildInfoPath, jsFilePath = _a.jsFilePath, sourceMapFilePath = _a.sourceMapFilePath, declarationFilePath = _a.declarationFilePath, declarationMapPath = _a.declarationMapPath;
94834         var buildInfoText = host.readFile(ts.Debug.checkDefined(buildInfoPath));
94835         if (!buildInfoText)
94836             return buildInfoPath;
94837         var jsFileText = host.readFile(ts.Debug.checkDefined(jsFilePath));
94838         if (!jsFileText)
94839             return jsFilePath;
94840         var sourceMapText = sourceMapFilePath && host.readFile(sourceMapFilePath);
94841         // error if no source map or for now if inline sourcemap
94842         if ((sourceMapFilePath && !sourceMapText) || config.options.inlineSourceMap)
94843             return sourceMapFilePath || "inline sourcemap decoding";
94844         // read declaration text
94845         var declarationText = declarationFilePath && host.readFile(declarationFilePath);
94846         if (declarationFilePath && !declarationText)
94847             return declarationFilePath;
94848         var declarationMapText = declarationMapPath && host.readFile(declarationMapPath);
94849         // error if no source map or for now if inline sourcemap
94850         if ((declarationMapPath && !declarationMapText) || config.options.inlineSourceMap)
94851             return declarationMapPath || "inline sourcemap decoding";
94852         var buildInfo = getBuildInfo(buildInfoText);
94853         if (!buildInfo.bundle || !buildInfo.bundle.js || (declarationText && !buildInfo.bundle.dts))
94854             return buildInfoPath;
94855         var buildInfoDirectory = ts.getDirectoryPath(ts.getNormalizedAbsolutePath(buildInfoPath, host.getCurrentDirectory()));
94856         var ownPrependInput = ts.createInputFiles(jsFileText, declarationText, sourceMapFilePath, sourceMapText, declarationMapPath, declarationMapText, jsFilePath, declarationFilePath, buildInfoPath, buildInfo, 
94857         /*onlyOwnText*/ true);
94858         var outputFiles = [];
94859         var prependNodes = ts.createPrependNodes(config.projectReferences, getCommandLine, function (f) { return host.readFile(f); });
94860         var sourceFilesForJsEmit = createSourceFilesFromBundleBuildInfo(buildInfo.bundle, buildInfoDirectory, host);
94861         var emitHost = {
94862             getPrependNodes: ts.memoize(function () { return __spreadArrays(prependNodes, [ownPrependInput]); }),
94863             getCanonicalFileName: host.getCanonicalFileName,
94864             getCommonSourceDirectory: function () { return ts.getNormalizedAbsolutePath(buildInfo.bundle.commonSourceDirectory, buildInfoDirectory); },
94865             getCompilerOptions: function () { return config.options; },
94866             getCurrentDirectory: function () { return host.getCurrentDirectory(); },
94867             getNewLine: function () { return host.getNewLine(); },
94868             getSourceFile: ts.returnUndefined,
94869             getSourceFileByPath: ts.returnUndefined,
94870             getSourceFiles: function () { return sourceFilesForJsEmit; },
94871             getLibFileFromReference: ts.notImplemented,
94872             isSourceFileFromExternalLibrary: ts.returnFalse,
94873             getResolvedProjectReferenceToRedirect: ts.returnUndefined,
94874             getProjectReferenceRedirect: ts.returnUndefined,
94875             isSourceOfProjectReferenceRedirect: ts.returnFalse,
94876             writeFile: function (name, text, writeByteOrderMark) {
94877                 switch (name) {
94878                     case jsFilePath:
94879                         if (jsFileText === text)
94880                             return;
94881                         break;
94882                     case sourceMapFilePath:
94883                         if (sourceMapText === text)
94884                             return;
94885                         break;
94886                     case buildInfoPath:
94887                         var newBuildInfo = getBuildInfo(text);
94888                         newBuildInfo.program = buildInfo.program;
94889                         // Update sourceFileInfo
94890                         var _a = buildInfo.bundle, js = _a.js, dts = _a.dts, sourceFiles = _a.sourceFiles;
94891                         newBuildInfo.bundle.js.sources = js.sources;
94892                         if (dts) {
94893                             newBuildInfo.bundle.dts.sources = dts.sources;
94894                         }
94895                         newBuildInfo.bundle.sourceFiles = sourceFiles;
94896                         outputFiles.push({ name: name, text: getBuildInfoText(newBuildInfo), writeByteOrderMark: writeByteOrderMark });
94897                         return;
94898                     case declarationFilePath:
94899                         if (declarationText === text)
94900                             return;
94901                         break;
94902                     case declarationMapPath:
94903                         if (declarationMapText === text)
94904                             return;
94905                         break;
94906                     default:
94907                         ts.Debug.fail("Unexpected path: " + name);
94908                 }
94909                 outputFiles.push({ name: name, text: text, writeByteOrderMark: writeByteOrderMark });
94910             },
94911             isEmitBlocked: ts.returnFalse,
94912             readFile: function (f) { return host.readFile(f); },
94913             fileExists: function (f) { return host.fileExists(f); },
94914             useCaseSensitiveFileNames: function () { return host.useCaseSensitiveFileNames(); },
94915             getProgramBuildInfo: ts.returnUndefined,
94916             getSourceFileFromReference: ts.returnUndefined,
94917             redirectTargetsMap: ts.createMultiMap()
94918         };
94919         emitFiles(ts.notImplementedResolver, emitHost, 
94920         /*targetSourceFile*/ undefined, ts.getTransformers(config.options, customTransformers));
94921         return outputFiles;
94922     }
94923     ts.emitUsingBuildInfo = emitUsingBuildInfo;
94924     var PipelinePhase;
94925     (function (PipelinePhase) {
94926         PipelinePhase[PipelinePhase["Notification"] = 0] = "Notification";
94927         PipelinePhase[PipelinePhase["Substitution"] = 1] = "Substitution";
94928         PipelinePhase[PipelinePhase["Comments"] = 2] = "Comments";
94929         PipelinePhase[PipelinePhase["SourceMaps"] = 3] = "SourceMaps";
94930         PipelinePhase[PipelinePhase["Emit"] = 4] = "Emit";
94931     })(PipelinePhase || (PipelinePhase = {}));
94932     function createPrinter(printerOptions, handlers) {
94933         if (printerOptions === void 0) { printerOptions = {}; }
94934         if (handlers === void 0) { handlers = {}; }
94935         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;
94936         var extendedDiagnostics = !!printerOptions.extendedDiagnostics;
94937         var newLine = ts.getNewLineCharacter(printerOptions);
94938         var moduleKind = ts.getEmitModuleKind(printerOptions);
94939         var bundledHelpers = ts.createMap();
94940         var currentSourceFile;
94941         var nodeIdToGeneratedName; // Map of generated names for specific nodes.
94942         var autoGeneratedIdToGeneratedName; // Map of generated names for temp and loop variables.
94943         var generatedNames; // Set of names generated by the NameGenerator.
94944         var tempFlagsStack; // Stack of enclosing name generation scopes.
94945         var tempFlags; // TempFlags for the current name generation scope.
94946         var reservedNamesStack; // Stack of TempFlags reserved in enclosing name generation scopes.
94947         var reservedNames; // TempFlags to reserve in nested name generation scopes.
94948         var preserveSourceNewlines = printerOptions.preserveSourceNewlines; // Can be overridden inside nodes with the `IgnoreSourceNewlines` emit flag.
94949         var writer;
94950         var ownWriter; // Reusable `EmitTextWriter` for basic printing.
94951         var write = writeBase;
94952         var isOwnFileEmit;
94953         var bundleFileInfo = printerOptions.writeBundleFileInfo ? { sections: [] } : undefined;
94954         var relativeToBuildInfo = bundleFileInfo ? ts.Debug.checkDefined(printerOptions.relativeToBuildInfo) : undefined;
94955         var recordInternalSection = printerOptions.recordInternalSection;
94956         var sourceFileTextPos = 0;
94957         var sourceFileTextKind = "text" /* Text */;
94958         // Source Maps
94959         var sourceMapsDisabled = true;
94960         var sourceMapGenerator;
94961         var sourceMapSource;
94962         var sourceMapSourceIndex = -1;
94963         // Comments
94964         var containerPos = -1;
94965         var containerEnd = -1;
94966         var declarationListContainerEnd = -1;
94967         var currentLineMap;
94968         var detachedCommentsInfo;
94969         var hasWrittenComment = false;
94970         var commentsDisabled = !!printerOptions.removeComments;
94971         var lastNode;
94972         var lastSubstitution;
94973         var _c = ts.performance.createTimerIf(extendedDiagnostics, "commentTime", "beforeComment", "afterComment"), enterComment = _c.enter, exitComment = _c.exit;
94974         reset();
94975         return {
94976             // public API
94977             printNode: printNode,
94978             printList: printList,
94979             printFile: printFile,
94980             printBundle: printBundle,
94981             // internal API
94982             writeNode: writeNode,
94983             writeList: writeList,
94984             writeFile: writeFile,
94985             writeBundle: writeBundle,
94986             bundleFileInfo: bundleFileInfo
94987         };
94988         function printNode(hint, node, sourceFile) {
94989             switch (hint) {
94990                 case 0 /* SourceFile */:
94991                     ts.Debug.assert(ts.isSourceFile(node), "Expected a SourceFile node.");
94992                     break;
94993                 case 2 /* IdentifierName */:
94994                     ts.Debug.assert(ts.isIdentifier(node), "Expected an Identifier node.");
94995                     break;
94996                 case 1 /* Expression */:
94997                     ts.Debug.assert(ts.isExpression(node), "Expected an Expression node.");
94998                     break;
94999             }
95000             switch (node.kind) {
95001                 case 290 /* SourceFile */: return printFile(node);
95002                 case 291 /* Bundle */: return printBundle(node);
95003                 case 292 /* UnparsedSource */: return printUnparsedSource(node);
95004             }
95005             writeNode(hint, node, sourceFile, beginPrint());
95006             return endPrint();
95007         }
95008         function printList(format, nodes, sourceFile) {
95009             writeList(format, nodes, sourceFile, beginPrint());
95010             return endPrint();
95011         }
95012         function printBundle(bundle) {
95013             writeBundle(bundle, beginPrint(), /*sourceMapEmitter*/ undefined);
95014             return endPrint();
95015         }
95016         function printFile(sourceFile) {
95017             writeFile(sourceFile, beginPrint(), /*sourceMapEmitter*/ undefined);
95018             return endPrint();
95019         }
95020         function printUnparsedSource(unparsed) {
95021             writeUnparsedSource(unparsed, beginPrint());
95022             return endPrint();
95023         }
95024         function writeNode(hint, node, sourceFile, output) {
95025             var previousWriter = writer;
95026             setWriter(output, /*_sourceMapGenerator*/ undefined);
95027             print(hint, node, sourceFile);
95028             reset();
95029             writer = previousWriter;
95030         }
95031         function writeList(format, nodes, sourceFile, output) {
95032             var previousWriter = writer;
95033             setWriter(output, /*_sourceMapGenerator*/ undefined);
95034             if (sourceFile) {
95035                 setSourceFile(sourceFile);
95036             }
95037             emitList(syntheticParent, nodes, format);
95038             reset();
95039             writer = previousWriter;
95040         }
95041         function getTextPosWithWriteLine() {
95042             return writer.getTextPosWithWriteLine ? writer.getTextPosWithWriteLine() : writer.getTextPos();
95043         }
95044         function updateOrPushBundleFileTextLike(pos, end, kind) {
95045             var last = ts.lastOrUndefined(bundleFileInfo.sections);
95046             if (last && last.kind === kind) {
95047                 last.end = end;
95048             }
95049             else {
95050                 bundleFileInfo.sections.push({ pos: pos, end: end, kind: kind });
95051             }
95052         }
95053         function recordBundleFileInternalSectionStart(node) {
95054             if (recordInternalSection &&
95055                 bundleFileInfo &&
95056                 currentSourceFile &&
95057                 (ts.isDeclaration(node) || ts.isVariableStatement(node)) &&
95058                 ts.isInternalDeclaration(node, currentSourceFile) &&
95059                 sourceFileTextKind !== "internal" /* Internal */) {
95060                 var prevSourceFileTextKind = sourceFileTextKind;
95061                 recordBundleFileTextLikeSection(writer.getTextPos());
95062                 sourceFileTextPos = getTextPosWithWriteLine();
95063                 sourceFileTextKind = "internal" /* Internal */;
95064                 return prevSourceFileTextKind;
95065             }
95066             return undefined;
95067         }
95068         function recordBundleFileInternalSectionEnd(prevSourceFileTextKind) {
95069             if (prevSourceFileTextKind) {
95070                 recordBundleFileTextLikeSection(writer.getTextPos());
95071                 sourceFileTextPos = getTextPosWithWriteLine();
95072                 sourceFileTextKind = prevSourceFileTextKind;
95073             }
95074         }
95075         function recordBundleFileTextLikeSection(end) {
95076             if (sourceFileTextPos < end) {
95077                 updateOrPushBundleFileTextLike(sourceFileTextPos, end, sourceFileTextKind);
95078                 return true;
95079             }
95080             return false;
95081         }
95082         function writeBundle(bundle, output, sourceMapGenerator) {
95083             var _a;
95084             isOwnFileEmit = false;
95085             var previousWriter = writer;
95086             setWriter(output, sourceMapGenerator);
95087             emitShebangIfNeeded(bundle);
95088             emitPrologueDirectivesIfNeeded(bundle);
95089             emitHelpers(bundle);
95090             emitSyntheticTripleSlashReferencesIfNeeded(bundle);
95091             for (var _b = 0, _c = bundle.prepends; _b < _c.length; _b++) {
95092                 var prepend = _c[_b];
95093                 writeLine();
95094                 var pos = writer.getTextPos();
95095                 var savedSections = bundleFileInfo && bundleFileInfo.sections;
95096                 if (savedSections)
95097                     bundleFileInfo.sections = [];
95098                 print(4 /* Unspecified */, prepend, /*sourceFile*/ undefined);
95099                 if (bundleFileInfo) {
95100                     var newSections = bundleFileInfo.sections;
95101                     bundleFileInfo.sections = savedSections;
95102                     if (prepend.oldFileOfCurrentEmit)
95103                         (_a = bundleFileInfo.sections).push.apply(_a, newSections);
95104                     else {
95105                         newSections.forEach(function (section) { return ts.Debug.assert(ts.isBundleFileTextLike(section)); });
95106                         bundleFileInfo.sections.push({
95107                             pos: pos,
95108                             end: writer.getTextPos(),
95109                             kind: "prepend" /* Prepend */,
95110                             data: relativeToBuildInfo(prepend.fileName),
95111                             texts: newSections
95112                         });
95113                     }
95114                 }
95115             }
95116             sourceFileTextPos = getTextPosWithWriteLine();
95117             for (var _d = 0, _e = bundle.sourceFiles; _d < _e.length; _d++) {
95118                 var sourceFile = _e[_d];
95119                 print(0 /* SourceFile */, sourceFile, sourceFile);
95120             }
95121             if (bundleFileInfo && bundle.sourceFiles.length) {
95122                 var end = writer.getTextPos();
95123                 if (recordBundleFileTextLikeSection(end)) {
95124                     // Store prologues
95125                     var prologues = getPrologueDirectivesFromBundledSourceFiles(bundle);
95126                     if (prologues) {
95127                         if (!bundleFileInfo.sources)
95128                             bundleFileInfo.sources = {};
95129                         bundleFileInfo.sources.prologues = prologues;
95130                     }
95131                     // Store helpes
95132                     var helpers = getHelpersFromBundledSourceFiles(bundle);
95133                     if (helpers) {
95134                         if (!bundleFileInfo.sources)
95135                             bundleFileInfo.sources = {};
95136                         bundleFileInfo.sources.helpers = helpers;
95137                     }
95138                 }
95139             }
95140             reset();
95141             writer = previousWriter;
95142         }
95143         function writeUnparsedSource(unparsed, output) {
95144             var previousWriter = writer;
95145             setWriter(output, /*_sourceMapGenerator*/ undefined);
95146             print(4 /* Unspecified */, unparsed, /*sourceFile*/ undefined);
95147             reset();
95148             writer = previousWriter;
95149         }
95150         function writeFile(sourceFile, output, sourceMapGenerator) {
95151             isOwnFileEmit = true;
95152             var previousWriter = writer;
95153             setWriter(output, sourceMapGenerator);
95154             emitShebangIfNeeded(sourceFile);
95155             emitPrologueDirectivesIfNeeded(sourceFile);
95156             print(0 /* SourceFile */, sourceFile, sourceFile);
95157             reset();
95158             writer = previousWriter;
95159         }
95160         function beginPrint() {
95161             return ownWriter || (ownWriter = ts.createTextWriter(newLine));
95162         }
95163         function endPrint() {
95164             var text = ownWriter.getText();
95165             ownWriter.clear();
95166             return text;
95167         }
95168         function print(hint, node, sourceFile) {
95169             if (sourceFile) {
95170                 setSourceFile(sourceFile);
95171             }
95172             pipelineEmit(hint, node);
95173         }
95174         function setSourceFile(sourceFile) {
95175             currentSourceFile = sourceFile;
95176             currentLineMap = undefined;
95177             detachedCommentsInfo = undefined;
95178             if (sourceFile) {
95179                 setSourceMapSource(sourceFile);
95180             }
95181         }
95182         function setWriter(_writer, _sourceMapGenerator) {
95183             if (_writer && printerOptions.omitTrailingSemicolon) {
95184                 _writer = ts.getTrailingSemicolonDeferringWriter(_writer);
95185             }
95186             writer = _writer; // TODO: GH#18217
95187             sourceMapGenerator = _sourceMapGenerator;
95188             sourceMapsDisabled = !writer || !sourceMapGenerator;
95189         }
95190         function reset() {
95191             nodeIdToGeneratedName = [];
95192             autoGeneratedIdToGeneratedName = [];
95193             generatedNames = ts.createMap();
95194             tempFlagsStack = [];
95195             tempFlags = 0 /* Auto */;
95196             reservedNamesStack = [];
95197             currentSourceFile = undefined;
95198             currentLineMap = undefined;
95199             detachedCommentsInfo = undefined;
95200             lastNode = undefined;
95201             lastSubstitution = undefined;
95202             setWriter(/*output*/ undefined, /*_sourceMapGenerator*/ undefined);
95203         }
95204         function getCurrentLineMap() {
95205             return currentLineMap || (currentLineMap = ts.getLineStarts(currentSourceFile));
95206         }
95207         function emit(node) {
95208             if (node === undefined)
95209                 return;
95210             var prevSourceFileTextKind = recordBundleFileInternalSectionStart(node);
95211             var substitute = pipelineEmit(4 /* Unspecified */, node);
95212             recordBundleFileInternalSectionEnd(prevSourceFileTextKind);
95213             return substitute;
95214         }
95215         function emitIdentifierName(node) {
95216             if (node === undefined)
95217                 return;
95218             return pipelineEmit(2 /* IdentifierName */, node);
95219         }
95220         function emitExpression(node) {
95221             if (node === undefined)
95222                 return;
95223             return pipelineEmit(1 /* Expression */, node);
95224         }
95225         function emitJsxAttributeValue(node) {
95226             return pipelineEmit(ts.isStringLiteral(node) ? 6 /* JsxAttributeValue */ : 4 /* Unspecified */, node);
95227         }
95228         function pipelineEmit(emitHint, node) {
95229             var savedLastNode = lastNode;
95230             var savedLastSubstitution = lastSubstitution;
95231             var savedPreserveSourceNewlines = preserveSourceNewlines;
95232             lastNode = node;
95233             lastSubstitution = undefined;
95234             if (preserveSourceNewlines && !!(ts.getEmitFlags(node) & 134217728 /* IgnoreSourceNewlines */)) {
95235                 preserveSourceNewlines = false;
95236             }
95237             var pipelinePhase = getPipelinePhase(0 /* Notification */, emitHint, node);
95238             pipelinePhase(emitHint, node);
95239             ts.Debug.assert(lastNode === node);
95240             var substitute = lastSubstitution;
95241             lastNode = savedLastNode;
95242             lastSubstitution = savedLastSubstitution;
95243             preserveSourceNewlines = savedPreserveSourceNewlines;
95244             return substitute || node;
95245         }
95246         function getPipelinePhase(phase, emitHint, node) {
95247             switch (phase) {
95248                 case 0 /* Notification */:
95249                     if (onEmitNode !== ts.noEmitNotification && (!isEmitNotificationEnabled || isEmitNotificationEnabled(node))) {
95250                         return pipelineEmitWithNotification;
95251                     }
95252                 // falls through
95253                 case 1 /* Substitution */:
95254                     if (substituteNode !== ts.noEmitSubstitution && (lastSubstitution = substituteNode(emitHint, node)) !== node) {
95255                         return pipelineEmitWithSubstitution;
95256                     }
95257                 // falls through
95258                 case 2 /* Comments */:
95259                     if (!commentsDisabled && node.kind !== 290 /* SourceFile */) {
95260                         return pipelineEmitWithComments;
95261                     }
95262                 // falls through
95263                 case 3 /* SourceMaps */:
95264                     if (!sourceMapsDisabled && node.kind !== 290 /* SourceFile */ && !ts.isInJsonFile(node)) {
95265                         return pipelineEmitWithSourceMap;
95266                     }
95267                 // falls through
95268                 case 4 /* Emit */:
95269                     return pipelineEmitWithHint;
95270                 default:
95271                     return ts.Debug.assertNever(phase);
95272             }
95273         }
95274         function getNextPipelinePhase(currentPhase, emitHint, node) {
95275             return getPipelinePhase(currentPhase + 1, emitHint, node);
95276         }
95277         function pipelineEmitWithNotification(hint, node) {
95278             ts.Debug.assert(lastNode === node);
95279             var pipelinePhase = getNextPipelinePhase(0 /* Notification */, hint, node);
95280             onEmitNode(hint, node, pipelinePhase);
95281             ts.Debug.assert(lastNode === node);
95282         }
95283         function pipelineEmitWithHint(hint, node) {
95284             ts.Debug.assert(lastNode === node || lastSubstitution === node);
95285             if (hint === 0 /* SourceFile */)
95286                 return emitSourceFile(ts.cast(node, ts.isSourceFile));
95287             if (hint === 2 /* IdentifierName */)
95288                 return emitIdentifier(ts.cast(node, ts.isIdentifier));
95289             if (hint === 6 /* JsxAttributeValue */)
95290                 return emitLiteral(ts.cast(node, ts.isStringLiteral), /*jsxAttributeEscape*/ true);
95291             if (hint === 3 /* MappedTypeParameter */)
95292                 return emitMappedTypeParameter(ts.cast(node, ts.isTypeParameterDeclaration));
95293             if (hint === 5 /* EmbeddedStatement */) {
95294                 ts.Debug.assertNode(node, ts.isEmptyStatement);
95295                 return emitEmptyStatement(/*isEmbeddedStatement*/ true);
95296             }
95297             if (hint === 4 /* Unspecified */) {
95298                 if (ts.isKeyword(node.kind))
95299                     return writeTokenNode(node, writeKeyword);
95300                 switch (node.kind) {
95301                     // Pseudo-literals
95302                     case 15 /* TemplateHead */:
95303                     case 16 /* TemplateMiddle */:
95304                     case 17 /* TemplateTail */:
95305                         return emitLiteral(node, /*jsxAttributeEscape*/ false);
95306                     case 292 /* UnparsedSource */:
95307                     case 286 /* UnparsedPrepend */:
95308                         return emitUnparsedSourceOrPrepend(node);
95309                     case 285 /* UnparsedPrologue */:
95310                         return writeUnparsedNode(node);
95311                     case 287 /* UnparsedText */:
95312                     case 288 /* UnparsedInternalText */:
95313                         return emitUnparsedTextLike(node);
95314                     case 289 /* UnparsedSyntheticReference */:
95315                         return emitUnparsedSyntheticReference(node);
95316                     // Identifiers
95317                     case 75 /* Identifier */:
95318                         return emitIdentifier(node);
95319                     // PrivateIdentifiers
95320                     case 76 /* PrivateIdentifier */:
95321                         return emitPrivateIdentifier(node);
95322                     // Parse tree nodes
95323                     // Names
95324                     case 153 /* QualifiedName */:
95325                         return emitQualifiedName(node);
95326                     case 154 /* ComputedPropertyName */:
95327                         return emitComputedPropertyName(node);
95328                     // Signature elements
95329                     case 155 /* TypeParameter */:
95330                         return emitTypeParameter(node);
95331                     case 156 /* Parameter */:
95332                         return emitParameter(node);
95333                     case 157 /* Decorator */:
95334                         return emitDecorator(node);
95335                     // Type members
95336                     case 158 /* PropertySignature */:
95337                         return emitPropertySignature(node);
95338                     case 159 /* PropertyDeclaration */:
95339                         return emitPropertyDeclaration(node);
95340                     case 160 /* MethodSignature */:
95341                         return emitMethodSignature(node);
95342                     case 161 /* MethodDeclaration */:
95343                         return emitMethodDeclaration(node);
95344                     case 162 /* Constructor */:
95345                         return emitConstructor(node);
95346                     case 163 /* GetAccessor */:
95347                     case 164 /* SetAccessor */:
95348                         return emitAccessorDeclaration(node);
95349                     case 165 /* CallSignature */:
95350                         return emitCallSignature(node);
95351                     case 166 /* ConstructSignature */:
95352                         return emitConstructSignature(node);
95353                     case 167 /* IndexSignature */:
95354                         return emitIndexSignature(node);
95355                     // Types
95356                     case 168 /* TypePredicate */:
95357                         return emitTypePredicate(node);
95358                     case 169 /* TypeReference */:
95359                         return emitTypeReference(node);
95360                     case 170 /* FunctionType */:
95361                         return emitFunctionType(node);
95362                     case 300 /* JSDocFunctionType */:
95363                         return emitJSDocFunctionType(node);
95364                     case 171 /* ConstructorType */:
95365                         return emitConstructorType(node);
95366                     case 172 /* TypeQuery */:
95367                         return emitTypeQuery(node);
95368                     case 173 /* TypeLiteral */:
95369                         return emitTypeLiteral(node);
95370                     case 174 /* ArrayType */:
95371                         return emitArrayType(node);
95372                     case 175 /* TupleType */:
95373                         return emitTupleType(node);
95374                     case 176 /* OptionalType */:
95375                         return emitOptionalType(node);
95376                     case 178 /* UnionType */:
95377                         return emitUnionType(node);
95378                     case 179 /* IntersectionType */:
95379                         return emitIntersectionType(node);
95380                     case 180 /* ConditionalType */:
95381                         return emitConditionalType(node);
95382                     case 181 /* InferType */:
95383                         return emitInferType(node);
95384                     case 182 /* ParenthesizedType */:
95385                         return emitParenthesizedType(node);
95386                     case 216 /* ExpressionWithTypeArguments */:
95387                         return emitExpressionWithTypeArguments(node);
95388                     case 183 /* ThisType */:
95389                         return emitThisType();
95390                     case 184 /* TypeOperator */:
95391                         return emitTypeOperator(node);
95392                     case 185 /* IndexedAccessType */:
95393                         return emitIndexedAccessType(node);
95394                     case 186 /* MappedType */:
95395                         return emitMappedType(node);
95396                     case 187 /* LiteralType */:
95397                         return emitLiteralType(node);
95398                     case 188 /* ImportType */:
95399                         return emitImportTypeNode(node);
95400                     case 295 /* JSDocAllType */:
95401                         writePunctuation("*");
95402                         return;
95403                     case 296 /* JSDocUnknownType */:
95404                         writePunctuation("?");
95405                         return;
95406                     case 297 /* JSDocNullableType */:
95407                         return emitJSDocNullableType(node);
95408                     case 298 /* JSDocNonNullableType */:
95409                         return emitJSDocNonNullableType(node);
95410                     case 299 /* JSDocOptionalType */:
95411                         return emitJSDocOptionalType(node);
95412                     case 177 /* RestType */:
95413                     case 301 /* JSDocVariadicType */:
95414                         return emitRestOrJSDocVariadicType(node);
95415                     // Binding patterns
95416                     case 189 /* ObjectBindingPattern */:
95417                         return emitObjectBindingPattern(node);
95418                     case 190 /* ArrayBindingPattern */:
95419                         return emitArrayBindingPattern(node);
95420                     case 191 /* BindingElement */:
95421                         return emitBindingElement(node);
95422                     // Misc
95423                     case 221 /* TemplateSpan */:
95424                         return emitTemplateSpan(node);
95425                     case 222 /* SemicolonClassElement */:
95426                         return emitSemicolonClassElement();
95427                     // Statements
95428                     case 223 /* Block */:
95429                         return emitBlock(node);
95430                     case 225 /* VariableStatement */:
95431                         return emitVariableStatement(node);
95432                     case 224 /* EmptyStatement */:
95433                         return emitEmptyStatement(/*isEmbeddedStatement*/ false);
95434                     case 226 /* ExpressionStatement */:
95435                         return emitExpressionStatement(node);
95436                     case 227 /* IfStatement */:
95437                         return emitIfStatement(node);
95438                     case 228 /* DoStatement */:
95439                         return emitDoStatement(node);
95440                     case 229 /* WhileStatement */:
95441                         return emitWhileStatement(node);
95442                     case 230 /* ForStatement */:
95443                         return emitForStatement(node);
95444                     case 231 /* ForInStatement */:
95445                         return emitForInStatement(node);
95446                     case 232 /* ForOfStatement */:
95447                         return emitForOfStatement(node);
95448                     case 233 /* ContinueStatement */:
95449                         return emitContinueStatement(node);
95450                     case 234 /* BreakStatement */:
95451                         return emitBreakStatement(node);
95452                     case 235 /* ReturnStatement */:
95453                         return emitReturnStatement(node);
95454                     case 236 /* WithStatement */:
95455                         return emitWithStatement(node);
95456                     case 237 /* SwitchStatement */:
95457                         return emitSwitchStatement(node);
95458                     case 238 /* LabeledStatement */:
95459                         return emitLabeledStatement(node);
95460                     case 239 /* ThrowStatement */:
95461                         return emitThrowStatement(node);
95462                     case 240 /* TryStatement */:
95463                         return emitTryStatement(node);
95464                     case 241 /* DebuggerStatement */:
95465                         return emitDebuggerStatement(node);
95466                     // Declarations
95467                     case 242 /* VariableDeclaration */:
95468                         return emitVariableDeclaration(node);
95469                     case 243 /* VariableDeclarationList */:
95470                         return emitVariableDeclarationList(node);
95471                     case 244 /* FunctionDeclaration */:
95472                         return emitFunctionDeclaration(node);
95473                     case 245 /* ClassDeclaration */:
95474                         return emitClassDeclaration(node);
95475                     case 246 /* InterfaceDeclaration */:
95476                         return emitInterfaceDeclaration(node);
95477                     case 247 /* TypeAliasDeclaration */:
95478                         return emitTypeAliasDeclaration(node);
95479                     case 248 /* EnumDeclaration */:
95480                         return emitEnumDeclaration(node);
95481                     case 249 /* ModuleDeclaration */:
95482                         return emitModuleDeclaration(node);
95483                     case 250 /* ModuleBlock */:
95484                         return emitModuleBlock(node);
95485                     case 251 /* CaseBlock */:
95486                         return emitCaseBlock(node);
95487                     case 252 /* NamespaceExportDeclaration */:
95488                         return emitNamespaceExportDeclaration(node);
95489                     case 253 /* ImportEqualsDeclaration */:
95490                         return emitImportEqualsDeclaration(node);
95491                     case 254 /* ImportDeclaration */:
95492                         return emitImportDeclaration(node);
95493                     case 255 /* ImportClause */:
95494                         return emitImportClause(node);
95495                     case 256 /* NamespaceImport */:
95496                         return emitNamespaceImport(node);
95497                     case 262 /* NamespaceExport */:
95498                         return emitNamespaceExport(node);
95499                     case 257 /* NamedImports */:
95500                         return emitNamedImports(node);
95501                     case 258 /* ImportSpecifier */:
95502                         return emitImportSpecifier(node);
95503                     case 259 /* ExportAssignment */:
95504                         return emitExportAssignment(node);
95505                     case 260 /* ExportDeclaration */:
95506                         return emitExportDeclaration(node);
95507                     case 261 /* NamedExports */:
95508                         return emitNamedExports(node);
95509                     case 263 /* ExportSpecifier */:
95510                         return emitExportSpecifier(node);
95511                     case 264 /* MissingDeclaration */:
95512                         return;
95513                     // Module references
95514                     case 265 /* ExternalModuleReference */:
95515                         return emitExternalModuleReference(node);
95516                     // JSX (non-expression)
95517                     case 11 /* JsxText */:
95518                         return emitJsxText(node);
95519                     case 268 /* JsxOpeningElement */:
95520                     case 271 /* JsxOpeningFragment */:
95521                         return emitJsxOpeningElementOrFragment(node);
95522                     case 269 /* JsxClosingElement */:
95523                     case 272 /* JsxClosingFragment */:
95524                         return emitJsxClosingElementOrFragment(node);
95525                     case 273 /* JsxAttribute */:
95526                         return emitJsxAttribute(node);
95527                     case 274 /* JsxAttributes */:
95528                         return emitJsxAttributes(node);
95529                     case 275 /* JsxSpreadAttribute */:
95530                         return emitJsxSpreadAttribute(node);
95531                     case 276 /* JsxExpression */:
95532                         return emitJsxExpression(node);
95533                     // Clauses
95534                     case 277 /* CaseClause */:
95535                         return emitCaseClause(node);
95536                     case 278 /* DefaultClause */:
95537                         return emitDefaultClause(node);
95538                     case 279 /* HeritageClause */:
95539                         return emitHeritageClause(node);
95540                     case 280 /* CatchClause */:
95541                         return emitCatchClause(node);
95542                     // Property assignments
95543                     case 281 /* PropertyAssignment */:
95544                         return emitPropertyAssignment(node);
95545                     case 282 /* ShorthandPropertyAssignment */:
95546                         return emitShorthandPropertyAssignment(node);
95547                     case 283 /* SpreadAssignment */:
95548                         return emitSpreadAssignment(node);
95549                     // Enum
95550                     case 284 /* EnumMember */:
95551                         return emitEnumMember(node);
95552                     // JSDoc nodes (only used in codefixes currently)
95553                     case 317 /* JSDocParameterTag */:
95554                     case 323 /* JSDocPropertyTag */:
95555                         return emitJSDocPropertyLikeTag(node);
95556                     case 318 /* JSDocReturnTag */:
95557                     case 320 /* JSDocTypeTag */:
95558                     case 319 /* JSDocThisTag */:
95559                     case 316 /* JSDocEnumTag */:
95560                         return emitJSDocSimpleTypedTag(node);
95561                     case 308 /* JSDocImplementsTag */:
95562                     case 307 /* JSDocAugmentsTag */:
95563                         return emitJSDocHeritageTag(node);
95564                     case 321 /* JSDocTemplateTag */:
95565                         return emitJSDocTemplateTag(node);
95566                     case 322 /* JSDocTypedefTag */:
95567                         return emitJSDocTypedefTag(node);
95568                     case 315 /* JSDocCallbackTag */:
95569                         return emitJSDocCallbackTag(node);
95570                     case 305 /* JSDocSignature */:
95571                         return emitJSDocSignature(node);
95572                     case 304 /* JSDocTypeLiteral */:
95573                         return emitJSDocTypeLiteral(node);
95574                     case 310 /* JSDocClassTag */:
95575                     case 306 /* JSDocTag */:
95576                         return emitJSDocSimpleTag(node);
95577                     case 303 /* JSDocComment */:
95578                         return emitJSDoc(node);
95579                     // Transformation nodes (ignored)
95580                 }
95581                 if (ts.isExpression(node)) {
95582                     hint = 1 /* Expression */;
95583                     if (substituteNode !== ts.noEmitSubstitution) {
95584                         lastSubstitution = node = substituteNode(hint, node);
95585                     }
95586                 }
95587                 else if (ts.isToken(node)) {
95588                     return writeTokenNode(node, writePunctuation);
95589                 }
95590             }
95591             if (hint === 1 /* Expression */) {
95592                 switch (node.kind) {
95593                     // Literals
95594                     case 8 /* NumericLiteral */:
95595                     case 9 /* BigIntLiteral */:
95596                         return emitNumericOrBigIntLiteral(node);
95597                     case 10 /* StringLiteral */:
95598                     case 13 /* RegularExpressionLiteral */:
95599                     case 14 /* NoSubstitutionTemplateLiteral */:
95600                         return emitLiteral(node, /*jsxAttributeEscape*/ false);
95601                     // Identifiers
95602                     case 75 /* Identifier */:
95603                         return emitIdentifier(node);
95604                     // Reserved words
95605                     case 91 /* FalseKeyword */:
95606                     case 100 /* NullKeyword */:
95607                     case 102 /* SuperKeyword */:
95608                     case 106 /* TrueKeyword */:
95609                     case 104 /* ThisKeyword */:
95610                     case 96 /* ImportKeyword */:
95611                         writeTokenNode(node, writeKeyword);
95612                         return;
95613                     // Expressions
95614                     case 192 /* ArrayLiteralExpression */:
95615                         return emitArrayLiteralExpression(node);
95616                     case 193 /* ObjectLiteralExpression */:
95617                         return emitObjectLiteralExpression(node);
95618                     case 194 /* PropertyAccessExpression */:
95619                         return emitPropertyAccessExpression(node);
95620                     case 195 /* ElementAccessExpression */:
95621                         return emitElementAccessExpression(node);
95622                     case 196 /* CallExpression */:
95623                         return emitCallExpression(node);
95624                     case 197 /* NewExpression */:
95625                         return emitNewExpression(node);
95626                     case 198 /* TaggedTemplateExpression */:
95627                         return emitTaggedTemplateExpression(node);
95628                     case 199 /* TypeAssertionExpression */:
95629                         return emitTypeAssertionExpression(node);
95630                     case 200 /* ParenthesizedExpression */:
95631                         return emitParenthesizedExpression(node);
95632                     case 201 /* FunctionExpression */:
95633                         return emitFunctionExpression(node);
95634                     case 202 /* ArrowFunction */:
95635                         return emitArrowFunction(node);
95636                     case 203 /* DeleteExpression */:
95637                         return emitDeleteExpression(node);
95638                     case 204 /* TypeOfExpression */:
95639                         return emitTypeOfExpression(node);
95640                     case 205 /* VoidExpression */:
95641                         return emitVoidExpression(node);
95642                     case 206 /* AwaitExpression */:
95643                         return emitAwaitExpression(node);
95644                     case 207 /* PrefixUnaryExpression */:
95645                         return emitPrefixUnaryExpression(node);
95646                     case 208 /* PostfixUnaryExpression */:
95647                         return emitPostfixUnaryExpression(node);
95648                     case 209 /* BinaryExpression */:
95649                         return emitBinaryExpression(node);
95650                     case 210 /* ConditionalExpression */:
95651                         return emitConditionalExpression(node);
95652                     case 211 /* TemplateExpression */:
95653                         return emitTemplateExpression(node);
95654                     case 212 /* YieldExpression */:
95655                         return emitYieldExpression(node);
95656                     case 213 /* SpreadElement */:
95657                         return emitSpreadExpression(node);
95658                     case 214 /* ClassExpression */:
95659                         return emitClassExpression(node);
95660                     case 215 /* OmittedExpression */:
95661                         return;
95662                     case 217 /* AsExpression */:
95663                         return emitAsExpression(node);
95664                     case 218 /* NonNullExpression */:
95665                         return emitNonNullExpression(node);
95666                     case 219 /* MetaProperty */:
95667                         return emitMetaProperty(node);
95668                     // JSX
95669                     case 266 /* JsxElement */:
95670                         return emitJsxElement(node);
95671                     case 267 /* JsxSelfClosingElement */:
95672                         return emitJsxSelfClosingElement(node);
95673                     case 270 /* JsxFragment */:
95674                         return emitJsxFragment(node);
95675                     // Transformation nodes
95676                     case 326 /* PartiallyEmittedExpression */:
95677                         return emitPartiallyEmittedExpression(node);
95678                     case 327 /* CommaListExpression */:
95679                         return emitCommaList(node);
95680                 }
95681             }
95682         }
95683         function emitMappedTypeParameter(node) {
95684             emit(node.name);
95685             writeSpace();
95686             writeKeyword("in");
95687             writeSpace();
95688             emit(node.constraint);
95689         }
95690         function pipelineEmitWithSubstitution(hint, node) {
95691             ts.Debug.assert(lastNode === node || lastSubstitution === node);
95692             var pipelinePhase = getNextPipelinePhase(1 /* Substitution */, hint, node);
95693             pipelinePhase(hint, lastSubstitution);
95694             ts.Debug.assert(lastNode === node || lastSubstitution === node);
95695         }
95696         function getHelpersFromBundledSourceFiles(bundle) {
95697             var result;
95698             if (moduleKind === ts.ModuleKind.None || printerOptions.noEmitHelpers) {
95699                 return undefined;
95700             }
95701             var bundledHelpers = ts.createMap();
95702             for (var _a = 0, _b = bundle.sourceFiles; _a < _b.length; _a++) {
95703                 var sourceFile = _b[_a];
95704                 var shouldSkip = ts.getExternalHelpersModuleName(sourceFile) !== undefined;
95705                 var helpers = getSortedEmitHelpers(sourceFile);
95706                 if (!helpers)
95707                     continue;
95708                 for (var _c = 0, helpers_4 = helpers; _c < helpers_4.length; _c++) {
95709                     var helper = helpers_4[_c];
95710                     if (!helper.scoped && !shouldSkip && !bundledHelpers.get(helper.name)) {
95711                         bundledHelpers.set(helper.name, true);
95712                         (result || (result = [])).push(helper.name);
95713                     }
95714                 }
95715             }
95716             return result;
95717         }
95718         function emitHelpers(node) {
95719             var helpersEmitted = false;
95720             var bundle = node.kind === 291 /* Bundle */ ? node : undefined;
95721             if (bundle && moduleKind === ts.ModuleKind.None) {
95722                 return;
95723             }
95724             var numPrepends = bundle ? bundle.prepends.length : 0;
95725             var numNodes = bundle ? bundle.sourceFiles.length + numPrepends : 1;
95726             for (var i = 0; i < numNodes; i++) {
95727                 var currentNode = bundle ? i < numPrepends ? bundle.prepends[i] : bundle.sourceFiles[i - numPrepends] : node;
95728                 var sourceFile = ts.isSourceFile(currentNode) ? currentNode : ts.isUnparsedSource(currentNode) ? undefined : currentSourceFile;
95729                 var shouldSkip = printerOptions.noEmitHelpers || (!!sourceFile && ts.hasRecordedExternalHelpers(sourceFile));
95730                 var shouldBundle = (ts.isSourceFile(currentNode) || ts.isUnparsedSource(currentNode)) && !isOwnFileEmit;
95731                 var helpers = ts.isUnparsedSource(currentNode) ? currentNode.helpers : getSortedEmitHelpers(currentNode);
95732                 if (helpers) {
95733                     for (var _a = 0, helpers_5 = helpers; _a < helpers_5.length; _a++) {
95734                         var helper = helpers_5[_a];
95735                         if (!helper.scoped) {
95736                             // Skip the helper if it can be skipped and the noEmitHelpers compiler
95737                             // option is set, or if it can be imported and the importHelpers compiler
95738                             // option is set.
95739                             if (shouldSkip)
95740                                 continue;
95741                             // Skip the helper if it can be bundled but hasn't already been emitted and we
95742                             // are emitting a bundled module.
95743                             if (shouldBundle) {
95744                                 if (bundledHelpers.get(helper.name)) {
95745                                     continue;
95746                                 }
95747                                 bundledHelpers.set(helper.name, true);
95748                             }
95749                         }
95750                         else if (bundle) {
95751                             // Skip the helper if it is scoped and we are emitting bundled helpers
95752                             continue;
95753                         }
95754                         var pos = getTextPosWithWriteLine();
95755                         if (typeof helper.text === "string") {
95756                             writeLines(helper.text);
95757                         }
95758                         else {
95759                             writeLines(helper.text(makeFileLevelOptimisticUniqueName));
95760                         }
95761                         if (bundleFileInfo)
95762                             bundleFileInfo.sections.push({ pos: pos, end: writer.getTextPos(), kind: "emitHelpers" /* EmitHelpers */, data: helper.name });
95763                         helpersEmitted = true;
95764                     }
95765                 }
95766             }
95767             return helpersEmitted;
95768         }
95769         function getSortedEmitHelpers(node) {
95770             var helpers = ts.getEmitHelpers(node);
95771             return helpers && ts.stableSort(helpers, ts.compareEmitHelpers);
95772         }
95773         //
95774         // Literals/Pseudo-literals
95775         //
95776         // SyntaxKind.NumericLiteral
95777         // SyntaxKind.BigIntLiteral
95778         function emitNumericOrBigIntLiteral(node) {
95779             emitLiteral(node, /*jsxAttributeEscape*/ false);
95780         }
95781         // SyntaxKind.StringLiteral
95782         // SyntaxKind.RegularExpressionLiteral
95783         // SyntaxKind.NoSubstitutionTemplateLiteral
95784         // SyntaxKind.TemplateHead
95785         // SyntaxKind.TemplateMiddle
95786         // SyntaxKind.TemplateTail
95787         function emitLiteral(node, jsxAttributeEscape) {
95788             var text = getLiteralTextOfNode(node, printerOptions.neverAsciiEscape, jsxAttributeEscape);
95789             if ((printerOptions.sourceMap || printerOptions.inlineSourceMap)
95790                 && (node.kind === 10 /* StringLiteral */ || ts.isTemplateLiteralKind(node.kind))) {
95791                 writeLiteral(text);
95792             }
95793             else {
95794                 // Quick info expects all literals to be called with writeStringLiteral, as there's no specific type for numberLiterals
95795                 writeStringLiteral(text);
95796             }
95797         }
95798         // SyntaxKind.UnparsedSource
95799         // SyntaxKind.UnparsedPrepend
95800         function emitUnparsedSourceOrPrepend(unparsed) {
95801             for (var _a = 0, _b = unparsed.texts; _a < _b.length; _a++) {
95802                 var text = _b[_a];
95803                 writeLine();
95804                 emit(text);
95805             }
95806         }
95807         // SyntaxKind.UnparsedPrologue
95808         // SyntaxKind.UnparsedText
95809         // SyntaxKind.UnparsedInternal
95810         // SyntaxKind.UnparsedSyntheticReference
95811         function writeUnparsedNode(unparsed) {
95812             writer.rawWrite(unparsed.parent.text.substring(unparsed.pos, unparsed.end));
95813         }
95814         // SyntaxKind.UnparsedText
95815         // SyntaxKind.UnparsedInternal
95816         function emitUnparsedTextLike(unparsed) {
95817             var pos = getTextPosWithWriteLine();
95818             writeUnparsedNode(unparsed);
95819             if (bundleFileInfo) {
95820                 updateOrPushBundleFileTextLike(pos, writer.getTextPos(), unparsed.kind === 287 /* UnparsedText */ ?
95821                     "text" /* Text */ :
95822                     "internal" /* Internal */);
95823             }
95824         }
95825         // SyntaxKind.UnparsedSyntheticReference
95826         function emitUnparsedSyntheticReference(unparsed) {
95827             var pos = getTextPosWithWriteLine();
95828             writeUnparsedNode(unparsed);
95829             if (bundleFileInfo) {
95830                 var section = ts.clone(unparsed.section);
95831                 section.pos = pos;
95832                 section.end = writer.getTextPos();
95833                 bundleFileInfo.sections.push(section);
95834             }
95835         }
95836         //
95837         // Identifiers
95838         //
95839         function emitIdentifier(node) {
95840             var writeText = node.symbol ? writeSymbol : write;
95841             writeText(getTextOfNode(node, /*includeTrivia*/ false), node.symbol);
95842             emitList(node, node.typeArguments, 53776 /* TypeParameters */); // Call emitList directly since it could be an array of TypeParameterDeclarations _or_ type arguments
95843         }
95844         //
95845         // Names
95846         //
95847         function emitPrivateIdentifier(node) {
95848             var writeText = node.symbol ? writeSymbol : write;
95849             writeText(getTextOfNode(node, /*includeTrivia*/ false), node.symbol);
95850         }
95851         function emitQualifiedName(node) {
95852             emitEntityName(node.left);
95853             writePunctuation(".");
95854             emit(node.right);
95855         }
95856         function emitEntityName(node) {
95857             if (node.kind === 75 /* Identifier */) {
95858                 emitExpression(node);
95859             }
95860             else {
95861                 emit(node);
95862             }
95863         }
95864         function emitComputedPropertyName(node) {
95865             writePunctuation("[");
95866             emitExpression(node.expression);
95867             writePunctuation("]");
95868         }
95869         //
95870         // Signature elements
95871         //
95872         function emitTypeParameter(node) {
95873             emit(node.name);
95874             if (node.constraint) {
95875                 writeSpace();
95876                 writeKeyword("extends");
95877                 writeSpace();
95878                 emit(node.constraint);
95879             }
95880             if (node.default) {
95881                 writeSpace();
95882                 writeOperator("=");
95883                 writeSpace();
95884                 emit(node.default);
95885             }
95886         }
95887         function emitParameter(node) {
95888             emitDecorators(node, node.decorators);
95889             emitModifiers(node, node.modifiers);
95890             emit(node.dotDotDotToken);
95891             emitNodeWithWriter(node.name, writeParameter);
95892             emit(node.questionToken);
95893             if (node.parent && node.parent.kind === 300 /* JSDocFunctionType */ && !node.name) {
95894                 emit(node.type);
95895             }
95896             else {
95897                 emitTypeAnnotation(node.type);
95898             }
95899             // 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.
95900             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);
95901         }
95902         function emitDecorator(decorator) {
95903             writePunctuation("@");
95904             emitExpression(decorator.expression);
95905         }
95906         //
95907         // Type members
95908         //
95909         function emitPropertySignature(node) {
95910             emitDecorators(node, node.decorators);
95911             emitModifiers(node, node.modifiers);
95912             emitNodeWithWriter(node.name, writeProperty);
95913             emit(node.questionToken);
95914             emitTypeAnnotation(node.type);
95915             writeTrailingSemicolon();
95916         }
95917         function emitPropertyDeclaration(node) {
95918             emitDecorators(node, node.decorators);
95919             emitModifiers(node, node.modifiers);
95920             emit(node.name);
95921             emit(node.questionToken);
95922             emit(node.exclamationToken);
95923             emitTypeAnnotation(node.type);
95924             emitInitializer(node.initializer, node.type ? node.type.end : node.questionToken ? node.questionToken.end : node.name.end, node);
95925             writeTrailingSemicolon();
95926         }
95927         function emitMethodSignature(node) {
95928             pushNameGenerationScope(node);
95929             emitDecorators(node, node.decorators);
95930             emitModifiers(node, node.modifiers);
95931             emit(node.name);
95932             emit(node.questionToken);
95933             emitTypeParameters(node, node.typeParameters);
95934             emitParameters(node, node.parameters);
95935             emitTypeAnnotation(node.type);
95936             writeTrailingSemicolon();
95937             popNameGenerationScope(node);
95938         }
95939         function emitMethodDeclaration(node) {
95940             emitDecorators(node, node.decorators);
95941             emitModifiers(node, node.modifiers);
95942             emit(node.asteriskToken);
95943             emit(node.name);
95944             emit(node.questionToken);
95945             emitSignatureAndBody(node, emitSignatureHead);
95946         }
95947         function emitConstructor(node) {
95948             emitModifiers(node, node.modifiers);
95949             writeKeyword("constructor");
95950             emitSignatureAndBody(node, emitSignatureHead);
95951         }
95952         function emitAccessorDeclaration(node) {
95953             emitDecorators(node, node.decorators);
95954             emitModifiers(node, node.modifiers);
95955             writeKeyword(node.kind === 163 /* GetAccessor */ ? "get" : "set");
95956             writeSpace();
95957             emit(node.name);
95958             emitSignatureAndBody(node, emitSignatureHead);
95959         }
95960         function emitCallSignature(node) {
95961             pushNameGenerationScope(node);
95962             emitDecorators(node, node.decorators);
95963             emitModifiers(node, node.modifiers);
95964             emitTypeParameters(node, node.typeParameters);
95965             emitParameters(node, node.parameters);
95966             emitTypeAnnotation(node.type);
95967             writeTrailingSemicolon();
95968             popNameGenerationScope(node);
95969         }
95970         function emitConstructSignature(node) {
95971             pushNameGenerationScope(node);
95972             emitDecorators(node, node.decorators);
95973             emitModifiers(node, node.modifiers);
95974             writeKeyword("new");
95975             writeSpace();
95976             emitTypeParameters(node, node.typeParameters);
95977             emitParameters(node, node.parameters);
95978             emitTypeAnnotation(node.type);
95979             writeTrailingSemicolon();
95980             popNameGenerationScope(node);
95981         }
95982         function emitIndexSignature(node) {
95983             emitDecorators(node, node.decorators);
95984             emitModifiers(node, node.modifiers);
95985             emitParametersForIndexSignature(node, node.parameters);
95986             emitTypeAnnotation(node.type);
95987             writeTrailingSemicolon();
95988         }
95989         function emitSemicolonClassElement() {
95990             writeTrailingSemicolon();
95991         }
95992         //
95993         // Types
95994         //
95995         function emitTypePredicate(node) {
95996             if (node.assertsModifier) {
95997                 emit(node.assertsModifier);
95998                 writeSpace();
95999             }
96000             emit(node.parameterName);
96001             if (node.type) {
96002                 writeSpace();
96003                 writeKeyword("is");
96004                 writeSpace();
96005                 emit(node.type);
96006             }
96007         }
96008         function emitTypeReference(node) {
96009             emit(node.typeName);
96010             emitTypeArguments(node, node.typeArguments);
96011         }
96012         function emitFunctionType(node) {
96013             pushNameGenerationScope(node);
96014             emitTypeParameters(node, node.typeParameters);
96015             emitParametersForArrow(node, node.parameters);
96016             writeSpace();
96017             writePunctuation("=>");
96018             writeSpace();
96019             emit(node.type);
96020             popNameGenerationScope(node);
96021         }
96022         function emitJSDocFunctionType(node) {
96023             writeKeyword("function");
96024             emitParameters(node, node.parameters);
96025             writePunctuation(":");
96026             emit(node.type);
96027         }
96028         function emitJSDocNullableType(node) {
96029             writePunctuation("?");
96030             emit(node.type);
96031         }
96032         function emitJSDocNonNullableType(node) {
96033             writePunctuation("!");
96034             emit(node.type);
96035         }
96036         function emitJSDocOptionalType(node) {
96037             emit(node.type);
96038             writePunctuation("=");
96039         }
96040         function emitConstructorType(node) {
96041             pushNameGenerationScope(node);
96042             writeKeyword("new");
96043             writeSpace();
96044             emitTypeParameters(node, node.typeParameters);
96045             emitParameters(node, node.parameters);
96046             writeSpace();
96047             writePunctuation("=>");
96048             writeSpace();
96049             emit(node.type);
96050             popNameGenerationScope(node);
96051         }
96052         function emitTypeQuery(node) {
96053             writeKeyword("typeof");
96054             writeSpace();
96055             emit(node.exprName);
96056         }
96057         function emitTypeLiteral(node) {
96058             writePunctuation("{");
96059             var flags = ts.getEmitFlags(node) & 1 /* SingleLine */ ? 768 /* SingleLineTypeLiteralMembers */ : 32897 /* MultiLineTypeLiteralMembers */;
96060             emitList(node, node.members, flags | 524288 /* NoSpaceIfEmpty */);
96061             writePunctuation("}");
96062         }
96063         function emitArrayType(node) {
96064             emit(node.elementType);
96065             writePunctuation("[");
96066             writePunctuation("]");
96067         }
96068         function emitRestOrJSDocVariadicType(node) {
96069             writePunctuation("...");
96070             emit(node.type);
96071         }
96072         function emitTupleType(node) {
96073             writePunctuation("[");
96074             emitList(node, node.elementTypes, 528 /* TupleTypeElements */);
96075             writePunctuation("]");
96076         }
96077         function emitOptionalType(node) {
96078             emit(node.type);
96079             writePunctuation("?");
96080         }
96081         function emitUnionType(node) {
96082             emitList(node, node.types, 516 /* UnionTypeConstituents */);
96083         }
96084         function emitIntersectionType(node) {
96085             emitList(node, node.types, 520 /* IntersectionTypeConstituents */);
96086         }
96087         function emitConditionalType(node) {
96088             emit(node.checkType);
96089             writeSpace();
96090             writeKeyword("extends");
96091             writeSpace();
96092             emit(node.extendsType);
96093             writeSpace();
96094             writePunctuation("?");
96095             writeSpace();
96096             emit(node.trueType);
96097             writeSpace();
96098             writePunctuation(":");
96099             writeSpace();
96100             emit(node.falseType);
96101         }
96102         function emitInferType(node) {
96103             writeKeyword("infer");
96104             writeSpace();
96105             emit(node.typeParameter);
96106         }
96107         function emitParenthesizedType(node) {
96108             writePunctuation("(");
96109             emit(node.type);
96110             writePunctuation(")");
96111         }
96112         function emitThisType() {
96113             writeKeyword("this");
96114         }
96115         function emitTypeOperator(node) {
96116             writeTokenText(node.operator, writeKeyword);
96117             writeSpace();
96118             emit(node.type);
96119         }
96120         function emitIndexedAccessType(node) {
96121             emit(node.objectType);
96122             writePunctuation("[");
96123             emit(node.indexType);
96124             writePunctuation("]");
96125         }
96126         function emitMappedType(node) {
96127             var emitFlags = ts.getEmitFlags(node);
96128             writePunctuation("{");
96129             if (emitFlags & 1 /* SingleLine */) {
96130                 writeSpace();
96131             }
96132             else {
96133                 writeLine();
96134                 increaseIndent();
96135             }
96136             if (node.readonlyToken) {
96137                 emit(node.readonlyToken);
96138                 if (node.readonlyToken.kind !== 138 /* ReadonlyKeyword */) {
96139                     writeKeyword("readonly");
96140                 }
96141                 writeSpace();
96142             }
96143             writePunctuation("[");
96144             pipelineEmit(3 /* MappedTypeParameter */, node.typeParameter);
96145             writePunctuation("]");
96146             if (node.questionToken) {
96147                 emit(node.questionToken);
96148                 if (node.questionToken.kind !== 57 /* QuestionToken */) {
96149                     writePunctuation("?");
96150                 }
96151             }
96152             writePunctuation(":");
96153             writeSpace();
96154             emit(node.type);
96155             writeTrailingSemicolon();
96156             if (emitFlags & 1 /* SingleLine */) {
96157                 writeSpace();
96158             }
96159             else {
96160                 writeLine();
96161                 decreaseIndent();
96162             }
96163             writePunctuation("}");
96164         }
96165         function emitLiteralType(node) {
96166             emitExpression(node.literal);
96167         }
96168         function emitImportTypeNode(node) {
96169             if (node.isTypeOf) {
96170                 writeKeyword("typeof");
96171                 writeSpace();
96172             }
96173             writeKeyword("import");
96174             writePunctuation("(");
96175             emit(node.argument);
96176             writePunctuation(")");
96177             if (node.qualifier) {
96178                 writePunctuation(".");
96179                 emit(node.qualifier);
96180             }
96181             emitTypeArguments(node, node.typeArguments);
96182         }
96183         //
96184         // Binding patterns
96185         //
96186         function emitObjectBindingPattern(node) {
96187             writePunctuation("{");
96188             emitList(node, node.elements, 525136 /* ObjectBindingPatternElements */);
96189             writePunctuation("}");
96190         }
96191         function emitArrayBindingPattern(node) {
96192             writePunctuation("[");
96193             emitList(node, node.elements, 524880 /* ArrayBindingPatternElements */);
96194             writePunctuation("]");
96195         }
96196         function emitBindingElement(node) {
96197             emit(node.dotDotDotToken);
96198             if (node.propertyName) {
96199                 emit(node.propertyName);
96200                 writePunctuation(":");
96201                 writeSpace();
96202             }
96203             emit(node.name);
96204             emitInitializer(node.initializer, node.name.end, node);
96205         }
96206         //
96207         // Expressions
96208         //
96209         function emitArrayLiteralExpression(node) {
96210             var elements = node.elements;
96211             var preferNewLine = node.multiLine ? 65536 /* PreferNewLine */ : 0 /* None */;
96212             emitExpressionList(node, elements, 8914 /* ArrayLiteralExpressionElements */ | preferNewLine);
96213         }
96214         function emitObjectLiteralExpression(node) {
96215             ts.forEach(node.properties, generateMemberNames);
96216             var indentedFlag = ts.getEmitFlags(node) & 65536 /* Indented */;
96217             if (indentedFlag) {
96218                 increaseIndent();
96219             }
96220             var preferNewLine = node.multiLine ? 65536 /* PreferNewLine */ : 0 /* None */;
96221             var allowTrailingComma = currentSourceFile.languageVersion >= 1 /* ES5 */ && !ts.isJsonSourceFile(currentSourceFile) ? 64 /* AllowTrailingComma */ : 0 /* None */;
96222             emitList(node, node.properties, 526226 /* ObjectLiteralExpressionProperties */ | allowTrailingComma | preferNewLine);
96223             if (indentedFlag) {
96224                 decreaseIndent();
96225             }
96226         }
96227         function emitPropertyAccessExpression(node) {
96228             var expression = ts.cast(emitExpression(node.expression), ts.isExpression);
96229             var token = node.questionDotToken || ts.createNode(24 /* DotToken */, node.expression.end, node.name.pos);
96230             var linesBeforeDot = getLinesBetweenNodes(node, node.expression, token);
96231             var linesAfterDot = getLinesBetweenNodes(node, token, node.name);
96232             writeLinesAndIndent(linesBeforeDot, /*writeSpaceIfNotIndenting*/ false);
96233             var shouldEmitDotDot = token.kind !== 28 /* QuestionDotToken */ &&
96234                 mayNeedDotDotForPropertyAccess(expression) &&
96235                 !writer.hasTrailingComment() &&
96236                 !writer.hasTrailingWhitespace();
96237             if (shouldEmitDotDot) {
96238                 writePunctuation(".");
96239             }
96240             if (node.questionDotToken) {
96241                 emit(token);
96242             }
96243             else {
96244                 emitTokenWithComment(token.kind, node.expression.end, writePunctuation, node);
96245             }
96246             writeLinesAndIndent(linesAfterDot, /*writeSpaceIfNotIndenting*/ false);
96247             emit(node.name);
96248             decreaseIndentIf(linesBeforeDot, linesAfterDot);
96249         }
96250         // 1..toString is a valid property access, emit a dot after the literal
96251         // Also emit a dot if expression is a integer const enum value - it will appear in generated code as numeric literal
96252         function mayNeedDotDotForPropertyAccess(expression) {
96253             expression = ts.skipPartiallyEmittedExpressions(expression);
96254             if (ts.isNumericLiteral(expression)) {
96255                 // check if numeric literal is a decimal literal that was originally written with a dot
96256                 var text = getLiteralTextOfNode(expression, /*neverAsciiEscape*/ true, /*jsxAttributeEscape*/ false);
96257                 // If he number will be printed verbatim and it doesn't already contain a dot, add one
96258                 // if the expression doesn't have any comments that will be emitted.
96259                 return !expression.numericLiteralFlags && !ts.stringContains(text, ts.tokenToString(24 /* DotToken */));
96260             }
96261             else if (ts.isAccessExpression(expression)) {
96262                 // check if constant enum value is integer
96263                 var constantValue = ts.getConstantValue(expression);
96264                 // isFinite handles cases when constantValue is undefined
96265                 return typeof constantValue === "number" && isFinite(constantValue)
96266                     && Math.floor(constantValue) === constantValue;
96267             }
96268         }
96269         function emitElementAccessExpression(node) {
96270             emitExpression(node.expression);
96271             emit(node.questionDotToken);
96272             emitTokenWithComment(22 /* OpenBracketToken */, node.expression.end, writePunctuation, node);
96273             emitExpression(node.argumentExpression);
96274             emitTokenWithComment(23 /* CloseBracketToken */, node.argumentExpression.end, writePunctuation, node);
96275         }
96276         function emitCallExpression(node) {
96277             emitExpression(node.expression);
96278             emit(node.questionDotToken);
96279             emitTypeArguments(node, node.typeArguments);
96280             emitExpressionList(node, node.arguments, 2576 /* CallExpressionArguments */);
96281         }
96282         function emitNewExpression(node) {
96283             emitTokenWithComment(99 /* NewKeyword */, node.pos, writeKeyword, node);
96284             writeSpace();
96285             emitExpression(node.expression);
96286             emitTypeArguments(node, node.typeArguments);
96287             emitExpressionList(node, node.arguments, 18960 /* NewExpressionArguments */);
96288         }
96289         function emitTaggedTemplateExpression(node) {
96290             emitExpression(node.tag);
96291             emitTypeArguments(node, node.typeArguments);
96292             writeSpace();
96293             emitExpression(node.template);
96294         }
96295         function emitTypeAssertionExpression(node) {
96296             writePunctuation("<");
96297             emit(node.type);
96298             writePunctuation(">");
96299             emitExpression(node.expression);
96300         }
96301         function emitParenthesizedExpression(node) {
96302             var openParenPos = emitTokenWithComment(20 /* OpenParenToken */, node.pos, writePunctuation, node);
96303             var indented = writeLineSeparatorsAndIndentBefore(node.expression, node);
96304             emitExpression(node.expression);
96305             writeLineSeparatorsAfter(node.expression, node);
96306             decreaseIndentIf(indented);
96307             emitTokenWithComment(21 /* CloseParenToken */, node.expression ? node.expression.end : openParenPos, writePunctuation, node);
96308         }
96309         function emitFunctionExpression(node) {
96310             generateNameIfNeeded(node.name);
96311             emitFunctionDeclarationOrExpression(node);
96312         }
96313         function emitArrowFunction(node) {
96314             emitDecorators(node, node.decorators);
96315             emitModifiers(node, node.modifiers);
96316             emitSignatureAndBody(node, emitArrowFunctionHead);
96317         }
96318         function emitArrowFunctionHead(node) {
96319             emitTypeParameters(node, node.typeParameters);
96320             emitParametersForArrow(node, node.parameters);
96321             emitTypeAnnotation(node.type);
96322             writeSpace();
96323             emit(node.equalsGreaterThanToken);
96324         }
96325         function emitDeleteExpression(node) {
96326             emitTokenWithComment(85 /* DeleteKeyword */, node.pos, writeKeyword, node);
96327             writeSpace();
96328             emitExpression(node.expression);
96329         }
96330         function emitTypeOfExpression(node) {
96331             emitTokenWithComment(108 /* TypeOfKeyword */, node.pos, writeKeyword, node);
96332             writeSpace();
96333             emitExpression(node.expression);
96334         }
96335         function emitVoidExpression(node) {
96336             emitTokenWithComment(110 /* VoidKeyword */, node.pos, writeKeyword, node);
96337             writeSpace();
96338             emitExpression(node.expression);
96339         }
96340         function emitAwaitExpression(node) {
96341             emitTokenWithComment(127 /* AwaitKeyword */, node.pos, writeKeyword, node);
96342             writeSpace();
96343             emitExpression(node.expression);
96344         }
96345         function emitPrefixUnaryExpression(node) {
96346             writeTokenText(node.operator, writeOperator);
96347             if (shouldEmitWhitespaceBeforeOperand(node)) {
96348                 writeSpace();
96349             }
96350             emitExpression(node.operand);
96351         }
96352         function shouldEmitWhitespaceBeforeOperand(node) {
96353             // In some cases, we need to emit a space between the operator and the operand. One obvious case
96354             // is when the operator is an identifier, like delete or typeof. We also need to do this for plus
96355             // and minus expressions in certain cases. Specifically, consider the following two cases (parens
96356             // are just for clarity of exposition, and not part of the source code):
96357             //
96358             //  (+(+1))
96359             //  (+(++1))
96360             //
96361             // We need to emit a space in both cases. In the first case, the absence of a space will make
96362             // the resulting expression a prefix increment operation. And in the second, it will make the resulting
96363             // expression a prefix increment whose operand is a plus expression - (++(+x))
96364             // The same is true of minus of course.
96365             var operand = node.operand;
96366             return operand.kind === 207 /* PrefixUnaryExpression */
96367                 && ((node.operator === 39 /* PlusToken */ && (operand.operator === 39 /* PlusToken */ || operand.operator === 45 /* PlusPlusToken */))
96368                     || (node.operator === 40 /* MinusToken */ && (operand.operator === 40 /* MinusToken */ || operand.operator === 46 /* MinusMinusToken */)));
96369         }
96370         function emitPostfixUnaryExpression(node) {
96371             emitExpression(node.operand);
96372             writeTokenText(node.operator, writeOperator);
96373         }
96374         var EmitBinaryExpressionState;
96375         (function (EmitBinaryExpressionState) {
96376             EmitBinaryExpressionState[EmitBinaryExpressionState["EmitLeft"] = 0] = "EmitLeft";
96377             EmitBinaryExpressionState[EmitBinaryExpressionState["EmitRight"] = 1] = "EmitRight";
96378             EmitBinaryExpressionState[EmitBinaryExpressionState["FinishEmit"] = 2] = "FinishEmit";
96379         })(EmitBinaryExpressionState || (EmitBinaryExpressionState = {}));
96380         /**
96381          * emitBinaryExpression includes an embedded work stack to attempt to handle as many nested binary expressions
96382          * as possible without creating any additional stack frames. This can only be done when the emit pipeline does
96383          * not require notification/substitution/comment/sourcemap decorations.
96384          */
96385         function emitBinaryExpression(node) {
96386             var nodeStack = [node];
96387             var stateStack = [0 /* EmitLeft */];
96388             var stackIndex = 0;
96389             while (stackIndex >= 0) {
96390                 node = nodeStack[stackIndex];
96391                 switch (stateStack[stackIndex]) {
96392                     case 0 /* EmitLeft */: {
96393                         maybePipelineEmitExpression(node.left);
96394                         break;
96395                     }
96396                     case 1 /* EmitRight */: {
96397                         var isCommaOperator = node.operatorToken.kind !== 27 /* CommaToken */;
96398                         var linesBeforeOperator = getLinesBetweenNodes(node, node.left, node.operatorToken);
96399                         var linesAfterOperator = getLinesBetweenNodes(node, node.operatorToken, node.right);
96400                         writeLinesAndIndent(linesBeforeOperator, isCommaOperator);
96401                         emitLeadingCommentsOfPosition(node.operatorToken.pos);
96402                         writeTokenNode(node.operatorToken, node.operatorToken.kind === 97 /* InKeyword */ ? writeKeyword : writeOperator);
96403                         emitTrailingCommentsOfPosition(node.operatorToken.end, /*prefixSpace*/ true); // Binary operators should have a space before the comment starts
96404                         writeLinesAndIndent(linesAfterOperator, /*writeSpaceIfNotIndenting*/ true);
96405                         maybePipelineEmitExpression(node.right);
96406                         break;
96407                     }
96408                     case 2 /* FinishEmit */: {
96409                         var linesBeforeOperator = getLinesBetweenNodes(node, node.left, node.operatorToken);
96410                         var linesAfterOperator = getLinesBetweenNodes(node, node.operatorToken, node.right);
96411                         decreaseIndentIf(linesBeforeOperator, linesAfterOperator);
96412                         stackIndex--;
96413                         break;
96414                     }
96415                     default: return ts.Debug.fail("Invalid state " + stateStack[stackIndex] + " for emitBinaryExpressionWorker");
96416                 }
96417             }
96418             function maybePipelineEmitExpression(next) {
96419                 // Advance the state of this unit of work,
96420                 stateStack[stackIndex]++;
96421                 // Then actually do the work of emitting the node `next` returned by the prior state
96422                 // The following section should be identical to `pipelineEmit` save it assumes EmitHint.Expression and offloads
96423                 // binary expression handling, where possible, to the contained work queue
96424                 // #region trampolinePipelineEmit
96425                 var savedLastNode = lastNode;
96426                 var savedLastSubstitution = lastSubstitution;
96427                 lastNode = next;
96428                 lastSubstitution = undefined;
96429                 var pipelinePhase = getPipelinePhase(0 /* Notification */, 1 /* Expression */, next);
96430                 if (pipelinePhase === pipelineEmitWithHint && ts.isBinaryExpression(next)) {
96431                     // If the target pipeline phase is emit directly, and the next node's also a binary expression,
96432                     // skip all the intermediate indirection and push the expression directly onto the work stack
96433                     stackIndex++;
96434                     stateStack[stackIndex] = 0 /* EmitLeft */;
96435                     nodeStack[stackIndex] = next;
96436                 }
96437                 else {
96438                     pipelinePhase(1 /* Expression */, next);
96439                 }
96440                 ts.Debug.assert(lastNode === next);
96441                 lastNode = savedLastNode;
96442                 lastSubstitution = savedLastSubstitution;
96443                 // #endregion trampolinePipelineEmit
96444             }
96445         }
96446         function emitConditionalExpression(node) {
96447             var linesBeforeQuestion = getLinesBetweenNodes(node, node.condition, node.questionToken);
96448             var linesAfterQuestion = getLinesBetweenNodes(node, node.questionToken, node.whenTrue);
96449             var linesBeforeColon = getLinesBetweenNodes(node, node.whenTrue, node.colonToken);
96450             var linesAfterColon = getLinesBetweenNodes(node, node.colonToken, node.whenFalse);
96451             emitExpression(node.condition);
96452             writeLinesAndIndent(linesBeforeQuestion, /*writeSpaceIfNotIndenting*/ true);
96453             emit(node.questionToken);
96454             writeLinesAndIndent(linesAfterQuestion, /*writeSpaceIfNotIndenting*/ true);
96455             emitExpression(node.whenTrue);
96456             decreaseIndentIf(linesBeforeQuestion, linesAfterQuestion);
96457             writeLinesAndIndent(linesBeforeColon, /*writeSpaceIfNotIndenting*/ true);
96458             emit(node.colonToken);
96459             writeLinesAndIndent(linesAfterColon, /*writeSpaceIfNotIndenting*/ true);
96460             emitExpression(node.whenFalse);
96461             decreaseIndentIf(linesBeforeColon, linesAfterColon);
96462         }
96463         function emitTemplateExpression(node) {
96464             emit(node.head);
96465             emitList(node, node.templateSpans, 262144 /* TemplateExpressionSpans */);
96466         }
96467         function emitYieldExpression(node) {
96468             emitTokenWithComment(121 /* YieldKeyword */, node.pos, writeKeyword, node);
96469             emit(node.asteriskToken);
96470             emitExpressionWithLeadingSpace(node.expression);
96471         }
96472         function emitSpreadExpression(node) {
96473             emitTokenWithComment(25 /* DotDotDotToken */, node.pos, writePunctuation, node);
96474             emitExpression(node.expression);
96475         }
96476         function emitClassExpression(node) {
96477             generateNameIfNeeded(node.name);
96478             emitClassDeclarationOrExpression(node);
96479         }
96480         function emitExpressionWithTypeArguments(node) {
96481             emitExpression(node.expression);
96482             emitTypeArguments(node, node.typeArguments);
96483         }
96484         function emitAsExpression(node) {
96485             emitExpression(node.expression);
96486             if (node.type) {
96487                 writeSpace();
96488                 writeKeyword("as");
96489                 writeSpace();
96490                 emit(node.type);
96491             }
96492         }
96493         function emitNonNullExpression(node) {
96494             emitExpression(node.expression);
96495             writeOperator("!");
96496         }
96497         function emitMetaProperty(node) {
96498             writeToken(node.keywordToken, node.pos, writePunctuation);
96499             writePunctuation(".");
96500             emit(node.name);
96501         }
96502         //
96503         // Misc
96504         //
96505         function emitTemplateSpan(node) {
96506             emitExpression(node.expression);
96507             emit(node.literal);
96508         }
96509         //
96510         // Statements
96511         //
96512         function emitBlock(node) {
96513             emitBlockStatements(node, /*forceSingleLine*/ !node.multiLine && isEmptyBlock(node));
96514         }
96515         function emitBlockStatements(node, forceSingleLine) {
96516             emitTokenWithComment(18 /* OpenBraceToken */, node.pos, writePunctuation, /*contextNode*/ node);
96517             var format = forceSingleLine || ts.getEmitFlags(node) & 1 /* SingleLine */ ? 768 /* SingleLineBlockStatements */ : 129 /* MultiLineBlockStatements */;
96518             emitList(node, node.statements, format);
96519             emitTokenWithComment(19 /* CloseBraceToken */, node.statements.end, writePunctuation, /*contextNode*/ node, /*indentLeading*/ !!(format & 1 /* MultiLine */));
96520         }
96521         function emitVariableStatement(node) {
96522             emitModifiers(node, node.modifiers);
96523             emit(node.declarationList);
96524             writeTrailingSemicolon();
96525         }
96526         function emitEmptyStatement(isEmbeddedStatement) {
96527             // While most trailing semicolons are possibly insignificant, an embedded "empty"
96528             // statement is significant and cannot be elided by a trailing-semicolon-omitting writer.
96529             if (isEmbeddedStatement) {
96530                 writePunctuation(";");
96531             }
96532             else {
96533                 writeTrailingSemicolon();
96534             }
96535         }
96536         function emitExpressionStatement(node) {
96537             emitExpression(node.expression);
96538             // Emit semicolon in non json files
96539             // or if json file that created synthesized expression(eg.define expression statement when --out and amd code generation)
96540             if (!ts.isJsonSourceFile(currentSourceFile) || ts.nodeIsSynthesized(node.expression)) {
96541                 writeTrailingSemicolon();
96542             }
96543         }
96544         function emitIfStatement(node) {
96545             var openParenPos = emitTokenWithComment(95 /* IfKeyword */, node.pos, writeKeyword, node);
96546             writeSpace();
96547             emitTokenWithComment(20 /* OpenParenToken */, openParenPos, writePunctuation, node);
96548             emitExpression(node.expression);
96549             emitTokenWithComment(21 /* CloseParenToken */, node.expression.end, writePunctuation, node);
96550             emitEmbeddedStatement(node, node.thenStatement);
96551             if (node.elseStatement) {
96552                 writeLineOrSpace(node);
96553                 emitTokenWithComment(87 /* ElseKeyword */, node.thenStatement.end, writeKeyword, node);
96554                 if (node.elseStatement.kind === 227 /* IfStatement */) {
96555                     writeSpace();
96556                     emit(node.elseStatement);
96557                 }
96558                 else {
96559                     emitEmbeddedStatement(node, node.elseStatement);
96560                 }
96561             }
96562         }
96563         function emitWhileClause(node, startPos) {
96564             var openParenPos = emitTokenWithComment(111 /* WhileKeyword */, startPos, writeKeyword, node);
96565             writeSpace();
96566             emitTokenWithComment(20 /* OpenParenToken */, openParenPos, writePunctuation, node);
96567             emitExpression(node.expression);
96568             emitTokenWithComment(21 /* CloseParenToken */, node.expression.end, writePunctuation, node);
96569         }
96570         function emitDoStatement(node) {
96571             emitTokenWithComment(86 /* DoKeyword */, node.pos, writeKeyword, node);
96572             emitEmbeddedStatement(node, node.statement);
96573             if (ts.isBlock(node.statement)) {
96574                 writeSpace();
96575             }
96576             else {
96577                 writeLineOrSpace(node);
96578             }
96579             emitWhileClause(node, node.statement.end);
96580             writeTrailingSemicolon();
96581         }
96582         function emitWhileStatement(node) {
96583             emitWhileClause(node, node.pos);
96584             emitEmbeddedStatement(node, node.statement);
96585         }
96586         function emitForStatement(node) {
96587             var openParenPos = emitTokenWithComment(93 /* ForKeyword */, node.pos, writeKeyword, node);
96588             writeSpace();
96589             var pos = emitTokenWithComment(20 /* OpenParenToken */, openParenPos, writePunctuation, /*contextNode*/ node);
96590             emitForBinding(node.initializer);
96591             pos = emitTokenWithComment(26 /* SemicolonToken */, node.initializer ? node.initializer.end : pos, writePunctuation, node);
96592             emitExpressionWithLeadingSpace(node.condition);
96593             pos = emitTokenWithComment(26 /* SemicolonToken */, node.condition ? node.condition.end : pos, writePunctuation, node);
96594             emitExpressionWithLeadingSpace(node.incrementor);
96595             emitTokenWithComment(21 /* CloseParenToken */, node.incrementor ? node.incrementor.end : pos, writePunctuation, node);
96596             emitEmbeddedStatement(node, node.statement);
96597         }
96598         function emitForInStatement(node) {
96599             var openParenPos = emitTokenWithComment(93 /* ForKeyword */, node.pos, writeKeyword, node);
96600             writeSpace();
96601             emitTokenWithComment(20 /* OpenParenToken */, openParenPos, writePunctuation, node);
96602             emitForBinding(node.initializer);
96603             writeSpace();
96604             emitTokenWithComment(97 /* InKeyword */, node.initializer.end, writeKeyword, node);
96605             writeSpace();
96606             emitExpression(node.expression);
96607             emitTokenWithComment(21 /* CloseParenToken */, node.expression.end, writePunctuation, node);
96608             emitEmbeddedStatement(node, node.statement);
96609         }
96610         function emitForOfStatement(node) {
96611             var openParenPos = emitTokenWithComment(93 /* ForKeyword */, node.pos, writeKeyword, node);
96612             writeSpace();
96613             emitWithTrailingSpace(node.awaitModifier);
96614             emitTokenWithComment(20 /* OpenParenToken */, openParenPos, writePunctuation, node);
96615             emitForBinding(node.initializer);
96616             writeSpace();
96617             emitTokenWithComment(152 /* OfKeyword */, node.initializer.end, writeKeyword, node);
96618             writeSpace();
96619             emitExpression(node.expression);
96620             emitTokenWithComment(21 /* CloseParenToken */, node.expression.end, writePunctuation, node);
96621             emitEmbeddedStatement(node, node.statement);
96622         }
96623         function emitForBinding(node) {
96624             if (node !== undefined) {
96625                 if (node.kind === 243 /* VariableDeclarationList */) {
96626                     emit(node);
96627                 }
96628                 else {
96629                     emitExpression(node);
96630                 }
96631             }
96632         }
96633         function emitContinueStatement(node) {
96634             emitTokenWithComment(82 /* ContinueKeyword */, node.pos, writeKeyword, node);
96635             emitWithLeadingSpace(node.label);
96636             writeTrailingSemicolon();
96637         }
96638         function emitBreakStatement(node) {
96639             emitTokenWithComment(77 /* BreakKeyword */, node.pos, writeKeyword, node);
96640             emitWithLeadingSpace(node.label);
96641             writeTrailingSemicolon();
96642         }
96643         function emitTokenWithComment(token, pos, writer, contextNode, indentLeading) {
96644             var node = ts.getParseTreeNode(contextNode);
96645             var isSimilarNode = node && node.kind === contextNode.kind;
96646             var startPos = pos;
96647             if (isSimilarNode && currentSourceFile) {
96648                 pos = ts.skipTrivia(currentSourceFile.text, pos);
96649             }
96650             if (emitLeadingCommentsOfPosition && isSimilarNode && contextNode.pos !== startPos) {
96651                 var needsIndent = indentLeading && currentSourceFile && !ts.positionsAreOnSameLine(startPos, pos, currentSourceFile);
96652                 if (needsIndent) {
96653                     increaseIndent();
96654                 }
96655                 emitLeadingCommentsOfPosition(startPos);
96656                 if (needsIndent) {
96657                     decreaseIndent();
96658                 }
96659             }
96660             pos = writeTokenText(token, writer, pos);
96661             if (emitTrailingCommentsOfPosition && isSimilarNode && contextNode.end !== pos) {
96662                 emitTrailingCommentsOfPosition(pos, /*prefixSpace*/ true);
96663             }
96664             return pos;
96665         }
96666         function emitReturnStatement(node) {
96667             emitTokenWithComment(101 /* ReturnKeyword */, node.pos, writeKeyword, /*contextNode*/ node);
96668             emitExpressionWithLeadingSpace(node.expression);
96669             writeTrailingSemicolon();
96670         }
96671         function emitWithStatement(node) {
96672             var openParenPos = emitTokenWithComment(112 /* WithKeyword */, node.pos, writeKeyword, node);
96673             writeSpace();
96674             emitTokenWithComment(20 /* OpenParenToken */, openParenPos, writePunctuation, node);
96675             emitExpression(node.expression);
96676             emitTokenWithComment(21 /* CloseParenToken */, node.expression.end, writePunctuation, node);
96677             emitEmbeddedStatement(node, node.statement);
96678         }
96679         function emitSwitchStatement(node) {
96680             var openParenPos = emitTokenWithComment(103 /* SwitchKeyword */, node.pos, writeKeyword, node);
96681             writeSpace();
96682             emitTokenWithComment(20 /* OpenParenToken */, openParenPos, writePunctuation, node);
96683             emitExpression(node.expression);
96684             emitTokenWithComment(21 /* CloseParenToken */, node.expression.end, writePunctuation, node);
96685             writeSpace();
96686             emit(node.caseBlock);
96687         }
96688         function emitLabeledStatement(node) {
96689             emit(node.label);
96690             emitTokenWithComment(58 /* ColonToken */, node.label.end, writePunctuation, node);
96691             writeSpace();
96692             emit(node.statement);
96693         }
96694         function emitThrowStatement(node) {
96695             emitTokenWithComment(105 /* ThrowKeyword */, node.pos, writeKeyword, node);
96696             emitExpressionWithLeadingSpace(node.expression);
96697             writeTrailingSemicolon();
96698         }
96699         function emitTryStatement(node) {
96700             emitTokenWithComment(107 /* TryKeyword */, node.pos, writeKeyword, node);
96701             writeSpace();
96702             emit(node.tryBlock);
96703             if (node.catchClause) {
96704                 writeLineOrSpace(node);
96705                 emit(node.catchClause);
96706             }
96707             if (node.finallyBlock) {
96708                 writeLineOrSpace(node);
96709                 emitTokenWithComment(92 /* FinallyKeyword */, (node.catchClause || node.tryBlock).end, writeKeyword, node);
96710                 writeSpace();
96711                 emit(node.finallyBlock);
96712             }
96713         }
96714         function emitDebuggerStatement(node) {
96715             writeToken(83 /* DebuggerKeyword */, node.pos, writeKeyword);
96716             writeTrailingSemicolon();
96717         }
96718         //
96719         // Declarations
96720         //
96721         function emitVariableDeclaration(node) {
96722             emit(node.name);
96723             emit(node.exclamationToken);
96724             emitTypeAnnotation(node.type);
96725             emitInitializer(node.initializer, node.type ? node.type.end : node.name.end, node);
96726         }
96727         function emitVariableDeclarationList(node) {
96728             writeKeyword(ts.isLet(node) ? "let" : ts.isVarConst(node) ? "const" : "var");
96729             writeSpace();
96730             emitList(node, node.declarations, 528 /* VariableDeclarationList */);
96731         }
96732         function emitFunctionDeclaration(node) {
96733             emitFunctionDeclarationOrExpression(node);
96734         }
96735         function emitFunctionDeclarationOrExpression(node) {
96736             emitDecorators(node, node.decorators);
96737             emitModifiers(node, node.modifiers);
96738             writeKeyword("function");
96739             emit(node.asteriskToken);
96740             writeSpace();
96741             emitIdentifierName(node.name);
96742             emitSignatureAndBody(node, emitSignatureHead);
96743         }
96744         function emitBlockCallback(_hint, body) {
96745             emitBlockFunctionBody(body);
96746         }
96747         function emitSignatureAndBody(node, emitSignatureHead) {
96748             var body = node.body;
96749             if (body) {
96750                 if (ts.isBlock(body)) {
96751                     var indentedFlag = ts.getEmitFlags(node) & 65536 /* Indented */;
96752                     if (indentedFlag) {
96753                         increaseIndent();
96754                     }
96755                     pushNameGenerationScope(node);
96756                     ts.forEach(node.parameters, generateNames);
96757                     generateNames(node.body);
96758                     emitSignatureHead(node);
96759                     if (onEmitNode) {
96760                         onEmitNode(4 /* Unspecified */, body, emitBlockCallback);
96761                     }
96762                     else {
96763                         emitBlockFunctionBody(body);
96764                     }
96765                     popNameGenerationScope(node);
96766                     if (indentedFlag) {
96767                         decreaseIndent();
96768                     }
96769                 }
96770                 else {
96771                     emitSignatureHead(node);
96772                     writeSpace();
96773                     emitExpression(body);
96774                 }
96775             }
96776             else {
96777                 emitSignatureHead(node);
96778                 writeTrailingSemicolon();
96779             }
96780         }
96781         function emitSignatureHead(node) {
96782             emitTypeParameters(node, node.typeParameters);
96783             emitParameters(node, node.parameters);
96784             emitTypeAnnotation(node.type);
96785         }
96786         function shouldEmitBlockFunctionBodyOnSingleLine(body) {
96787             // We must emit a function body as a single-line body in the following case:
96788             // * The body has NodeEmitFlags.SingleLine specified.
96789             // We must emit a function body as a multi-line body in the following cases:
96790             // * The body is explicitly marked as multi-line.
96791             // * A non-synthesized body's start and end position are on different lines.
96792             // * Any statement in the body starts on a new line.
96793             if (ts.getEmitFlags(body) & 1 /* SingleLine */) {
96794                 return true;
96795             }
96796             if (body.multiLine) {
96797                 return false;
96798             }
96799             if (!ts.nodeIsSynthesized(body) && !ts.rangeIsOnSingleLine(body, currentSourceFile)) {
96800                 return false;
96801             }
96802             if (getLeadingLineTerminatorCount(body, body.statements, 2 /* PreserveLines */)
96803                 || getClosingLineTerminatorCount(body, body.statements, 2 /* PreserveLines */)) {
96804                 return false;
96805             }
96806             var previousStatement;
96807             for (var _a = 0, _b = body.statements; _a < _b.length; _a++) {
96808                 var statement = _b[_a];
96809                 if (getSeparatingLineTerminatorCount(previousStatement, statement, 2 /* PreserveLines */) > 0) {
96810                     return false;
96811                 }
96812                 previousStatement = statement;
96813             }
96814             return true;
96815         }
96816         function emitBlockFunctionBody(body) {
96817             writeSpace();
96818             writePunctuation("{");
96819             increaseIndent();
96820             var emitBlockFunctionBody = shouldEmitBlockFunctionBodyOnSingleLine(body)
96821                 ? emitBlockFunctionBodyOnSingleLine
96822                 : emitBlockFunctionBodyWorker;
96823             if (emitBodyWithDetachedComments) {
96824                 emitBodyWithDetachedComments(body, body.statements, emitBlockFunctionBody);
96825             }
96826             else {
96827                 emitBlockFunctionBody(body);
96828             }
96829             decreaseIndent();
96830             writeToken(19 /* CloseBraceToken */, body.statements.end, writePunctuation, body);
96831         }
96832         function emitBlockFunctionBodyOnSingleLine(body) {
96833             emitBlockFunctionBodyWorker(body, /*emitBlockFunctionBodyOnSingleLine*/ true);
96834         }
96835         function emitBlockFunctionBodyWorker(body, emitBlockFunctionBodyOnSingleLine) {
96836             // Emit all the prologue directives (like "use strict").
96837             var statementOffset = emitPrologueDirectives(body.statements);
96838             var pos = writer.getTextPos();
96839             emitHelpers(body);
96840             if (statementOffset === 0 && pos === writer.getTextPos() && emitBlockFunctionBodyOnSingleLine) {
96841                 decreaseIndent();
96842                 emitList(body, body.statements, 768 /* SingleLineFunctionBodyStatements */);
96843                 increaseIndent();
96844             }
96845             else {
96846                 emitList(body, body.statements, 1 /* MultiLineFunctionBodyStatements */, statementOffset);
96847             }
96848         }
96849         function emitClassDeclaration(node) {
96850             emitClassDeclarationOrExpression(node);
96851         }
96852         function emitClassDeclarationOrExpression(node) {
96853             ts.forEach(node.members, generateMemberNames);
96854             emitDecorators(node, node.decorators);
96855             emitModifiers(node, node.modifiers);
96856             writeKeyword("class");
96857             if (node.name) {
96858                 writeSpace();
96859                 emitIdentifierName(node.name);
96860             }
96861             var indentedFlag = ts.getEmitFlags(node) & 65536 /* Indented */;
96862             if (indentedFlag) {
96863                 increaseIndent();
96864             }
96865             emitTypeParameters(node, node.typeParameters);
96866             emitList(node, node.heritageClauses, 0 /* ClassHeritageClauses */);
96867             writeSpace();
96868             writePunctuation("{");
96869             emitList(node, node.members, 129 /* ClassMembers */);
96870             writePunctuation("}");
96871             if (indentedFlag) {
96872                 decreaseIndent();
96873             }
96874         }
96875         function emitInterfaceDeclaration(node) {
96876             emitDecorators(node, node.decorators);
96877             emitModifiers(node, node.modifiers);
96878             writeKeyword("interface");
96879             writeSpace();
96880             emit(node.name);
96881             emitTypeParameters(node, node.typeParameters);
96882             emitList(node, node.heritageClauses, 512 /* HeritageClauses */);
96883             writeSpace();
96884             writePunctuation("{");
96885             emitList(node, node.members, 129 /* InterfaceMembers */);
96886             writePunctuation("}");
96887         }
96888         function emitTypeAliasDeclaration(node) {
96889             emitDecorators(node, node.decorators);
96890             emitModifiers(node, node.modifiers);
96891             writeKeyword("type");
96892             writeSpace();
96893             emit(node.name);
96894             emitTypeParameters(node, node.typeParameters);
96895             writeSpace();
96896             writePunctuation("=");
96897             writeSpace();
96898             emit(node.type);
96899             writeTrailingSemicolon();
96900         }
96901         function emitEnumDeclaration(node) {
96902             emitModifiers(node, node.modifiers);
96903             writeKeyword("enum");
96904             writeSpace();
96905             emit(node.name);
96906             writeSpace();
96907             writePunctuation("{");
96908             emitList(node, node.members, 145 /* EnumMembers */);
96909             writePunctuation("}");
96910         }
96911         function emitModuleDeclaration(node) {
96912             emitModifiers(node, node.modifiers);
96913             if (~node.flags & 1024 /* GlobalAugmentation */) {
96914                 writeKeyword(node.flags & 16 /* Namespace */ ? "namespace" : "module");
96915                 writeSpace();
96916             }
96917             emit(node.name);
96918             var body = node.body;
96919             if (!body)
96920                 return writeTrailingSemicolon();
96921             while (body.kind === 249 /* ModuleDeclaration */) {
96922                 writePunctuation(".");
96923                 emit(body.name);
96924                 body = body.body;
96925             }
96926             writeSpace();
96927             emit(body);
96928         }
96929         function emitModuleBlock(node) {
96930             pushNameGenerationScope(node);
96931             ts.forEach(node.statements, generateNames);
96932             emitBlockStatements(node, /*forceSingleLine*/ isEmptyBlock(node));
96933             popNameGenerationScope(node);
96934         }
96935         function emitCaseBlock(node) {
96936             emitTokenWithComment(18 /* OpenBraceToken */, node.pos, writePunctuation, node);
96937             emitList(node, node.clauses, 129 /* CaseBlockClauses */);
96938             emitTokenWithComment(19 /* CloseBraceToken */, node.clauses.end, writePunctuation, node, /*indentLeading*/ true);
96939         }
96940         function emitImportEqualsDeclaration(node) {
96941             emitModifiers(node, node.modifiers);
96942             emitTokenWithComment(96 /* ImportKeyword */, node.modifiers ? node.modifiers.end : node.pos, writeKeyword, node);
96943             writeSpace();
96944             emit(node.name);
96945             writeSpace();
96946             emitTokenWithComment(62 /* EqualsToken */, node.name.end, writePunctuation, node);
96947             writeSpace();
96948             emitModuleReference(node.moduleReference);
96949             writeTrailingSemicolon();
96950         }
96951         function emitModuleReference(node) {
96952             if (node.kind === 75 /* Identifier */) {
96953                 emitExpression(node);
96954             }
96955             else {
96956                 emit(node);
96957             }
96958         }
96959         function emitImportDeclaration(node) {
96960             emitModifiers(node, node.modifiers);
96961             emitTokenWithComment(96 /* ImportKeyword */, node.modifiers ? node.modifiers.end : node.pos, writeKeyword, node);
96962             writeSpace();
96963             if (node.importClause) {
96964                 emit(node.importClause);
96965                 writeSpace();
96966                 emitTokenWithComment(149 /* FromKeyword */, node.importClause.end, writeKeyword, node);
96967                 writeSpace();
96968             }
96969             emitExpression(node.moduleSpecifier);
96970             writeTrailingSemicolon();
96971         }
96972         function emitImportClause(node) {
96973             if (node.isTypeOnly) {
96974                 emitTokenWithComment(145 /* TypeKeyword */, node.pos, writeKeyword, node);
96975                 writeSpace();
96976             }
96977             emit(node.name);
96978             if (node.name && node.namedBindings) {
96979                 emitTokenWithComment(27 /* CommaToken */, node.name.end, writePunctuation, node);
96980                 writeSpace();
96981             }
96982             emit(node.namedBindings);
96983         }
96984         function emitNamespaceImport(node) {
96985             var asPos = emitTokenWithComment(41 /* AsteriskToken */, node.pos, writePunctuation, node);
96986             writeSpace();
96987             emitTokenWithComment(123 /* AsKeyword */, asPos, writeKeyword, node);
96988             writeSpace();
96989             emit(node.name);
96990         }
96991         function emitNamedImports(node) {
96992             emitNamedImportsOrExports(node);
96993         }
96994         function emitImportSpecifier(node) {
96995             emitImportOrExportSpecifier(node);
96996         }
96997         function emitExportAssignment(node) {
96998             var nextPos = emitTokenWithComment(89 /* ExportKeyword */, node.pos, writeKeyword, node);
96999             writeSpace();
97000             if (node.isExportEquals) {
97001                 emitTokenWithComment(62 /* EqualsToken */, nextPos, writeOperator, node);
97002             }
97003             else {
97004                 emitTokenWithComment(84 /* DefaultKeyword */, nextPos, writeKeyword, node);
97005             }
97006             writeSpace();
97007             emitExpression(node.expression);
97008             writeTrailingSemicolon();
97009         }
97010         function emitExportDeclaration(node) {
97011             var nextPos = emitTokenWithComment(89 /* ExportKeyword */, node.pos, writeKeyword, node);
97012             writeSpace();
97013             if (node.isTypeOnly) {
97014                 nextPos = emitTokenWithComment(145 /* TypeKeyword */, nextPos, writeKeyword, node);
97015                 writeSpace();
97016             }
97017             if (node.exportClause) {
97018                 emit(node.exportClause);
97019             }
97020             else {
97021                 nextPos = emitTokenWithComment(41 /* AsteriskToken */, nextPos, writePunctuation, node);
97022             }
97023             if (node.moduleSpecifier) {
97024                 writeSpace();
97025                 var fromPos = node.exportClause ? node.exportClause.end : nextPos;
97026                 emitTokenWithComment(149 /* FromKeyword */, fromPos, writeKeyword, node);
97027                 writeSpace();
97028                 emitExpression(node.moduleSpecifier);
97029             }
97030             writeTrailingSemicolon();
97031         }
97032         function emitNamespaceExportDeclaration(node) {
97033             var nextPos = emitTokenWithComment(89 /* ExportKeyword */, node.pos, writeKeyword, node);
97034             writeSpace();
97035             nextPos = emitTokenWithComment(123 /* AsKeyword */, nextPos, writeKeyword, node);
97036             writeSpace();
97037             nextPos = emitTokenWithComment(136 /* NamespaceKeyword */, nextPos, writeKeyword, node);
97038             writeSpace();
97039             emit(node.name);
97040             writeTrailingSemicolon();
97041         }
97042         function emitNamespaceExport(node) {
97043             var asPos = emitTokenWithComment(41 /* AsteriskToken */, node.pos, writePunctuation, node);
97044             writeSpace();
97045             emitTokenWithComment(123 /* AsKeyword */, asPos, writeKeyword, node);
97046             writeSpace();
97047             emit(node.name);
97048         }
97049         function emitNamedExports(node) {
97050             emitNamedImportsOrExports(node);
97051         }
97052         function emitExportSpecifier(node) {
97053             emitImportOrExportSpecifier(node);
97054         }
97055         function emitNamedImportsOrExports(node) {
97056             writePunctuation("{");
97057             emitList(node, node.elements, 525136 /* NamedImportsOrExportsElements */);
97058             writePunctuation("}");
97059         }
97060         function emitImportOrExportSpecifier(node) {
97061             if (node.propertyName) {
97062                 emit(node.propertyName);
97063                 writeSpace();
97064                 emitTokenWithComment(123 /* AsKeyword */, node.propertyName.end, writeKeyword, node);
97065                 writeSpace();
97066             }
97067             emit(node.name);
97068         }
97069         //
97070         // Module references
97071         //
97072         function emitExternalModuleReference(node) {
97073             writeKeyword("require");
97074             writePunctuation("(");
97075             emitExpression(node.expression);
97076             writePunctuation(")");
97077         }
97078         //
97079         // JSX
97080         //
97081         function emitJsxElement(node) {
97082             emit(node.openingElement);
97083             emitList(node, node.children, 262144 /* JsxElementOrFragmentChildren */);
97084             emit(node.closingElement);
97085         }
97086         function emitJsxSelfClosingElement(node) {
97087             writePunctuation("<");
97088             emitJsxTagName(node.tagName);
97089             emitTypeArguments(node, node.typeArguments);
97090             writeSpace();
97091             emit(node.attributes);
97092             writePunctuation("/>");
97093         }
97094         function emitJsxFragment(node) {
97095             emit(node.openingFragment);
97096             emitList(node, node.children, 262144 /* JsxElementOrFragmentChildren */);
97097             emit(node.closingFragment);
97098         }
97099         function emitJsxOpeningElementOrFragment(node) {
97100             writePunctuation("<");
97101             if (ts.isJsxOpeningElement(node)) {
97102                 var indented = writeLineSeparatorsAndIndentBefore(node.tagName, node);
97103                 emitJsxTagName(node.tagName);
97104                 emitTypeArguments(node, node.typeArguments);
97105                 if (node.attributes.properties && node.attributes.properties.length > 0) {
97106                     writeSpace();
97107                 }
97108                 emit(node.attributes);
97109                 writeLineSeparatorsAfter(node.attributes, node);
97110                 decreaseIndentIf(indented);
97111             }
97112             writePunctuation(">");
97113         }
97114         function emitJsxText(node) {
97115             writer.writeLiteral(node.text);
97116         }
97117         function emitJsxClosingElementOrFragment(node) {
97118             writePunctuation("</");
97119             if (ts.isJsxClosingElement(node)) {
97120                 emitJsxTagName(node.tagName);
97121             }
97122             writePunctuation(">");
97123         }
97124         function emitJsxAttributes(node) {
97125             emitList(node, node.properties, 262656 /* JsxElementAttributes */);
97126         }
97127         function emitJsxAttribute(node) {
97128             emit(node.name);
97129             emitNodeWithPrefix("=", writePunctuation, node.initializer, emitJsxAttributeValue);
97130         }
97131         function emitJsxSpreadAttribute(node) {
97132             writePunctuation("{...");
97133             emitExpression(node.expression);
97134             writePunctuation("}");
97135         }
97136         function emitJsxExpression(node) {
97137             if (node.expression) {
97138                 writePunctuation("{");
97139                 emit(node.dotDotDotToken);
97140                 emitExpression(node.expression);
97141                 writePunctuation("}");
97142             }
97143         }
97144         function emitJsxTagName(node) {
97145             if (node.kind === 75 /* Identifier */) {
97146                 emitExpression(node);
97147             }
97148             else {
97149                 emit(node);
97150             }
97151         }
97152         //
97153         // Clauses
97154         //
97155         function emitCaseClause(node) {
97156             emitTokenWithComment(78 /* CaseKeyword */, node.pos, writeKeyword, node);
97157             writeSpace();
97158             emitExpression(node.expression);
97159             emitCaseOrDefaultClauseRest(node, node.statements, node.expression.end);
97160         }
97161         function emitDefaultClause(node) {
97162             var pos = emitTokenWithComment(84 /* DefaultKeyword */, node.pos, writeKeyword, node);
97163             emitCaseOrDefaultClauseRest(node, node.statements, pos);
97164         }
97165         function emitCaseOrDefaultClauseRest(parentNode, statements, colonPos) {
97166             var emitAsSingleStatement = statements.length === 1 &&
97167                 (
97168                 // treat synthesized nodes as located on the same line for emit purposes
97169                 ts.nodeIsSynthesized(parentNode) ||
97170                     ts.nodeIsSynthesized(statements[0]) ||
97171                     ts.rangeStartPositionsAreOnSameLine(parentNode, statements[0], currentSourceFile));
97172             var format = 163969 /* CaseOrDefaultClauseStatements */;
97173             if (emitAsSingleStatement) {
97174                 writeToken(58 /* ColonToken */, colonPos, writePunctuation, parentNode);
97175                 writeSpace();
97176                 format &= ~(1 /* MultiLine */ | 128 /* Indented */);
97177             }
97178             else {
97179                 emitTokenWithComment(58 /* ColonToken */, colonPos, writePunctuation, parentNode);
97180             }
97181             emitList(parentNode, statements, format);
97182         }
97183         function emitHeritageClause(node) {
97184             writeSpace();
97185             writeTokenText(node.token, writeKeyword);
97186             writeSpace();
97187             emitList(node, node.types, 528 /* HeritageClauseTypes */);
97188         }
97189         function emitCatchClause(node) {
97190             var openParenPos = emitTokenWithComment(79 /* CatchKeyword */, node.pos, writeKeyword, node);
97191             writeSpace();
97192             if (node.variableDeclaration) {
97193                 emitTokenWithComment(20 /* OpenParenToken */, openParenPos, writePunctuation, node);
97194                 emit(node.variableDeclaration);
97195                 emitTokenWithComment(21 /* CloseParenToken */, node.variableDeclaration.end, writePunctuation, node);
97196                 writeSpace();
97197             }
97198             emit(node.block);
97199         }
97200         //
97201         // Property assignments
97202         //
97203         function emitPropertyAssignment(node) {
97204             emit(node.name);
97205             writePunctuation(":");
97206             writeSpace();
97207             // This is to ensure that we emit comment in the following case:
97208             //      For example:
97209             //          obj = {
97210             //              id: /*comment1*/ ()=>void
97211             //          }
97212             // "comment1" is not considered to be leading comment for node.initializer
97213             // but rather a trailing comment on the previous node.
97214             var initializer = node.initializer;
97215             if (emitTrailingCommentsOfPosition && (ts.getEmitFlags(initializer) & 512 /* NoLeadingComments */) === 0) {
97216                 var commentRange = ts.getCommentRange(initializer);
97217                 emitTrailingCommentsOfPosition(commentRange.pos);
97218             }
97219             emitExpression(initializer);
97220         }
97221         function emitShorthandPropertyAssignment(node) {
97222             emit(node.name);
97223             if (node.objectAssignmentInitializer) {
97224                 writeSpace();
97225                 writePunctuation("=");
97226                 writeSpace();
97227                 emitExpression(node.objectAssignmentInitializer);
97228             }
97229         }
97230         function emitSpreadAssignment(node) {
97231             if (node.expression) {
97232                 emitTokenWithComment(25 /* DotDotDotToken */, node.pos, writePunctuation, node);
97233                 emitExpression(node.expression);
97234             }
97235         }
97236         //
97237         // Enum
97238         //
97239         function emitEnumMember(node) {
97240             emit(node.name);
97241             emitInitializer(node.initializer, node.name.end, node);
97242         }
97243         //
97244         // JSDoc
97245         //
97246         function emitJSDoc(node) {
97247             write("/**");
97248             if (node.comment) {
97249                 var lines = node.comment.split(/\r\n?|\n/g);
97250                 for (var _a = 0, lines_2 = lines; _a < lines_2.length; _a++) {
97251                     var line = lines_2[_a];
97252                     writeLine();
97253                     writeSpace();
97254                     writePunctuation("*");
97255                     writeSpace();
97256                     write(line);
97257                 }
97258             }
97259             if (node.tags) {
97260                 if (node.tags.length === 1 && node.tags[0].kind === 320 /* JSDocTypeTag */ && !node.comment) {
97261                     writeSpace();
97262                     emit(node.tags[0]);
97263                 }
97264                 else {
97265                     emitList(node, node.tags, 33 /* JSDocComment */);
97266                 }
97267             }
97268             writeSpace();
97269             write("*/");
97270         }
97271         function emitJSDocSimpleTypedTag(tag) {
97272             emitJSDocTagName(tag.tagName);
97273             emitJSDocTypeExpression(tag.typeExpression);
97274             emitJSDocComment(tag.comment);
97275         }
97276         function emitJSDocHeritageTag(tag) {
97277             emitJSDocTagName(tag.tagName);
97278             writeSpace();
97279             writePunctuation("{");
97280             emit(tag.class);
97281             writePunctuation("}");
97282             emitJSDocComment(tag.comment);
97283         }
97284         function emitJSDocTemplateTag(tag) {
97285             emitJSDocTagName(tag.tagName);
97286             emitJSDocTypeExpression(tag.constraint);
97287             writeSpace();
97288             emitList(tag, tag.typeParameters, 528 /* CommaListElements */);
97289             emitJSDocComment(tag.comment);
97290         }
97291         function emitJSDocTypedefTag(tag) {
97292             emitJSDocTagName(tag.tagName);
97293             if (tag.typeExpression) {
97294                 if (tag.typeExpression.kind === 294 /* JSDocTypeExpression */) {
97295                     emitJSDocTypeExpression(tag.typeExpression);
97296                 }
97297                 else {
97298                     writeSpace();
97299                     writePunctuation("{");
97300                     write("Object");
97301                     if (tag.typeExpression.isArrayType) {
97302                         writePunctuation("[");
97303                         writePunctuation("]");
97304                     }
97305                     writePunctuation("}");
97306                 }
97307             }
97308             if (tag.fullName) {
97309                 writeSpace();
97310                 emit(tag.fullName);
97311             }
97312             emitJSDocComment(tag.comment);
97313             if (tag.typeExpression && tag.typeExpression.kind === 304 /* JSDocTypeLiteral */) {
97314                 emitJSDocTypeLiteral(tag.typeExpression);
97315             }
97316         }
97317         function emitJSDocCallbackTag(tag) {
97318             emitJSDocTagName(tag.tagName);
97319             if (tag.name) {
97320                 writeSpace();
97321                 emit(tag.name);
97322             }
97323             emitJSDocComment(tag.comment);
97324             emitJSDocSignature(tag.typeExpression);
97325         }
97326         function emitJSDocSimpleTag(tag) {
97327             emitJSDocTagName(tag.tagName);
97328             emitJSDocComment(tag.comment);
97329         }
97330         function emitJSDocTypeLiteral(lit) {
97331             emitList(lit, ts.createNodeArray(lit.jsDocPropertyTags), 33 /* JSDocComment */);
97332         }
97333         function emitJSDocSignature(sig) {
97334             if (sig.typeParameters) {
97335                 emitList(sig, ts.createNodeArray(sig.typeParameters), 33 /* JSDocComment */);
97336             }
97337             if (sig.parameters) {
97338                 emitList(sig, ts.createNodeArray(sig.parameters), 33 /* JSDocComment */);
97339             }
97340             if (sig.type) {
97341                 writeLine();
97342                 writeSpace();
97343                 writePunctuation("*");
97344                 writeSpace();
97345                 emit(sig.type);
97346             }
97347         }
97348         function emitJSDocPropertyLikeTag(param) {
97349             emitJSDocTagName(param.tagName);
97350             emitJSDocTypeExpression(param.typeExpression);
97351             writeSpace();
97352             if (param.isBracketed) {
97353                 writePunctuation("[");
97354             }
97355             emit(param.name);
97356             if (param.isBracketed) {
97357                 writePunctuation("]");
97358             }
97359             emitJSDocComment(param.comment);
97360         }
97361         function emitJSDocTagName(tagName) {
97362             writePunctuation("@");
97363             emit(tagName);
97364         }
97365         function emitJSDocComment(comment) {
97366             if (comment) {
97367                 writeSpace();
97368                 write(comment);
97369             }
97370         }
97371         function emitJSDocTypeExpression(typeExpression) {
97372             if (typeExpression) {
97373                 writeSpace();
97374                 writePunctuation("{");
97375                 emit(typeExpression.type);
97376                 writePunctuation("}");
97377             }
97378         }
97379         //
97380         // Top-level nodes
97381         //
97382         function emitSourceFile(node) {
97383             writeLine();
97384             var statements = node.statements;
97385             if (emitBodyWithDetachedComments) {
97386                 // Emit detached comment if there are no prologue directives or if the first node is synthesized.
97387                 // The synthesized node will have no leading comment so some comments may be missed.
97388                 var shouldEmitDetachedComment = statements.length === 0 ||
97389                     !ts.isPrologueDirective(statements[0]) ||
97390                     ts.nodeIsSynthesized(statements[0]);
97391                 if (shouldEmitDetachedComment) {
97392                     emitBodyWithDetachedComments(node, statements, emitSourceFileWorker);
97393                     return;
97394                 }
97395             }
97396             emitSourceFileWorker(node);
97397         }
97398         function emitSyntheticTripleSlashReferencesIfNeeded(node) {
97399             emitTripleSlashDirectives(!!node.hasNoDefaultLib, node.syntheticFileReferences || [], node.syntheticTypeReferences || [], node.syntheticLibReferences || []);
97400             for (var _a = 0, _b = node.prepends; _a < _b.length; _a++) {
97401                 var prepend = _b[_a];
97402                 if (ts.isUnparsedSource(prepend) && prepend.syntheticReferences) {
97403                     for (var _c = 0, _d = prepend.syntheticReferences; _c < _d.length; _c++) {
97404                         var ref = _d[_c];
97405                         emit(ref);
97406                         writeLine();
97407                     }
97408                 }
97409             }
97410         }
97411         function emitTripleSlashDirectivesIfNeeded(node) {
97412             if (node.isDeclarationFile)
97413                 emitTripleSlashDirectives(node.hasNoDefaultLib, node.referencedFiles, node.typeReferenceDirectives, node.libReferenceDirectives);
97414         }
97415         function emitTripleSlashDirectives(hasNoDefaultLib, files, types, libs) {
97416             if (hasNoDefaultLib) {
97417                 var pos = writer.getTextPos();
97418                 writeComment("/// <reference no-default-lib=\"true\"/>");
97419                 if (bundleFileInfo)
97420                     bundleFileInfo.sections.push({ pos: pos, end: writer.getTextPos(), kind: "no-default-lib" /* NoDefaultLib */ });
97421                 writeLine();
97422             }
97423             if (currentSourceFile && currentSourceFile.moduleName) {
97424                 writeComment("/// <amd-module name=\"" + currentSourceFile.moduleName + "\" />");
97425                 writeLine();
97426             }
97427             if (currentSourceFile && currentSourceFile.amdDependencies) {
97428                 for (var _a = 0, _b = currentSourceFile.amdDependencies; _a < _b.length; _a++) {
97429                     var dep = _b[_a];
97430                     if (dep.name) {
97431                         writeComment("/// <amd-dependency name=\"" + dep.name + "\" path=\"" + dep.path + "\" />");
97432                     }
97433                     else {
97434                         writeComment("/// <amd-dependency path=\"" + dep.path + "\" />");
97435                     }
97436                     writeLine();
97437                 }
97438             }
97439             for (var _c = 0, files_1 = files; _c < files_1.length; _c++) {
97440                 var directive = files_1[_c];
97441                 var pos = writer.getTextPos();
97442                 writeComment("/// <reference path=\"" + directive.fileName + "\" />");
97443                 if (bundleFileInfo)
97444                     bundleFileInfo.sections.push({ pos: pos, end: writer.getTextPos(), kind: "reference" /* Reference */, data: directive.fileName });
97445                 writeLine();
97446             }
97447             for (var _d = 0, types_22 = types; _d < types_22.length; _d++) {
97448                 var directive = types_22[_d];
97449                 var pos = writer.getTextPos();
97450                 writeComment("/// <reference types=\"" + directive.fileName + "\" />");
97451                 if (bundleFileInfo)
97452                     bundleFileInfo.sections.push({ pos: pos, end: writer.getTextPos(), kind: "type" /* Type */, data: directive.fileName });
97453                 writeLine();
97454             }
97455             for (var _e = 0, libs_1 = libs; _e < libs_1.length; _e++) {
97456                 var directive = libs_1[_e];
97457                 var pos = writer.getTextPos();
97458                 writeComment("/// <reference lib=\"" + directive.fileName + "\" />");
97459                 if (bundleFileInfo)
97460                     bundleFileInfo.sections.push({ pos: pos, end: writer.getTextPos(), kind: "lib" /* Lib */, data: directive.fileName });
97461                 writeLine();
97462             }
97463         }
97464         function emitSourceFileWorker(node) {
97465             var statements = node.statements;
97466             pushNameGenerationScope(node);
97467             ts.forEach(node.statements, generateNames);
97468             emitHelpers(node);
97469             var index = ts.findIndex(statements, function (statement) { return !ts.isPrologueDirective(statement); });
97470             emitTripleSlashDirectivesIfNeeded(node);
97471             emitList(node, statements, 1 /* MultiLine */, index === -1 ? statements.length : index);
97472             popNameGenerationScope(node);
97473         }
97474         // Transformation nodes
97475         function emitPartiallyEmittedExpression(node) {
97476             emitExpression(node.expression);
97477         }
97478         function emitCommaList(node) {
97479             emitExpressionList(node, node.elements, 528 /* CommaListElements */);
97480         }
97481         /**
97482          * Emits any prologue directives at the start of a Statement list, returning the
97483          * number of prologue directives written to the output.
97484          */
97485         function emitPrologueDirectives(statements, sourceFile, seenPrologueDirectives, recordBundleFileSection) {
97486             var needsToSetSourceFile = !!sourceFile;
97487             for (var i = 0; i < statements.length; i++) {
97488                 var statement = statements[i];
97489                 if (ts.isPrologueDirective(statement)) {
97490                     var shouldEmitPrologueDirective = seenPrologueDirectives ? !seenPrologueDirectives.has(statement.expression.text) : true;
97491                     if (shouldEmitPrologueDirective) {
97492                         if (needsToSetSourceFile) {
97493                             needsToSetSourceFile = false;
97494                             setSourceFile(sourceFile);
97495                         }
97496                         writeLine();
97497                         var pos = writer.getTextPos();
97498                         emit(statement);
97499                         if (recordBundleFileSection && bundleFileInfo)
97500                             bundleFileInfo.sections.push({ pos: pos, end: writer.getTextPos(), kind: "prologue" /* Prologue */, data: statement.expression.text });
97501                         if (seenPrologueDirectives) {
97502                             seenPrologueDirectives.set(statement.expression.text, true);
97503                         }
97504                     }
97505                 }
97506                 else {
97507                     // return index of the first non prologue directive
97508                     return i;
97509                 }
97510             }
97511             return statements.length;
97512         }
97513         function emitUnparsedPrologues(prologues, seenPrologueDirectives) {
97514             for (var _a = 0, prologues_1 = prologues; _a < prologues_1.length; _a++) {
97515                 var prologue = prologues_1[_a];
97516                 if (!seenPrologueDirectives.has(prologue.data)) {
97517                     writeLine();
97518                     var pos = writer.getTextPos();
97519                     emit(prologue);
97520                     if (bundleFileInfo)
97521                         bundleFileInfo.sections.push({ pos: pos, end: writer.getTextPos(), kind: "prologue" /* Prologue */, data: prologue.data });
97522                     if (seenPrologueDirectives) {
97523                         seenPrologueDirectives.set(prologue.data, true);
97524                     }
97525                 }
97526             }
97527         }
97528         function emitPrologueDirectivesIfNeeded(sourceFileOrBundle) {
97529             if (ts.isSourceFile(sourceFileOrBundle)) {
97530                 emitPrologueDirectives(sourceFileOrBundle.statements, sourceFileOrBundle);
97531             }
97532             else {
97533                 var seenPrologueDirectives = ts.createMap();
97534                 for (var _a = 0, _b = sourceFileOrBundle.prepends; _a < _b.length; _a++) {
97535                     var prepend = _b[_a];
97536                     emitUnparsedPrologues(prepend.prologues, seenPrologueDirectives);
97537                 }
97538                 for (var _c = 0, _d = sourceFileOrBundle.sourceFiles; _c < _d.length; _c++) {
97539                     var sourceFile = _d[_c];
97540                     emitPrologueDirectives(sourceFile.statements, sourceFile, seenPrologueDirectives, /*recordBundleFileSection*/ true);
97541                 }
97542                 setSourceFile(undefined);
97543             }
97544         }
97545         function getPrologueDirectivesFromBundledSourceFiles(bundle) {
97546             var seenPrologueDirectives = ts.createMap();
97547             var prologues;
97548             for (var index = 0; index < bundle.sourceFiles.length; index++) {
97549                 var sourceFile = bundle.sourceFiles[index];
97550                 var directives = void 0;
97551                 var end = 0;
97552                 for (var _a = 0, _b = sourceFile.statements; _a < _b.length; _a++) {
97553                     var statement = _b[_a];
97554                     if (!ts.isPrologueDirective(statement))
97555                         break;
97556                     if (seenPrologueDirectives.has(statement.expression.text))
97557                         continue;
97558                     seenPrologueDirectives.set(statement.expression.text, true);
97559                     (directives || (directives = [])).push({
97560                         pos: statement.pos,
97561                         end: statement.end,
97562                         expression: {
97563                             pos: statement.expression.pos,
97564                             end: statement.expression.end,
97565                             text: statement.expression.text
97566                         }
97567                     });
97568                     end = end < statement.end ? statement.end : end;
97569                 }
97570                 if (directives)
97571                     (prologues || (prologues = [])).push({ file: index, text: sourceFile.text.substring(0, end), directives: directives });
97572             }
97573             return prologues;
97574         }
97575         function emitShebangIfNeeded(sourceFileOrBundle) {
97576             if (ts.isSourceFile(sourceFileOrBundle) || ts.isUnparsedSource(sourceFileOrBundle)) {
97577                 var shebang = ts.getShebang(sourceFileOrBundle.text);
97578                 if (shebang) {
97579                     writeComment(shebang);
97580                     writeLine();
97581                     return true;
97582                 }
97583             }
97584             else {
97585                 for (var _a = 0, _b = sourceFileOrBundle.prepends; _a < _b.length; _a++) {
97586                     var prepend = _b[_a];
97587                     ts.Debug.assertNode(prepend, ts.isUnparsedSource);
97588                     if (emitShebangIfNeeded(prepend)) {
97589                         return true;
97590                     }
97591                 }
97592                 for (var _c = 0, _d = sourceFileOrBundle.sourceFiles; _c < _d.length; _c++) {
97593                     var sourceFile = _d[_c];
97594                     // Emit only the first encountered shebang
97595                     if (emitShebangIfNeeded(sourceFile)) {
97596                         return true;
97597                     }
97598                 }
97599             }
97600         }
97601         //
97602         // Helpers
97603         //
97604         function emitNodeWithWriter(node, writer) {
97605             if (!node)
97606                 return;
97607             var savedWrite = write;
97608             write = writer;
97609             emit(node);
97610             write = savedWrite;
97611         }
97612         function emitModifiers(node, modifiers) {
97613             if (modifiers && modifiers.length) {
97614                 emitList(node, modifiers, 262656 /* Modifiers */);
97615                 writeSpace();
97616             }
97617         }
97618         function emitTypeAnnotation(node) {
97619             if (node) {
97620                 writePunctuation(":");
97621                 writeSpace();
97622                 emit(node);
97623             }
97624         }
97625         function emitInitializer(node, equalCommentStartPos, container) {
97626             if (node) {
97627                 writeSpace();
97628                 emitTokenWithComment(62 /* EqualsToken */, equalCommentStartPos, writeOperator, container);
97629                 writeSpace();
97630                 emitExpression(node);
97631             }
97632         }
97633         function emitNodeWithPrefix(prefix, prefixWriter, node, emit) {
97634             if (node) {
97635                 prefixWriter(prefix);
97636                 emit(node);
97637             }
97638         }
97639         function emitWithLeadingSpace(node) {
97640             if (node) {
97641                 writeSpace();
97642                 emit(node);
97643             }
97644         }
97645         function emitExpressionWithLeadingSpace(node) {
97646             if (node) {
97647                 writeSpace();
97648                 emitExpression(node);
97649             }
97650         }
97651         function emitWithTrailingSpace(node) {
97652             if (node) {
97653                 emit(node);
97654                 writeSpace();
97655             }
97656         }
97657         function emitEmbeddedStatement(parent, node) {
97658             if (ts.isBlock(node) || ts.getEmitFlags(parent) & 1 /* SingleLine */) {
97659                 writeSpace();
97660                 emit(node);
97661             }
97662             else {
97663                 writeLine();
97664                 increaseIndent();
97665                 if (ts.isEmptyStatement(node)) {
97666                     pipelineEmit(5 /* EmbeddedStatement */, node);
97667                 }
97668                 else {
97669                     emit(node);
97670                 }
97671                 decreaseIndent();
97672             }
97673         }
97674         function emitDecorators(parentNode, decorators) {
97675             emitList(parentNode, decorators, 2146305 /* Decorators */);
97676         }
97677         function emitTypeArguments(parentNode, typeArguments) {
97678             emitList(parentNode, typeArguments, 53776 /* TypeArguments */);
97679         }
97680         function emitTypeParameters(parentNode, typeParameters) {
97681             if (ts.isFunctionLike(parentNode) && parentNode.typeArguments) { // Quick info uses type arguments in place of type parameters on instantiated signatures
97682                 return emitTypeArguments(parentNode, parentNode.typeArguments);
97683             }
97684             emitList(parentNode, typeParameters, 53776 /* TypeParameters */);
97685         }
97686         function emitParameters(parentNode, parameters) {
97687             emitList(parentNode, parameters, 2576 /* Parameters */);
97688         }
97689         function canEmitSimpleArrowHead(parentNode, parameters) {
97690             var parameter = ts.singleOrUndefined(parameters);
97691             return parameter
97692                 && parameter.pos === parentNode.pos // may not have parsed tokens between parent and parameter
97693                 && ts.isArrowFunction(parentNode) // only arrow functions may have simple arrow head
97694                 && !parentNode.type // arrow function may not have return type annotation
97695                 && !ts.some(parentNode.decorators) // parent may not have decorators
97696                 && !ts.some(parentNode.modifiers) // parent may not have modifiers
97697                 && !ts.some(parentNode.typeParameters) // parent may not have type parameters
97698                 && !ts.some(parameter.decorators) // parameter may not have decorators
97699                 && !ts.some(parameter.modifiers) // parameter may not have modifiers
97700                 && !parameter.dotDotDotToken // parameter may not be rest
97701                 && !parameter.questionToken // parameter may not be optional
97702                 && !parameter.type // parameter may not have a type annotation
97703                 && !parameter.initializer // parameter may not have an initializer
97704                 && ts.isIdentifier(parameter.name); // parameter name must be identifier
97705         }
97706         function emitParametersForArrow(parentNode, parameters) {
97707             if (canEmitSimpleArrowHead(parentNode, parameters)) {
97708                 emitList(parentNode, parameters, 2576 /* Parameters */ & ~2048 /* Parenthesis */);
97709             }
97710             else {
97711                 emitParameters(parentNode, parameters);
97712             }
97713         }
97714         function emitParametersForIndexSignature(parentNode, parameters) {
97715             emitList(parentNode, parameters, 8848 /* IndexSignatureParameters */);
97716         }
97717         function emitList(parentNode, children, format, start, count) {
97718             emitNodeList(emit, parentNode, children, format, start, count);
97719         }
97720         function emitExpressionList(parentNode, children, format, start, count) {
97721             emitNodeList(emitExpression, parentNode, children, format, start, count); // TODO: GH#18217
97722         }
97723         function writeDelimiter(format) {
97724             switch (format & 60 /* DelimitersMask */) {
97725                 case 0 /* None */:
97726                     break;
97727                 case 16 /* CommaDelimited */:
97728                     writePunctuation(",");
97729                     break;
97730                 case 4 /* BarDelimited */:
97731                     writeSpace();
97732                     writePunctuation("|");
97733                     break;
97734                 case 32 /* AsteriskDelimited */:
97735                     writeSpace();
97736                     writePunctuation("*");
97737                     writeSpace();
97738                     break;
97739                 case 8 /* AmpersandDelimited */:
97740                     writeSpace();
97741                     writePunctuation("&");
97742                     break;
97743             }
97744         }
97745         function emitNodeList(emit, parentNode, children, format, start, count) {
97746             if (start === void 0) { start = 0; }
97747             if (count === void 0) { count = children ? children.length - start : 0; }
97748             var isUndefined = children === undefined;
97749             if (isUndefined && format & 16384 /* OptionalIfUndefined */) {
97750                 return;
97751             }
97752             var isEmpty = children === undefined || start >= children.length || count === 0;
97753             if (isEmpty && format & 32768 /* OptionalIfEmpty */) {
97754                 if (onBeforeEmitNodeArray) {
97755                     onBeforeEmitNodeArray(children);
97756                 }
97757                 if (onAfterEmitNodeArray) {
97758                     onAfterEmitNodeArray(children);
97759                 }
97760                 return;
97761             }
97762             if (format & 15360 /* BracketsMask */) {
97763                 writePunctuation(getOpeningBracket(format));
97764                 if (isEmpty && !isUndefined) {
97765                     // TODO: GH#18217
97766                     emitTrailingCommentsOfPosition(children.pos, /*prefixSpace*/ true); // Emit comments within empty bracketed lists
97767                 }
97768             }
97769             if (onBeforeEmitNodeArray) {
97770                 onBeforeEmitNodeArray(children);
97771             }
97772             if (isEmpty) {
97773                 // Write a line terminator if the parent node was multi-line
97774                 if (format & 1 /* MultiLine */ && !(preserveSourceNewlines && ts.rangeIsOnSingleLine(parentNode, currentSourceFile))) {
97775                     writeLine();
97776                 }
97777                 else if (format & 256 /* SpaceBetweenBraces */ && !(format & 524288 /* NoSpaceIfEmpty */)) {
97778                     writeSpace();
97779                 }
97780             }
97781             else {
97782                 // Write the opening line terminator or leading whitespace.
97783                 var mayEmitInterveningComments = (format & 262144 /* NoInterveningComments */) === 0;
97784                 var shouldEmitInterveningComments = mayEmitInterveningComments;
97785                 var leadingLineTerminatorCount = getLeadingLineTerminatorCount(parentNode, children, format); // TODO: GH#18217
97786                 if (leadingLineTerminatorCount) {
97787                     writeLine(leadingLineTerminatorCount);
97788                     shouldEmitInterveningComments = false;
97789                 }
97790                 else if (format & 256 /* SpaceBetweenBraces */) {
97791                     writeSpace();
97792                 }
97793                 // Increase the indent, if requested.
97794                 if (format & 128 /* Indented */) {
97795                     increaseIndent();
97796                 }
97797                 // Emit each child.
97798                 var previousSibling = void 0;
97799                 var previousSourceFileTextKind = void 0;
97800                 var shouldDecreaseIndentAfterEmit = false;
97801                 for (var i = 0; i < count; i++) {
97802                     var child = children[start + i];
97803                     // Write the delimiter if this is not the first node.
97804                     if (format & 32 /* AsteriskDelimited */) {
97805                         // always write JSDoc in the format "\n *"
97806                         writeLine();
97807                         writeDelimiter(format);
97808                     }
97809                     else if (previousSibling) {
97810                         // i.e
97811                         //      function commentedParameters(
97812                         //          /* Parameter a */
97813                         //          a
97814                         //          /* End of parameter a */ -> this comment isn't considered to be trailing comment of parameter "a" due to newline
97815                         //          ,
97816                         if (format & 60 /* DelimitersMask */ && previousSibling.end !== parentNode.end) {
97817                             emitLeadingCommentsOfPosition(previousSibling.end);
97818                         }
97819                         writeDelimiter(format);
97820                         recordBundleFileInternalSectionEnd(previousSourceFileTextKind);
97821                         // Write either a line terminator or whitespace to separate the elements.
97822                         var separatingLineTerminatorCount = getSeparatingLineTerminatorCount(previousSibling, child, format);
97823                         if (separatingLineTerminatorCount > 0) {
97824                             // If a synthesized node in a single-line list starts on a new
97825                             // line, we should increase the indent.
97826                             if ((format & (3 /* LinesMask */ | 128 /* Indented */)) === 0 /* SingleLine */) {
97827                                 increaseIndent();
97828                                 shouldDecreaseIndentAfterEmit = true;
97829                             }
97830                             writeLine(separatingLineTerminatorCount);
97831                             shouldEmitInterveningComments = false;
97832                         }
97833                         else if (previousSibling && format & 512 /* SpaceBetweenSiblings */) {
97834                             writeSpace();
97835                         }
97836                     }
97837                     // Emit this child.
97838                     previousSourceFileTextKind = recordBundleFileInternalSectionStart(child);
97839                     if (shouldEmitInterveningComments) {
97840                         if (emitTrailingCommentsOfPosition) {
97841                             var commentRange = ts.getCommentRange(child);
97842                             emitTrailingCommentsOfPosition(commentRange.pos);
97843                         }
97844                     }
97845                     else {
97846                         shouldEmitInterveningComments = mayEmitInterveningComments;
97847                     }
97848                     emit(child);
97849                     if (shouldDecreaseIndentAfterEmit) {
97850                         decreaseIndent();
97851                         shouldDecreaseIndentAfterEmit = false;
97852                     }
97853                     previousSibling = child;
97854                 }
97855                 // Write a trailing comma, if requested.
97856                 var hasTrailingComma = (format & 64 /* AllowTrailingComma */) && children.hasTrailingComma;
97857                 if (format & 16 /* CommaDelimited */ && hasTrailingComma) {
97858                     writePunctuation(",");
97859                 }
97860                 // Emit any trailing comment of the last element in the list
97861                 // i.e
97862                 //       var array = [...
97863                 //          2
97864                 //          /* end of element 2 */
97865                 //       ];
97866                 if (previousSibling && format & 60 /* DelimitersMask */ && previousSibling.end !== parentNode.end && !(ts.getEmitFlags(previousSibling) & 1024 /* NoTrailingComments */)) {
97867                     emitLeadingCommentsOfPosition(previousSibling.end);
97868                 }
97869                 // Decrease the indent, if requested.
97870                 if (format & 128 /* Indented */) {
97871                     decreaseIndent();
97872                 }
97873                 recordBundleFileInternalSectionEnd(previousSourceFileTextKind);
97874                 // Write the closing line terminator or closing whitespace.
97875                 var closingLineTerminatorCount = getClosingLineTerminatorCount(parentNode, children, format);
97876                 if (closingLineTerminatorCount) {
97877                     writeLine(closingLineTerminatorCount);
97878                 }
97879                 else if (format & (2097152 /* SpaceAfterList */ | 256 /* SpaceBetweenBraces */)) {
97880                     writeSpace();
97881                 }
97882             }
97883             if (onAfterEmitNodeArray) {
97884                 onAfterEmitNodeArray(children);
97885             }
97886             if (format & 15360 /* BracketsMask */) {
97887                 if (isEmpty && !isUndefined) {
97888                     // TODO: GH#18217
97889                     emitLeadingCommentsOfPosition(children.end); // Emit leading comments within empty lists
97890                 }
97891                 writePunctuation(getClosingBracket(format));
97892             }
97893         }
97894         // Writers
97895         function writeLiteral(s) {
97896             writer.writeLiteral(s);
97897         }
97898         function writeStringLiteral(s) {
97899             writer.writeStringLiteral(s);
97900         }
97901         function writeBase(s) {
97902             writer.write(s);
97903         }
97904         function writeSymbol(s, sym) {
97905             writer.writeSymbol(s, sym);
97906         }
97907         function writePunctuation(s) {
97908             writer.writePunctuation(s);
97909         }
97910         function writeTrailingSemicolon() {
97911             writer.writeTrailingSemicolon(";");
97912         }
97913         function writeKeyword(s) {
97914             writer.writeKeyword(s);
97915         }
97916         function writeOperator(s) {
97917             writer.writeOperator(s);
97918         }
97919         function writeParameter(s) {
97920             writer.writeParameter(s);
97921         }
97922         function writeComment(s) {
97923             writer.writeComment(s);
97924         }
97925         function writeSpace() {
97926             writer.writeSpace(" ");
97927         }
97928         function writeProperty(s) {
97929             writer.writeProperty(s);
97930         }
97931         function writeLine(count) {
97932             if (count === void 0) { count = 1; }
97933             for (var i = 0; i < count; i++) {
97934                 writer.writeLine(i > 0);
97935             }
97936         }
97937         function increaseIndent() {
97938             writer.increaseIndent();
97939         }
97940         function decreaseIndent() {
97941             writer.decreaseIndent();
97942         }
97943         function writeToken(token, pos, writer, contextNode) {
97944             return !sourceMapsDisabled
97945                 ? emitTokenWithSourceMap(contextNode, token, writer, pos, writeTokenText)
97946                 : writeTokenText(token, writer, pos);
97947         }
97948         function writeTokenNode(node, writer) {
97949             if (onBeforeEmitToken) {
97950                 onBeforeEmitToken(node);
97951             }
97952             writer(ts.tokenToString(node.kind));
97953             if (onAfterEmitToken) {
97954                 onAfterEmitToken(node);
97955             }
97956         }
97957         function writeTokenText(token, writer, pos) {
97958             var tokenString = ts.tokenToString(token);
97959             writer(tokenString);
97960             return pos < 0 ? pos : pos + tokenString.length;
97961         }
97962         function writeLineOrSpace(node) {
97963             if (ts.getEmitFlags(node) & 1 /* SingleLine */) {
97964                 writeSpace();
97965             }
97966             else {
97967                 writeLine();
97968             }
97969         }
97970         function writeLines(text) {
97971             var lines = text.split(/\r\n?|\n/g);
97972             var indentation = ts.guessIndentation(lines);
97973             for (var _a = 0, lines_3 = lines; _a < lines_3.length; _a++) {
97974                 var lineText = lines_3[_a];
97975                 var line = indentation ? lineText.slice(indentation) : lineText;
97976                 if (line.length) {
97977                     writeLine();
97978                     write(line);
97979                 }
97980             }
97981         }
97982         function writeLinesAndIndent(lineCount, writeSpaceIfNotIndenting) {
97983             if (lineCount) {
97984                 increaseIndent();
97985                 writeLine(lineCount);
97986             }
97987             else if (writeSpaceIfNotIndenting) {
97988                 writeSpace();
97989             }
97990         }
97991         // Helper function to decrease the indent if we previously indented.  Allows multiple
97992         // previous indent values to be considered at a time.  This also allows caller to just
97993         // call this once, passing in all their appropriate indent values, instead of needing
97994         // to call this helper function multiple times.
97995         function decreaseIndentIf(value1, value2) {
97996             if (value1) {
97997                 decreaseIndent();
97998             }
97999             if (value2) {
98000                 decreaseIndent();
98001             }
98002         }
98003         function getLeadingLineTerminatorCount(parentNode, children, format) {
98004             if (format & 2 /* PreserveLines */ || preserveSourceNewlines) {
98005                 if (format & 65536 /* PreferNewLine */) {
98006                     return 1;
98007                 }
98008                 var firstChild_1 = children[0];
98009                 if (firstChild_1 === undefined) {
98010                     return ts.rangeIsOnSingleLine(parentNode, currentSourceFile) ? 0 : 1;
98011                 }
98012                 if (firstChild_1.kind === 11 /* JsxText */) {
98013                     // JsxText will be written with its leading whitespace, so don't add more manually.
98014                     return 0;
98015                 }
98016                 if (!ts.positionIsSynthesized(parentNode.pos) && !ts.nodeIsSynthesized(firstChild_1) && (!firstChild_1.parent || firstChild_1.parent === parentNode)) {
98017                     if (preserveSourceNewlines) {
98018                         return getEffectiveLines(function (includeComments) { return ts.getLinesBetweenPositionAndPrecedingNonWhitespaceCharacter(firstChild_1.pos, parentNode.pos, currentSourceFile, includeComments); });
98019                     }
98020                     return ts.rangeStartPositionsAreOnSameLine(parentNode, firstChild_1, currentSourceFile) ? 0 : 1;
98021                 }
98022                 if (synthesizedNodeStartsOnNewLine(firstChild_1, format)) {
98023                     return 1;
98024                 }
98025             }
98026             return format & 1 /* MultiLine */ ? 1 : 0;
98027         }
98028         function getSeparatingLineTerminatorCount(previousNode, nextNode, format) {
98029             if (format & 2 /* PreserveLines */ || preserveSourceNewlines) {
98030                 if (previousNode === undefined || nextNode === undefined) {
98031                     return 0;
98032                 }
98033                 if (nextNode.kind === 11 /* JsxText */) {
98034                     // JsxText will be written with its leading whitespace, so don't add more manually.
98035                     return 0;
98036                 }
98037                 else if (!ts.nodeIsSynthesized(previousNode) && !ts.nodeIsSynthesized(nextNode) && previousNode.parent === nextNode.parent) {
98038                     if (preserveSourceNewlines) {
98039                         return getEffectiveLines(function (includeComments) { return ts.getLinesBetweenRangeEndAndRangeStart(previousNode, nextNode, currentSourceFile, includeComments); });
98040                     }
98041                     return ts.rangeEndIsOnSameLineAsRangeStart(previousNode, nextNode, currentSourceFile) ? 0 : 1;
98042                 }
98043                 else if (synthesizedNodeStartsOnNewLine(previousNode, format) || synthesizedNodeStartsOnNewLine(nextNode, format)) {
98044                     return 1;
98045                 }
98046             }
98047             else if (ts.getStartsOnNewLine(nextNode)) {
98048                 return 1;
98049             }
98050             return format & 1 /* MultiLine */ ? 1 : 0;
98051         }
98052         function getClosingLineTerminatorCount(parentNode, children, format) {
98053             if (format & 2 /* PreserveLines */ || preserveSourceNewlines) {
98054                 if (format & 65536 /* PreferNewLine */) {
98055                     return 1;
98056                 }
98057                 var lastChild_1 = ts.lastOrUndefined(children);
98058                 if (lastChild_1 === undefined) {
98059                     return ts.rangeIsOnSingleLine(parentNode, currentSourceFile) ? 0 : 1;
98060                 }
98061                 if (!ts.positionIsSynthesized(parentNode.pos) && !ts.nodeIsSynthesized(lastChild_1) && (!lastChild_1.parent || lastChild_1.parent === parentNode)) {
98062                     if (preserveSourceNewlines) {
98063                         return getEffectiveLines(function (includeComments) { return ts.getLinesBetweenPositionAndNextNonWhitespaceCharacter(lastChild_1.end, parentNode.end, currentSourceFile, includeComments); });
98064                     }
98065                     return ts.rangeEndPositionsAreOnSameLine(parentNode, lastChild_1, currentSourceFile) ? 0 : 1;
98066                 }
98067                 if (synthesizedNodeStartsOnNewLine(lastChild_1, format)) {
98068                     return 1;
98069                 }
98070             }
98071             if (format & 1 /* MultiLine */ && !(format & 131072 /* NoTrailingNewLine */)) {
98072                 return 1;
98073             }
98074             return 0;
98075         }
98076         function getEffectiveLines(getLineDifference) {
98077             // If 'preserveSourceNewlines' is disabled, we should never call this function
98078             // because it could be more expensive than alternative approximations.
98079             ts.Debug.assert(!!preserveSourceNewlines);
98080             // We start by measuring the line difference from a position to its adjacent comments,
98081             // so that this is counted as a one-line difference, not two:
98082             //
98083             //   node1;
98084             //   // NODE2 COMMENT
98085             //   node2;
98086             var lines = getLineDifference(/*includeComments*/ true);
98087             if (lines === 0) {
98088                 // However, if the line difference considering comments was 0, we might have this:
98089                 //
98090                 //   node1; // NODE2 COMMENT
98091                 //   node2;
98092                 //
98093                 // in which case we should be ignoring node2's comment, so this too is counted as
98094                 // a one-line difference, not zero.
98095                 return getLineDifference(/*includeComments*/ false);
98096             }
98097             return lines;
98098         }
98099         function writeLineSeparatorsAndIndentBefore(node, parent) {
98100             var leadingNewlines = preserveSourceNewlines && getLeadingLineTerminatorCount(parent, [node], 0 /* None */);
98101             if (leadingNewlines) {
98102                 writeLinesAndIndent(leadingNewlines, /*writeLinesIfNotIndenting*/ false);
98103             }
98104             return !!leadingNewlines;
98105         }
98106         function writeLineSeparatorsAfter(node, parent) {
98107             var trailingNewlines = preserveSourceNewlines && getClosingLineTerminatorCount(parent, [node], 0 /* None */);
98108             if (trailingNewlines) {
98109                 writeLine(trailingNewlines);
98110             }
98111         }
98112         function synthesizedNodeStartsOnNewLine(node, format) {
98113             if (ts.nodeIsSynthesized(node)) {
98114                 var startsOnNewLine = ts.getStartsOnNewLine(node);
98115                 if (startsOnNewLine === undefined) {
98116                     return (format & 65536 /* PreferNewLine */) !== 0;
98117                 }
98118                 return startsOnNewLine;
98119             }
98120             return (format & 65536 /* PreferNewLine */) !== 0;
98121         }
98122         function getLinesBetweenNodes(parent, node1, node2) {
98123             if (ts.getEmitFlags(parent) & 131072 /* NoIndentation */) {
98124                 return 0;
98125             }
98126             parent = skipSynthesizedParentheses(parent);
98127             node1 = skipSynthesizedParentheses(node1);
98128             node2 = skipSynthesizedParentheses(node2);
98129             // Always use a newline for synthesized code if the synthesizer desires it.
98130             if (ts.getStartsOnNewLine(node2)) {
98131                 return 1;
98132             }
98133             if (!ts.nodeIsSynthesized(parent) && !ts.nodeIsSynthesized(node1) && !ts.nodeIsSynthesized(node2)) {
98134                 if (preserveSourceNewlines) {
98135                     return getEffectiveLines(function (includeComments) { return ts.getLinesBetweenRangeEndAndRangeStart(node1, node2, currentSourceFile, includeComments); });
98136                 }
98137                 return ts.rangeEndIsOnSameLineAsRangeStart(node1, node2, currentSourceFile) ? 0 : 1;
98138             }
98139             return 0;
98140         }
98141         function isEmptyBlock(block) {
98142             return block.statements.length === 0
98143                 && ts.rangeEndIsOnSameLineAsRangeStart(block, block, currentSourceFile);
98144         }
98145         function skipSynthesizedParentheses(node) {
98146             while (node.kind === 200 /* ParenthesizedExpression */ && ts.nodeIsSynthesized(node)) {
98147                 node = node.expression;
98148             }
98149             return node;
98150         }
98151         function getTextOfNode(node, includeTrivia) {
98152             if (ts.isGeneratedIdentifier(node)) {
98153                 return generateName(node);
98154             }
98155             else if ((ts.isIdentifier(node) || ts.isPrivateIdentifier(node)) && (ts.nodeIsSynthesized(node) || !node.parent || !currentSourceFile || (node.parent && currentSourceFile && ts.getSourceFileOfNode(node) !== ts.getOriginalNode(currentSourceFile)))) {
98156                 return ts.idText(node);
98157             }
98158             else if (node.kind === 10 /* StringLiteral */ && node.textSourceNode) {
98159                 return getTextOfNode(node.textSourceNode, includeTrivia);
98160             }
98161             else if (ts.isLiteralExpression(node) && (ts.nodeIsSynthesized(node) || !node.parent)) {
98162                 return node.text;
98163             }
98164             return ts.getSourceTextOfNodeFromSourceFile(currentSourceFile, node, includeTrivia);
98165         }
98166         function getLiteralTextOfNode(node, neverAsciiEscape, jsxAttributeEscape) {
98167             if (node.kind === 10 /* StringLiteral */ && node.textSourceNode) {
98168                 var textSourceNode = node.textSourceNode;
98169                 if (ts.isIdentifier(textSourceNode)) {
98170                     return jsxAttributeEscape ? "\"" + ts.escapeJsxAttributeString(getTextOfNode(textSourceNode)) + "\"" :
98171                         neverAsciiEscape || (ts.getEmitFlags(node) & 16777216 /* NoAsciiEscaping */) ? "\"" + ts.escapeString(getTextOfNode(textSourceNode)) + "\"" :
98172                             "\"" + ts.escapeNonAsciiString(getTextOfNode(textSourceNode)) + "\"";
98173                 }
98174                 else {
98175                     return getLiteralTextOfNode(textSourceNode, neverAsciiEscape, jsxAttributeEscape);
98176                 }
98177             }
98178             return ts.getLiteralText(node, currentSourceFile, neverAsciiEscape, jsxAttributeEscape);
98179         }
98180         /**
98181          * Push a new name generation scope.
98182          */
98183         function pushNameGenerationScope(node) {
98184             if (node && ts.getEmitFlags(node) & 524288 /* ReuseTempVariableScope */) {
98185                 return;
98186             }
98187             tempFlagsStack.push(tempFlags);
98188             tempFlags = 0;
98189             reservedNamesStack.push(reservedNames);
98190         }
98191         /**
98192          * Pop the current name generation scope.
98193          */
98194         function popNameGenerationScope(node) {
98195             if (node && ts.getEmitFlags(node) & 524288 /* ReuseTempVariableScope */) {
98196                 return;
98197             }
98198             tempFlags = tempFlagsStack.pop();
98199             reservedNames = reservedNamesStack.pop();
98200         }
98201         function reserveNameInNestedScopes(name) {
98202             if (!reservedNames || reservedNames === ts.lastOrUndefined(reservedNamesStack)) {
98203                 reservedNames = ts.createMap();
98204             }
98205             reservedNames.set(name, true);
98206         }
98207         function generateNames(node) {
98208             if (!node)
98209                 return;
98210             switch (node.kind) {
98211                 case 223 /* Block */:
98212                     ts.forEach(node.statements, generateNames);
98213                     break;
98214                 case 238 /* LabeledStatement */:
98215                 case 236 /* WithStatement */:
98216                 case 228 /* DoStatement */:
98217                 case 229 /* WhileStatement */:
98218                     generateNames(node.statement);
98219                     break;
98220                 case 227 /* IfStatement */:
98221                     generateNames(node.thenStatement);
98222                     generateNames(node.elseStatement);
98223                     break;
98224                 case 230 /* ForStatement */:
98225                 case 232 /* ForOfStatement */:
98226                 case 231 /* ForInStatement */:
98227                     generateNames(node.initializer);
98228                     generateNames(node.statement);
98229                     break;
98230                 case 237 /* SwitchStatement */:
98231                     generateNames(node.caseBlock);
98232                     break;
98233                 case 251 /* CaseBlock */:
98234                     ts.forEach(node.clauses, generateNames);
98235                     break;
98236                 case 277 /* CaseClause */:
98237                 case 278 /* DefaultClause */:
98238                     ts.forEach(node.statements, generateNames);
98239                     break;
98240                 case 240 /* TryStatement */:
98241                     generateNames(node.tryBlock);
98242                     generateNames(node.catchClause);
98243                     generateNames(node.finallyBlock);
98244                     break;
98245                 case 280 /* CatchClause */:
98246                     generateNames(node.variableDeclaration);
98247                     generateNames(node.block);
98248                     break;
98249                 case 225 /* VariableStatement */:
98250                     generateNames(node.declarationList);
98251                     break;
98252                 case 243 /* VariableDeclarationList */:
98253                     ts.forEach(node.declarations, generateNames);
98254                     break;
98255                 case 242 /* VariableDeclaration */:
98256                 case 156 /* Parameter */:
98257                 case 191 /* BindingElement */:
98258                 case 245 /* ClassDeclaration */:
98259                     generateNameIfNeeded(node.name);
98260                     break;
98261                 case 244 /* FunctionDeclaration */:
98262                     generateNameIfNeeded(node.name);
98263                     if (ts.getEmitFlags(node) & 524288 /* ReuseTempVariableScope */) {
98264                         ts.forEach(node.parameters, generateNames);
98265                         generateNames(node.body);
98266                     }
98267                     break;
98268                 case 189 /* ObjectBindingPattern */:
98269                 case 190 /* ArrayBindingPattern */:
98270                     ts.forEach(node.elements, generateNames);
98271                     break;
98272                 case 254 /* ImportDeclaration */:
98273                     generateNames(node.importClause);
98274                     break;
98275                 case 255 /* ImportClause */:
98276                     generateNameIfNeeded(node.name);
98277                     generateNames(node.namedBindings);
98278                     break;
98279                 case 256 /* NamespaceImport */:
98280                     generateNameIfNeeded(node.name);
98281                     break;
98282                 case 262 /* NamespaceExport */:
98283                     generateNameIfNeeded(node.name);
98284                     break;
98285                 case 257 /* NamedImports */:
98286                     ts.forEach(node.elements, generateNames);
98287                     break;
98288                 case 258 /* ImportSpecifier */:
98289                     generateNameIfNeeded(node.propertyName || node.name);
98290                     break;
98291             }
98292         }
98293         function generateMemberNames(node) {
98294             if (!node)
98295                 return;
98296             switch (node.kind) {
98297                 case 281 /* PropertyAssignment */:
98298                 case 282 /* ShorthandPropertyAssignment */:
98299                 case 159 /* PropertyDeclaration */:
98300                 case 161 /* MethodDeclaration */:
98301                 case 163 /* GetAccessor */:
98302                 case 164 /* SetAccessor */:
98303                     generateNameIfNeeded(node.name);
98304                     break;
98305             }
98306         }
98307         function generateNameIfNeeded(name) {
98308             if (name) {
98309                 if (ts.isGeneratedIdentifier(name)) {
98310                     generateName(name);
98311                 }
98312                 else if (ts.isBindingPattern(name)) {
98313                     generateNames(name);
98314                 }
98315             }
98316         }
98317         /**
98318          * Generate the text for a generated identifier.
98319          */
98320         function generateName(name) {
98321             if ((name.autoGenerateFlags & 7 /* KindMask */) === 4 /* Node */) {
98322                 // Node names generate unique names based on their original node
98323                 // and are cached based on that node's id.
98324                 return generateNameCached(getNodeForGeneratedName(name), name.autoGenerateFlags);
98325             }
98326             else {
98327                 // Auto, Loop, and Unique names are cached based on their unique
98328                 // autoGenerateId.
98329                 var autoGenerateId = name.autoGenerateId;
98330                 return autoGeneratedIdToGeneratedName[autoGenerateId] || (autoGeneratedIdToGeneratedName[autoGenerateId] = makeName(name));
98331             }
98332         }
98333         function generateNameCached(node, flags) {
98334             var nodeId = ts.getNodeId(node);
98335             return nodeIdToGeneratedName[nodeId] || (nodeIdToGeneratedName[nodeId] = generateNameForNode(node, flags));
98336         }
98337         /**
98338          * Returns a value indicating whether a name is unique globally, within the current file,
98339          * or within the NameGenerator.
98340          */
98341         function isUniqueName(name) {
98342             return isFileLevelUniqueName(name)
98343                 && !generatedNames.has(name)
98344                 && !(reservedNames && reservedNames.has(name));
98345         }
98346         /**
98347          * Returns a value indicating whether a name is unique globally or within the current file.
98348          */
98349         function isFileLevelUniqueName(name) {
98350             return currentSourceFile ? ts.isFileLevelUniqueName(currentSourceFile, name, hasGlobalName) : true;
98351         }
98352         /**
98353          * Returns a value indicating whether a name is unique within a container.
98354          */
98355         function isUniqueLocalName(name, container) {
98356             for (var node = container; ts.isNodeDescendantOf(node, container); node = node.nextContainer) {
98357                 if (node.locals) {
98358                     var local = node.locals.get(ts.escapeLeadingUnderscores(name));
98359                     // We conservatively include alias symbols to cover cases where they're emitted as locals
98360                     if (local && local.flags & (111551 /* Value */ | 1048576 /* ExportValue */ | 2097152 /* Alias */)) {
98361                         return false;
98362                     }
98363                 }
98364             }
98365             return true;
98366         }
98367         /**
98368          * Return the next available name in the pattern _a ... _z, _0, _1, ...
98369          * TempFlags._i or TempFlags._n may be used to express a preference for that dedicated name.
98370          * Note that names generated by makeTempVariableName and makeUniqueName will never conflict.
98371          */
98372         function makeTempVariableName(flags, reservedInNestedScopes) {
98373             if (flags && !(tempFlags & flags)) {
98374                 var name = flags === 268435456 /* _i */ ? "_i" : "_n";
98375                 if (isUniqueName(name)) {
98376                     tempFlags |= flags;
98377                     if (reservedInNestedScopes) {
98378                         reserveNameInNestedScopes(name);
98379                     }
98380                     return name;
98381                 }
98382             }
98383             while (true) {
98384                 var count = tempFlags & 268435455 /* CountMask */;
98385                 tempFlags++;
98386                 // Skip over 'i' and 'n'
98387                 if (count !== 8 && count !== 13) {
98388                     var name = count < 26
98389                         ? "_" + String.fromCharCode(97 /* a */ + count)
98390                         : "_" + (count - 26);
98391                     if (isUniqueName(name)) {
98392                         if (reservedInNestedScopes) {
98393                             reserveNameInNestedScopes(name);
98394                         }
98395                         return name;
98396                     }
98397                 }
98398             }
98399         }
98400         /**
98401          * Generate a name that is unique within the current file and doesn't conflict with any names
98402          * in global scope. The name is formed by adding an '_n' suffix to the specified base name,
98403          * where n is a positive integer. Note that names generated by makeTempVariableName and
98404          * makeUniqueName are guaranteed to never conflict.
98405          * If `optimistic` is set, the first instance will use 'baseName' verbatim instead of 'baseName_1'
98406          */
98407         function makeUniqueName(baseName, checkFn, optimistic, scoped) {
98408             if (checkFn === void 0) { checkFn = isUniqueName; }
98409             if (optimistic) {
98410                 if (checkFn(baseName)) {
98411                     if (scoped) {
98412                         reserveNameInNestedScopes(baseName);
98413                     }
98414                     else {
98415                         generatedNames.set(baseName, true);
98416                     }
98417                     return baseName;
98418                 }
98419             }
98420             // Find the first unique 'name_n', where n is a positive number
98421             if (baseName.charCodeAt(baseName.length - 1) !== 95 /* _ */) {
98422                 baseName += "_";
98423             }
98424             var i = 1;
98425             while (true) {
98426                 var generatedName = baseName + i;
98427                 if (checkFn(generatedName)) {
98428                     if (scoped) {
98429                         reserveNameInNestedScopes(generatedName);
98430                     }
98431                     else {
98432                         generatedNames.set(generatedName, true);
98433                     }
98434                     return generatedName;
98435                 }
98436                 i++;
98437             }
98438         }
98439         function makeFileLevelOptimisticUniqueName(name) {
98440             return makeUniqueName(name, isFileLevelUniqueName, /*optimistic*/ true);
98441         }
98442         /**
98443          * Generates a unique name for a ModuleDeclaration or EnumDeclaration.
98444          */
98445         function generateNameForModuleOrEnum(node) {
98446             var name = getTextOfNode(node.name);
98447             // Use module/enum name itself if it is unique, otherwise make a unique variation
98448             return isUniqueLocalName(name, node) ? name : makeUniqueName(name);
98449         }
98450         /**
98451          * Generates a unique name for an ImportDeclaration or ExportDeclaration.
98452          */
98453         function generateNameForImportOrExportDeclaration(node) {
98454             var expr = ts.getExternalModuleName(node); // TODO: GH#18217
98455             var baseName = ts.isStringLiteral(expr) ?
98456                 ts.makeIdentifierFromModuleName(expr.text) : "module";
98457             return makeUniqueName(baseName);
98458         }
98459         /**
98460          * Generates a unique name for a default export.
98461          */
98462         function generateNameForExportDefault() {
98463             return makeUniqueName("default");
98464         }
98465         /**
98466          * Generates a unique name for a class expression.
98467          */
98468         function generateNameForClassExpression() {
98469             return makeUniqueName("class");
98470         }
98471         function generateNameForMethodOrAccessor(node) {
98472             if (ts.isIdentifier(node.name)) {
98473                 return generateNameCached(node.name);
98474             }
98475             return makeTempVariableName(0 /* Auto */);
98476         }
98477         /**
98478          * Generates a unique name from a node.
98479          */
98480         function generateNameForNode(node, flags) {
98481             switch (node.kind) {
98482                 case 75 /* Identifier */:
98483                     return makeUniqueName(getTextOfNode(node), isUniqueName, !!(flags & 16 /* Optimistic */), !!(flags & 8 /* ReservedInNestedScopes */));
98484                 case 249 /* ModuleDeclaration */:
98485                 case 248 /* EnumDeclaration */:
98486                     return generateNameForModuleOrEnum(node);
98487                 case 254 /* ImportDeclaration */:
98488                 case 260 /* ExportDeclaration */:
98489                     return generateNameForImportOrExportDeclaration(node);
98490                 case 244 /* FunctionDeclaration */:
98491                 case 245 /* ClassDeclaration */:
98492                 case 259 /* ExportAssignment */:
98493                     return generateNameForExportDefault();
98494                 case 214 /* ClassExpression */:
98495                     return generateNameForClassExpression();
98496                 case 161 /* MethodDeclaration */:
98497                 case 163 /* GetAccessor */:
98498                 case 164 /* SetAccessor */:
98499                     return generateNameForMethodOrAccessor(node);
98500                 case 154 /* ComputedPropertyName */:
98501                     return makeTempVariableName(0 /* Auto */, /*reserveInNestedScopes*/ true);
98502                 default:
98503                     return makeTempVariableName(0 /* Auto */);
98504             }
98505         }
98506         /**
98507          * Generates a unique identifier for a node.
98508          */
98509         function makeName(name) {
98510             switch (name.autoGenerateFlags & 7 /* KindMask */) {
98511                 case 1 /* Auto */:
98512                     return makeTempVariableName(0 /* Auto */, !!(name.autoGenerateFlags & 8 /* ReservedInNestedScopes */));
98513                 case 2 /* Loop */:
98514                     return makeTempVariableName(268435456 /* _i */, !!(name.autoGenerateFlags & 8 /* ReservedInNestedScopes */));
98515                 case 3 /* Unique */:
98516                     return makeUniqueName(ts.idText(name), (name.autoGenerateFlags & 32 /* FileLevel */) ? isFileLevelUniqueName : isUniqueName, !!(name.autoGenerateFlags & 16 /* Optimistic */), !!(name.autoGenerateFlags & 8 /* ReservedInNestedScopes */));
98517             }
98518             return ts.Debug.fail("Unsupported GeneratedIdentifierKind.");
98519         }
98520         /**
98521          * Gets the node from which a name should be generated.
98522          */
98523         function getNodeForGeneratedName(name) {
98524             var autoGenerateId = name.autoGenerateId;
98525             var node = name;
98526             var original = node.original;
98527             while (original) {
98528                 node = original;
98529                 // if "node" is a different generated name (having a different
98530                 // "autoGenerateId"), use it and stop traversing.
98531                 if (ts.isIdentifier(node)
98532                     && !!(node.autoGenerateFlags & 4 /* Node */)
98533                     && node.autoGenerateId !== autoGenerateId) {
98534                     break;
98535                 }
98536                 original = node.original;
98537             }
98538             // otherwise, return the original node for the source;
98539             return node;
98540         }
98541         // Comments
98542         function pipelineEmitWithComments(hint, node) {
98543             ts.Debug.assert(lastNode === node || lastSubstitution === node);
98544             enterComment();
98545             hasWrittenComment = false;
98546             var emitFlags = ts.getEmitFlags(node);
98547             var _a = ts.getCommentRange(node), pos = _a.pos, end = _a.end;
98548             var isEmittedNode = node.kind !== 325 /* NotEmittedStatement */;
98549             // We have to explicitly check that the node is JsxText because if the compilerOptions.jsx is "preserve" we will not do any transformation.
98550             // It is expensive to walk entire tree just to set one kind of node to have no comments.
98551             var skipLeadingComments = pos < 0 || (emitFlags & 512 /* NoLeadingComments */) !== 0 || node.kind === 11 /* JsxText */;
98552             var skipTrailingComments = end < 0 || (emitFlags & 1024 /* NoTrailingComments */) !== 0 || node.kind === 11 /* JsxText */;
98553             // Save current container state on the stack.
98554             var savedContainerPos = containerPos;
98555             var savedContainerEnd = containerEnd;
98556             var savedDeclarationListContainerEnd = declarationListContainerEnd;
98557             if ((pos > 0 || end > 0) && pos !== end) {
98558                 // Emit leading comments if the position is not synthesized and the node
98559                 // has not opted out from emitting leading comments.
98560                 if (!skipLeadingComments) {
98561                     emitLeadingComments(pos, isEmittedNode);
98562                 }
98563                 if (!skipLeadingComments || (pos >= 0 && (emitFlags & 512 /* NoLeadingComments */) !== 0)) {
98564                     // Advance the container position if comments get emitted or if they've been disabled explicitly using NoLeadingComments.
98565                     containerPos = pos;
98566                 }
98567                 if (!skipTrailingComments || (end >= 0 && (emitFlags & 1024 /* NoTrailingComments */) !== 0)) {
98568                     // As above.
98569                     containerEnd = end;
98570                     // To avoid invalid comment emit in a down-level binding pattern, we
98571                     // keep track of the last declaration list container's end
98572                     if (node.kind === 243 /* VariableDeclarationList */) {
98573                         declarationListContainerEnd = end;
98574                     }
98575                 }
98576             }
98577             ts.forEach(ts.getSyntheticLeadingComments(node), emitLeadingSynthesizedComment);
98578             exitComment();
98579             var pipelinePhase = getNextPipelinePhase(2 /* Comments */, hint, node);
98580             if (emitFlags & 2048 /* NoNestedComments */) {
98581                 commentsDisabled = true;
98582                 pipelinePhase(hint, node);
98583                 commentsDisabled = false;
98584             }
98585             else {
98586                 pipelinePhase(hint, node);
98587             }
98588             enterComment();
98589             ts.forEach(ts.getSyntheticTrailingComments(node), emitTrailingSynthesizedComment);
98590             if ((pos > 0 || end > 0) && pos !== end) {
98591                 // Restore previous container state.
98592                 containerPos = savedContainerPos;
98593                 containerEnd = savedContainerEnd;
98594                 declarationListContainerEnd = savedDeclarationListContainerEnd;
98595                 // Emit trailing comments if the position is not synthesized and the node
98596                 // has not opted out from emitting leading comments and is an emitted node.
98597                 if (!skipTrailingComments && isEmittedNode) {
98598                     emitTrailingComments(end);
98599                 }
98600             }
98601             exitComment();
98602             ts.Debug.assert(lastNode === node || lastSubstitution === node);
98603         }
98604         function emitLeadingSynthesizedComment(comment) {
98605             if (comment.kind === 2 /* SingleLineCommentTrivia */) {
98606                 writer.writeLine();
98607             }
98608             writeSynthesizedComment(comment);
98609             if (comment.hasTrailingNewLine || comment.kind === 2 /* SingleLineCommentTrivia */) {
98610                 writer.writeLine();
98611             }
98612             else {
98613                 writer.writeSpace(" ");
98614             }
98615         }
98616         function emitTrailingSynthesizedComment(comment) {
98617             if (!writer.isAtStartOfLine()) {
98618                 writer.writeSpace(" ");
98619             }
98620             writeSynthesizedComment(comment);
98621             if (comment.hasTrailingNewLine) {
98622                 writer.writeLine();
98623             }
98624         }
98625         function writeSynthesizedComment(comment) {
98626             var text = formatSynthesizedComment(comment);
98627             var lineMap = comment.kind === 3 /* MultiLineCommentTrivia */ ? ts.computeLineStarts(text) : undefined;
98628             ts.writeCommentRange(text, lineMap, writer, 0, text.length, newLine);
98629         }
98630         function formatSynthesizedComment(comment) {
98631             return comment.kind === 3 /* MultiLineCommentTrivia */
98632                 ? "/*" + comment.text + "*/"
98633                 : "//" + comment.text;
98634         }
98635         function emitBodyWithDetachedComments(node, detachedRange, emitCallback) {
98636             enterComment();
98637             var pos = detachedRange.pos, end = detachedRange.end;
98638             var emitFlags = ts.getEmitFlags(node);
98639             var skipLeadingComments = pos < 0 || (emitFlags & 512 /* NoLeadingComments */) !== 0;
98640             var skipTrailingComments = commentsDisabled || end < 0 || (emitFlags & 1024 /* NoTrailingComments */) !== 0;
98641             if (!skipLeadingComments) {
98642                 emitDetachedCommentsAndUpdateCommentsInfo(detachedRange);
98643             }
98644             exitComment();
98645             if (emitFlags & 2048 /* NoNestedComments */ && !commentsDisabled) {
98646                 commentsDisabled = true;
98647                 emitCallback(node);
98648                 commentsDisabled = false;
98649             }
98650             else {
98651                 emitCallback(node);
98652             }
98653             enterComment();
98654             if (!skipTrailingComments) {
98655                 emitLeadingComments(detachedRange.end, /*isEmittedNode*/ true);
98656                 if (hasWrittenComment && !writer.isAtStartOfLine()) {
98657                     writer.writeLine();
98658                 }
98659             }
98660             exitComment();
98661         }
98662         function emitLeadingComments(pos, isEmittedNode) {
98663             hasWrittenComment = false;
98664             if (isEmittedNode) {
98665                 forEachLeadingCommentToEmit(pos, emitLeadingComment);
98666             }
98667             else if (pos === 0) {
98668                 // If the node will not be emitted in JS, remove all the comments(normal, pinned and ///) associated with the node,
98669                 // unless it is a triple slash comment at the top of the file.
98670                 // For Example:
98671                 //      /// <reference-path ...>
98672                 //      declare var x;
98673                 //      /// <reference-path ...>
98674                 //      interface F {}
98675                 //  The first /// will NOT be removed while the second one will be removed even though both node will not be emitted
98676                 forEachLeadingCommentToEmit(pos, emitTripleSlashLeadingComment);
98677             }
98678         }
98679         function emitTripleSlashLeadingComment(commentPos, commentEnd, kind, hasTrailingNewLine, rangePos) {
98680             if (isTripleSlashComment(commentPos, commentEnd)) {
98681                 emitLeadingComment(commentPos, commentEnd, kind, hasTrailingNewLine, rangePos);
98682             }
98683         }
98684         function shouldWriteComment(text, pos) {
98685             if (printerOptions.onlyPrintJsDocStyle) {
98686                 return (ts.isJSDocLikeText(text, pos) || ts.isPinnedComment(text, pos));
98687             }
98688             return true;
98689         }
98690         function emitLeadingComment(commentPos, commentEnd, kind, hasTrailingNewLine, rangePos) {
98691             if (!shouldWriteComment(currentSourceFile.text, commentPos))
98692                 return;
98693             if (!hasWrittenComment) {
98694                 ts.emitNewLineBeforeLeadingCommentOfPosition(getCurrentLineMap(), writer, rangePos, commentPos);
98695                 hasWrittenComment = true;
98696             }
98697             // Leading comments are emitted at /*leading comment1 */space/*leading comment*/space
98698             emitPos(commentPos);
98699             ts.writeCommentRange(currentSourceFile.text, getCurrentLineMap(), writer, commentPos, commentEnd, newLine);
98700             emitPos(commentEnd);
98701             if (hasTrailingNewLine) {
98702                 writer.writeLine();
98703             }
98704             else if (kind === 3 /* MultiLineCommentTrivia */) {
98705                 writer.writeSpace(" ");
98706             }
98707         }
98708         function emitLeadingCommentsOfPosition(pos) {
98709             if (commentsDisabled || pos === -1) {
98710                 return;
98711             }
98712             emitLeadingComments(pos, /*isEmittedNode*/ true);
98713         }
98714         function emitTrailingComments(pos) {
98715             forEachTrailingCommentToEmit(pos, emitTrailingComment);
98716         }
98717         function emitTrailingComment(commentPos, commentEnd, _kind, hasTrailingNewLine) {
98718             if (!shouldWriteComment(currentSourceFile.text, commentPos))
98719                 return;
98720             // trailing comments are emitted at space/*trailing comment1 */space/*trailing comment2*/
98721             if (!writer.isAtStartOfLine()) {
98722                 writer.writeSpace(" ");
98723             }
98724             emitPos(commentPos);
98725             ts.writeCommentRange(currentSourceFile.text, getCurrentLineMap(), writer, commentPos, commentEnd, newLine);
98726             emitPos(commentEnd);
98727             if (hasTrailingNewLine) {
98728                 writer.writeLine();
98729             }
98730         }
98731         function emitTrailingCommentsOfPosition(pos, prefixSpace) {
98732             if (commentsDisabled) {
98733                 return;
98734             }
98735             enterComment();
98736             forEachTrailingCommentToEmit(pos, prefixSpace ? emitTrailingComment : emitTrailingCommentOfPosition);
98737             exitComment();
98738         }
98739         function emitTrailingCommentOfPosition(commentPos, commentEnd, _kind, hasTrailingNewLine) {
98740             // trailing comments of a position are emitted at /*trailing comment1 */space/*trailing comment*/space
98741             emitPos(commentPos);
98742             ts.writeCommentRange(currentSourceFile.text, getCurrentLineMap(), writer, commentPos, commentEnd, newLine);
98743             emitPos(commentEnd);
98744             if (hasTrailingNewLine) {
98745                 writer.writeLine();
98746             }
98747             else {
98748                 writer.writeSpace(" ");
98749             }
98750         }
98751         function forEachLeadingCommentToEmit(pos, cb) {
98752             // Emit the leading comments only if the container's pos doesn't match because the container should take care of emitting these comments
98753             if (currentSourceFile && (containerPos === -1 || pos !== containerPos)) {
98754                 if (hasDetachedComments(pos)) {
98755                     forEachLeadingCommentWithoutDetachedComments(cb);
98756                 }
98757                 else {
98758                     ts.forEachLeadingCommentRange(currentSourceFile.text, pos, cb, /*state*/ pos);
98759                 }
98760             }
98761         }
98762         function forEachTrailingCommentToEmit(end, cb) {
98763             // Emit the trailing comments only if the container's end doesn't match because the container should take care of emitting these comments
98764             if (currentSourceFile && (containerEnd === -1 || (end !== containerEnd && end !== declarationListContainerEnd))) {
98765                 ts.forEachTrailingCommentRange(currentSourceFile.text, end, cb);
98766             }
98767         }
98768         function hasDetachedComments(pos) {
98769             return detachedCommentsInfo !== undefined && ts.last(detachedCommentsInfo).nodePos === pos;
98770         }
98771         function forEachLeadingCommentWithoutDetachedComments(cb) {
98772             // get the leading comments from detachedPos
98773             var pos = ts.last(detachedCommentsInfo).detachedCommentEndPos;
98774             if (detachedCommentsInfo.length - 1) {
98775                 detachedCommentsInfo.pop();
98776             }
98777             else {
98778                 detachedCommentsInfo = undefined;
98779             }
98780             ts.forEachLeadingCommentRange(currentSourceFile.text, pos, cb, /*state*/ pos);
98781         }
98782         function emitDetachedCommentsAndUpdateCommentsInfo(range) {
98783             var currentDetachedCommentInfo = ts.emitDetachedComments(currentSourceFile.text, getCurrentLineMap(), writer, emitComment, range, newLine, commentsDisabled);
98784             if (currentDetachedCommentInfo) {
98785                 if (detachedCommentsInfo) {
98786                     detachedCommentsInfo.push(currentDetachedCommentInfo);
98787                 }
98788                 else {
98789                     detachedCommentsInfo = [currentDetachedCommentInfo];
98790                 }
98791             }
98792         }
98793         function emitComment(text, lineMap, writer, commentPos, commentEnd, newLine) {
98794             if (!shouldWriteComment(currentSourceFile.text, commentPos))
98795                 return;
98796             emitPos(commentPos);
98797             ts.writeCommentRange(text, lineMap, writer, commentPos, commentEnd, newLine);
98798             emitPos(commentEnd);
98799         }
98800         /**
98801          * Determine if the given comment is a triple-slash
98802          *
98803          * @return true if the comment is a triple-slash comment else false
98804          */
98805         function isTripleSlashComment(commentPos, commentEnd) {
98806             return ts.isRecognizedTripleSlashComment(currentSourceFile.text, commentPos, commentEnd);
98807         }
98808         // Source Maps
98809         function getParsedSourceMap(node) {
98810             if (node.parsedSourceMap === undefined && node.sourceMapText !== undefined) {
98811                 node.parsedSourceMap = ts.tryParseRawSourceMap(node.sourceMapText) || false;
98812             }
98813             return node.parsedSourceMap || undefined;
98814         }
98815         function pipelineEmitWithSourceMap(hint, node) {
98816             ts.Debug.assert(lastNode === node || lastSubstitution === node);
98817             var pipelinePhase = getNextPipelinePhase(3 /* SourceMaps */, hint, node);
98818             if (ts.isUnparsedSource(node) || ts.isUnparsedPrepend(node)) {
98819                 pipelinePhase(hint, node);
98820             }
98821             else if (ts.isUnparsedNode(node)) {
98822                 var parsed = getParsedSourceMap(node.parent);
98823                 if (parsed && sourceMapGenerator) {
98824                     sourceMapGenerator.appendSourceMap(writer.getLine(), writer.getColumn(), parsed, node.parent.sourceMapPath, node.parent.getLineAndCharacterOfPosition(node.pos), node.parent.getLineAndCharacterOfPosition(node.end));
98825                 }
98826                 pipelinePhase(hint, node);
98827             }
98828             else {
98829                 var _a = ts.getSourceMapRange(node), pos = _a.pos, end = _a.end, _b = _a.source, source = _b === void 0 ? sourceMapSource : _b;
98830                 var emitFlags = ts.getEmitFlags(node);
98831                 if (node.kind !== 325 /* NotEmittedStatement */
98832                     && (emitFlags & 16 /* NoLeadingSourceMap */) === 0
98833                     && pos >= 0) {
98834                     emitSourcePos(source, skipSourceTrivia(source, pos));
98835                 }
98836                 if (emitFlags & 64 /* NoNestedSourceMaps */) {
98837                     sourceMapsDisabled = true;
98838                     pipelinePhase(hint, node);
98839                     sourceMapsDisabled = false;
98840                 }
98841                 else {
98842                     pipelinePhase(hint, node);
98843                 }
98844                 if (node.kind !== 325 /* NotEmittedStatement */
98845                     && (emitFlags & 32 /* NoTrailingSourceMap */) === 0
98846                     && end >= 0) {
98847                     emitSourcePos(source, end);
98848                 }
98849             }
98850             ts.Debug.assert(lastNode === node || lastSubstitution === node);
98851         }
98852         /**
98853          * Skips trivia such as comments and white-space that can be optionally overridden by the source-map source
98854          */
98855         function skipSourceTrivia(source, pos) {
98856             return source.skipTrivia ? source.skipTrivia(pos) : ts.skipTrivia(source.text, pos);
98857         }
98858         /**
98859          * Emits a mapping.
98860          *
98861          * If the position is synthetic (undefined or a negative value), no mapping will be
98862          * created.
98863          *
98864          * @param pos The position.
98865          */
98866         function emitPos(pos) {
98867             if (sourceMapsDisabled || ts.positionIsSynthesized(pos) || isJsonSourceMapSource(sourceMapSource)) {
98868                 return;
98869             }
98870             var _a = ts.getLineAndCharacterOfPosition(sourceMapSource, pos), sourceLine = _a.line, sourceCharacter = _a.character;
98871             sourceMapGenerator.addMapping(writer.getLine(), writer.getColumn(), sourceMapSourceIndex, sourceLine, sourceCharacter, 
98872             /*nameIndex*/ undefined);
98873         }
98874         function emitSourcePos(source, pos) {
98875             if (source !== sourceMapSource) {
98876                 var savedSourceMapSource = sourceMapSource;
98877                 setSourceMapSource(source);
98878                 emitPos(pos);
98879                 setSourceMapSource(savedSourceMapSource);
98880             }
98881             else {
98882                 emitPos(pos);
98883             }
98884         }
98885         /**
98886          * Emits a token of a node with possible leading and trailing source maps.
98887          *
98888          * @param node The node containing the token.
98889          * @param token The token to emit.
98890          * @param tokenStartPos The start pos of the token.
98891          * @param emitCallback The callback used to emit the token.
98892          */
98893         function emitTokenWithSourceMap(node, token, writer, tokenPos, emitCallback) {
98894             if (sourceMapsDisabled || node && ts.isInJsonFile(node)) {
98895                 return emitCallback(token, writer, tokenPos);
98896             }
98897             var emitNode = node && node.emitNode;
98898             var emitFlags = emitNode && emitNode.flags || 0 /* None */;
98899             var range = emitNode && emitNode.tokenSourceMapRanges && emitNode.tokenSourceMapRanges[token];
98900             var source = range && range.source || sourceMapSource;
98901             tokenPos = skipSourceTrivia(source, range ? range.pos : tokenPos);
98902             if ((emitFlags & 128 /* NoTokenLeadingSourceMaps */) === 0 && tokenPos >= 0) {
98903                 emitSourcePos(source, tokenPos);
98904             }
98905             tokenPos = emitCallback(token, writer, tokenPos);
98906             if (range)
98907                 tokenPos = range.end;
98908             if ((emitFlags & 256 /* NoTokenTrailingSourceMaps */) === 0 && tokenPos >= 0) {
98909                 emitSourcePos(source, tokenPos);
98910             }
98911             return tokenPos;
98912         }
98913         function setSourceMapSource(source) {
98914             if (sourceMapsDisabled) {
98915                 return;
98916             }
98917             sourceMapSource = source;
98918             if (isJsonSourceMapSource(source)) {
98919                 return;
98920             }
98921             sourceMapSourceIndex = sourceMapGenerator.addSource(source.fileName);
98922             if (printerOptions.inlineSources) {
98923                 sourceMapGenerator.setSourceContent(sourceMapSourceIndex, source.text);
98924             }
98925         }
98926         function isJsonSourceMapSource(sourceFile) {
98927             return ts.fileExtensionIs(sourceFile.fileName, ".json" /* Json */);
98928         }
98929     }
98930     ts.createPrinter = createPrinter;
98931     function createBracketsMap() {
98932         var brackets = [];
98933         brackets[1024 /* Braces */] = ["{", "}"];
98934         brackets[2048 /* Parenthesis */] = ["(", ")"];
98935         brackets[4096 /* AngleBrackets */] = ["<", ">"];
98936         brackets[8192 /* SquareBrackets */] = ["[", "]"];
98937         return brackets;
98938     }
98939     function getOpeningBracket(format) {
98940         return brackets[format & 15360 /* BracketsMask */][0];
98941     }
98942     function getClosingBracket(format) {
98943         return brackets[format & 15360 /* BracketsMask */][1];
98944     }
98945     // Flags enum to track count of temp variables and a few dedicated names
98946     var TempFlags;
98947     (function (TempFlags) {
98948         TempFlags[TempFlags["Auto"] = 0] = "Auto";
98949         TempFlags[TempFlags["CountMask"] = 268435455] = "CountMask";
98950         TempFlags[TempFlags["_i"] = 268435456] = "_i";
98951     })(TempFlags || (TempFlags = {}));
98952 })(ts || (ts = {}));
98953 /* @internal */
98954 var ts;
98955 (function (ts) {
98956     function createCachedDirectoryStructureHost(host, currentDirectory, useCaseSensitiveFileNames) {
98957         if (!host.getDirectories || !host.readDirectory) {
98958             return undefined;
98959         }
98960         var cachedReadDirectoryResult = ts.createMap();
98961         var getCanonicalFileName = ts.createGetCanonicalFileName(useCaseSensitiveFileNames);
98962         return {
98963             useCaseSensitiveFileNames: useCaseSensitiveFileNames,
98964             fileExists: fileExists,
98965             readFile: function (path, encoding) { return host.readFile(path, encoding); },
98966             directoryExists: host.directoryExists && directoryExists,
98967             getDirectories: getDirectories,
98968             readDirectory: readDirectory,
98969             createDirectory: host.createDirectory && createDirectory,
98970             writeFile: host.writeFile && writeFile,
98971             addOrDeleteFileOrDirectory: addOrDeleteFileOrDirectory,
98972             addOrDeleteFile: addOrDeleteFile,
98973             clearCache: clearCache,
98974             realpath: host.realpath && realpath
98975         };
98976         function toPath(fileName) {
98977             return ts.toPath(fileName, currentDirectory, getCanonicalFileName);
98978         }
98979         function getCachedFileSystemEntries(rootDirPath) {
98980             return cachedReadDirectoryResult.get(ts.ensureTrailingDirectorySeparator(rootDirPath));
98981         }
98982         function getCachedFileSystemEntriesForBaseDir(path) {
98983             return getCachedFileSystemEntries(ts.getDirectoryPath(path));
98984         }
98985         function getBaseNameOfFileName(fileName) {
98986             return ts.getBaseFileName(ts.normalizePath(fileName));
98987         }
98988         function createCachedFileSystemEntries(rootDir, rootDirPath) {
98989             var resultFromHost = {
98990                 files: ts.map(host.readDirectory(rootDir, /*extensions*/ undefined, /*exclude*/ undefined, /*include*/ ["*.*"]), getBaseNameOfFileName) || [],
98991                 directories: host.getDirectories(rootDir) || []
98992             };
98993             cachedReadDirectoryResult.set(ts.ensureTrailingDirectorySeparator(rootDirPath), resultFromHost);
98994             return resultFromHost;
98995         }
98996         /**
98997          * If the readDirectory result was already cached, it returns that
98998          * Otherwise gets result from host and caches it.
98999          * The host request is done under try catch block to avoid caching incorrect result
99000          */
99001         function tryReadDirectory(rootDir, rootDirPath) {
99002             rootDirPath = ts.ensureTrailingDirectorySeparator(rootDirPath);
99003             var cachedResult = getCachedFileSystemEntries(rootDirPath);
99004             if (cachedResult) {
99005                 return cachedResult;
99006             }
99007             try {
99008                 return createCachedFileSystemEntries(rootDir, rootDirPath);
99009             }
99010             catch (_e) {
99011                 // If there is exception to read directories, dont cache the result and direct the calls to host
99012                 ts.Debug.assert(!cachedReadDirectoryResult.has(ts.ensureTrailingDirectorySeparator(rootDirPath)));
99013                 return undefined;
99014             }
99015         }
99016         function fileNameEqual(name1, name2) {
99017             return getCanonicalFileName(name1) === getCanonicalFileName(name2);
99018         }
99019         function hasEntry(entries, name) {
99020             return ts.some(entries, function (file) { return fileNameEqual(file, name); });
99021         }
99022         function updateFileSystemEntry(entries, baseName, isValid) {
99023             if (hasEntry(entries, baseName)) {
99024                 if (!isValid) {
99025                     return ts.filterMutate(entries, function (entry) { return !fileNameEqual(entry, baseName); });
99026                 }
99027             }
99028             else if (isValid) {
99029                 return entries.push(baseName);
99030             }
99031         }
99032         function writeFile(fileName, data, writeByteOrderMark) {
99033             var path = toPath(fileName);
99034             var result = getCachedFileSystemEntriesForBaseDir(path);
99035             if (result) {
99036                 updateFilesOfFileSystemEntry(result, getBaseNameOfFileName(fileName), /*fileExists*/ true);
99037             }
99038             return host.writeFile(fileName, data, writeByteOrderMark);
99039         }
99040         function fileExists(fileName) {
99041             var path = toPath(fileName);
99042             var result = getCachedFileSystemEntriesForBaseDir(path);
99043             return result && hasEntry(result.files, getBaseNameOfFileName(fileName)) ||
99044                 host.fileExists(fileName);
99045         }
99046         function directoryExists(dirPath) {
99047             var path = toPath(dirPath);
99048             return cachedReadDirectoryResult.has(ts.ensureTrailingDirectorySeparator(path)) || host.directoryExists(dirPath);
99049         }
99050         function createDirectory(dirPath) {
99051             var path = toPath(dirPath);
99052             var result = getCachedFileSystemEntriesForBaseDir(path);
99053             var baseFileName = getBaseNameOfFileName(dirPath);
99054             if (result) {
99055                 updateFileSystemEntry(result.directories, baseFileName, /*isValid*/ true);
99056             }
99057             host.createDirectory(dirPath);
99058         }
99059         function getDirectories(rootDir) {
99060             var rootDirPath = toPath(rootDir);
99061             var result = tryReadDirectory(rootDir, rootDirPath);
99062             if (result) {
99063                 return result.directories.slice();
99064             }
99065             return host.getDirectories(rootDir);
99066         }
99067         function readDirectory(rootDir, extensions, excludes, includes, depth) {
99068             var rootDirPath = toPath(rootDir);
99069             var result = tryReadDirectory(rootDir, rootDirPath);
99070             if (result) {
99071                 return ts.matchFiles(rootDir, extensions, excludes, includes, useCaseSensitiveFileNames, currentDirectory, depth, getFileSystemEntries, realpath);
99072             }
99073             return host.readDirectory(rootDir, extensions, excludes, includes, depth);
99074             function getFileSystemEntries(dir) {
99075                 var path = toPath(dir);
99076                 if (path === rootDirPath) {
99077                     return result;
99078                 }
99079                 return tryReadDirectory(dir, path) || ts.emptyFileSystemEntries;
99080             }
99081         }
99082         function realpath(s) {
99083             return host.realpath ? host.realpath(s) : s;
99084         }
99085         function addOrDeleteFileOrDirectory(fileOrDirectory, fileOrDirectoryPath) {
99086             var existingResult = getCachedFileSystemEntries(fileOrDirectoryPath);
99087             if (existingResult) {
99088                 // Just clear the cache for now
99089                 // For now just clear the cache, since this could mean that multiple level entries might need to be re-evaluated
99090                 clearCache();
99091                 return undefined;
99092             }
99093             var parentResult = getCachedFileSystemEntriesForBaseDir(fileOrDirectoryPath);
99094             if (!parentResult) {
99095                 return undefined;
99096             }
99097             // This was earlier a file (hence not in cached directory contents)
99098             // or we never cached the directory containing it
99099             if (!host.directoryExists) {
99100                 // Since host doesnt support directory exists, clear the cache as otherwise it might not be same
99101                 clearCache();
99102                 return undefined;
99103             }
99104             var baseName = getBaseNameOfFileName(fileOrDirectory);
99105             var fsQueryResult = {
99106                 fileExists: host.fileExists(fileOrDirectoryPath),
99107                 directoryExists: host.directoryExists(fileOrDirectoryPath)
99108             };
99109             if (fsQueryResult.directoryExists || hasEntry(parentResult.directories, baseName)) {
99110                 // Folder added or removed, clear the cache instead of updating the folder and its structure
99111                 clearCache();
99112             }
99113             else {
99114                 // No need to update the directory structure, just files
99115                 updateFilesOfFileSystemEntry(parentResult, baseName, fsQueryResult.fileExists);
99116             }
99117             return fsQueryResult;
99118         }
99119         function addOrDeleteFile(fileName, filePath, eventKind) {
99120             if (eventKind === ts.FileWatcherEventKind.Changed) {
99121                 return;
99122             }
99123             var parentResult = getCachedFileSystemEntriesForBaseDir(filePath);
99124             if (parentResult) {
99125                 updateFilesOfFileSystemEntry(parentResult, getBaseNameOfFileName(fileName), eventKind === ts.FileWatcherEventKind.Created);
99126             }
99127         }
99128         function updateFilesOfFileSystemEntry(parentResult, baseName, fileExists) {
99129             updateFileSystemEntry(parentResult.files, baseName, fileExists);
99130         }
99131         function clearCache() {
99132             cachedReadDirectoryResult.clear();
99133         }
99134     }
99135     ts.createCachedDirectoryStructureHost = createCachedDirectoryStructureHost;
99136     var ConfigFileProgramReloadLevel;
99137     (function (ConfigFileProgramReloadLevel) {
99138         ConfigFileProgramReloadLevel[ConfigFileProgramReloadLevel["None"] = 0] = "None";
99139         /** Update the file name list from the disk */
99140         ConfigFileProgramReloadLevel[ConfigFileProgramReloadLevel["Partial"] = 1] = "Partial";
99141         /** Reload completely by re-reading contents of config file from disk and updating program */
99142         ConfigFileProgramReloadLevel[ConfigFileProgramReloadLevel["Full"] = 2] = "Full";
99143     })(ConfigFileProgramReloadLevel = ts.ConfigFileProgramReloadLevel || (ts.ConfigFileProgramReloadLevel = {}));
99144     /**
99145      * Updates the existing missing file watches with the new set of missing files after new program is created
99146      */
99147     function updateMissingFilePathsWatch(program, missingFileWatches, createMissingFileWatch) {
99148         var missingFilePaths = program.getMissingFilePaths();
99149         var newMissingFilePathMap = ts.arrayToSet(missingFilePaths);
99150         // Update the missing file paths watcher
99151         ts.mutateMap(missingFileWatches, newMissingFilePathMap, {
99152             // Watch the missing files
99153             createNewValue: createMissingFileWatch,
99154             // Files that are no longer missing (e.g. because they are no longer required)
99155             // should no longer be watched.
99156             onDeleteValue: ts.closeFileWatcher
99157         });
99158     }
99159     ts.updateMissingFilePathsWatch = updateMissingFilePathsWatch;
99160     /**
99161      * Updates the existing wild card directory watches with the new set of wild card directories from the config file
99162      * after new program is created because the config file was reloaded or program was created first time from the config file
99163      * Note that there is no need to call this function when the program is updated with additional files without reloading config files,
99164      * as wildcard directories wont change unless reloading config file
99165      */
99166     function updateWatchingWildcardDirectories(existingWatchedForWildcards, wildcardDirectories, watchDirectory) {
99167         ts.mutateMap(existingWatchedForWildcards, wildcardDirectories, {
99168             // Create new watch and recursive info
99169             createNewValue: createWildcardDirectoryWatcher,
99170             // Close existing watch thats not needed any more
99171             onDeleteValue: closeFileWatcherOf,
99172             // Close existing watch that doesnt match in the flags
99173             onExistingValue: updateWildcardDirectoryWatcher
99174         });
99175         function createWildcardDirectoryWatcher(directory, flags) {
99176             // Create new watch and recursive info
99177             return {
99178                 watcher: watchDirectory(directory, flags),
99179                 flags: flags
99180             };
99181         }
99182         function updateWildcardDirectoryWatcher(existingWatcher, flags, directory) {
99183             // Watcher needs to be updated if the recursive flags dont match
99184             if (existingWatcher.flags === flags) {
99185                 return;
99186             }
99187             existingWatcher.watcher.close();
99188             existingWatchedForWildcards.set(directory, createWildcardDirectoryWatcher(directory, flags));
99189         }
99190     }
99191     ts.updateWatchingWildcardDirectories = updateWatchingWildcardDirectories;
99192     function isEmittedFileOfProgram(program, file) {
99193         if (!program) {
99194             return false;
99195         }
99196         return program.isEmittedFile(file);
99197     }
99198     ts.isEmittedFileOfProgram = isEmittedFileOfProgram;
99199     var WatchLogLevel;
99200     (function (WatchLogLevel) {
99201         WatchLogLevel[WatchLogLevel["None"] = 0] = "None";
99202         WatchLogLevel[WatchLogLevel["TriggerOnly"] = 1] = "TriggerOnly";
99203         WatchLogLevel[WatchLogLevel["Verbose"] = 2] = "Verbose";
99204     })(WatchLogLevel = ts.WatchLogLevel || (ts.WatchLogLevel = {}));
99205     function getWatchFactory(watchLogLevel, log, getDetailWatchInfo) {
99206         return getWatchFactoryWith(watchLogLevel, log, getDetailWatchInfo, watchFile, watchDirectory);
99207     }
99208     ts.getWatchFactory = getWatchFactory;
99209     function getWatchFactoryWith(watchLogLevel, log, getDetailWatchInfo, watchFile, watchDirectory) {
99210         var createFileWatcher = getCreateFileWatcher(watchLogLevel, watchFile);
99211         var createFilePathWatcher = watchLogLevel === WatchLogLevel.None ? watchFilePath : createFileWatcher;
99212         var createDirectoryWatcher = getCreateFileWatcher(watchLogLevel, watchDirectory);
99213         if (watchLogLevel === WatchLogLevel.Verbose && ts.sysLog === ts.noop) {
99214             ts.setSysLog(function (s) { return log(s); });
99215         }
99216         return {
99217             watchFile: function (host, file, callback, pollingInterval, options, detailInfo1, detailInfo2) {
99218                 return createFileWatcher(host, file, callback, pollingInterval, options, /*passThrough*/ undefined, detailInfo1, detailInfo2, watchFile, log, "FileWatcher", getDetailWatchInfo);
99219             },
99220             watchFilePath: function (host, file, callback, pollingInterval, options, path, detailInfo1, detailInfo2) {
99221                 return createFilePathWatcher(host, file, callback, pollingInterval, options, path, detailInfo1, detailInfo2, watchFile, log, "FileWatcher", getDetailWatchInfo);
99222             },
99223             watchDirectory: function (host, directory, callback, flags, options, detailInfo1, detailInfo2) {
99224                 return createDirectoryWatcher(host, directory, callback, flags, options, /*passThrough*/ undefined, detailInfo1, detailInfo2, watchDirectory, log, "DirectoryWatcher", getDetailWatchInfo);
99225             }
99226         };
99227     }
99228     function watchFile(host, file, callback, pollingInterval, options) {
99229         return host.watchFile(file, callback, pollingInterval, options);
99230     }
99231     function watchFilePath(host, file, callback, pollingInterval, options, path) {
99232         return watchFile(host, file, function (fileName, eventKind) { return callback(fileName, eventKind, path); }, pollingInterval, options);
99233     }
99234     function watchDirectory(host, directory, callback, flags, options) {
99235         return host.watchDirectory(directory, callback, (flags & 1 /* Recursive */) !== 0, options);
99236     }
99237     function getCreateFileWatcher(watchLogLevel, addWatch) {
99238         switch (watchLogLevel) {
99239             case WatchLogLevel.None:
99240                 return addWatch;
99241             case WatchLogLevel.TriggerOnly:
99242                 return createFileWatcherWithTriggerLogging;
99243             case WatchLogLevel.Verbose:
99244                 return addWatch === watchDirectory ? createDirectoryWatcherWithLogging : createFileWatcherWithLogging;
99245         }
99246     }
99247     function createFileWatcherWithLogging(host, file, cb, flags, options, passThrough, detailInfo1, detailInfo2, addWatch, log, watchCaption, getDetailWatchInfo) {
99248         log(watchCaption + ":: Added:: " + getWatchInfo(file, flags, options, detailInfo1, detailInfo2, getDetailWatchInfo));
99249         var watcher = createFileWatcherWithTriggerLogging(host, file, cb, flags, options, passThrough, detailInfo1, detailInfo2, addWatch, log, watchCaption, getDetailWatchInfo);
99250         return {
99251             close: function () {
99252                 log(watchCaption + ":: Close:: " + getWatchInfo(file, flags, options, detailInfo1, detailInfo2, getDetailWatchInfo));
99253                 watcher.close();
99254             }
99255         };
99256     }
99257     function createDirectoryWatcherWithLogging(host, file, cb, flags, options, passThrough, detailInfo1, detailInfo2, addWatch, log, watchCaption, getDetailWatchInfo) {
99258         var watchInfo = watchCaption + ":: Added:: " + getWatchInfo(file, flags, options, detailInfo1, detailInfo2, getDetailWatchInfo);
99259         log(watchInfo);
99260         var start = ts.timestamp();
99261         var watcher = createFileWatcherWithTriggerLogging(host, file, cb, flags, options, passThrough, detailInfo1, detailInfo2, addWatch, log, watchCaption, getDetailWatchInfo);
99262         var elapsed = ts.timestamp() - start;
99263         log("Elapsed:: " + elapsed + "ms " + watchInfo);
99264         return {
99265             close: function () {
99266                 var watchInfo = watchCaption + ":: Close:: " + getWatchInfo(file, flags, options, detailInfo1, detailInfo2, getDetailWatchInfo);
99267                 log(watchInfo);
99268                 var start = ts.timestamp();
99269                 watcher.close();
99270                 var elapsed = ts.timestamp() - start;
99271                 log("Elapsed:: " + elapsed + "ms " + watchInfo);
99272             }
99273         };
99274     }
99275     function createFileWatcherWithTriggerLogging(host, file, cb, flags, options, passThrough, detailInfo1, detailInfo2, addWatch, log, watchCaption, getDetailWatchInfo) {
99276         return addWatch(host, file, function (fileName, cbOptional) {
99277             var triggerredInfo = watchCaption + ":: Triggered with " + fileName + " " + (cbOptional !== undefined ? cbOptional : "") + ":: " + getWatchInfo(file, flags, options, detailInfo1, detailInfo2, getDetailWatchInfo);
99278             log(triggerredInfo);
99279             var start = ts.timestamp();
99280             cb(fileName, cbOptional, passThrough);
99281             var elapsed = ts.timestamp() - start;
99282             log("Elapsed:: " + elapsed + "ms " + triggerredInfo);
99283         }, flags, options);
99284     }
99285     function getFallbackOptions(options) {
99286         var fallbackPolling = options === null || options === void 0 ? void 0 : options.fallbackPolling;
99287         return {
99288             watchFile: fallbackPolling !== undefined ?
99289                 fallbackPolling :
99290                 ts.WatchFileKind.PriorityPollingInterval
99291         };
99292     }
99293     ts.getFallbackOptions = getFallbackOptions;
99294     function getWatchInfo(file, flags, options, detailInfo1, detailInfo2, getDetailWatchInfo) {
99295         return "WatchInfo: " + file + " " + flags + " " + JSON.stringify(options) + " " + (getDetailWatchInfo ? getDetailWatchInfo(detailInfo1, detailInfo2) : detailInfo2 === undefined ? detailInfo1 : detailInfo1 + " " + detailInfo2);
99296     }
99297     function closeFileWatcherOf(objWithWatcher) {
99298         objWithWatcher.watcher.close();
99299     }
99300     ts.closeFileWatcherOf = closeFileWatcherOf;
99301 })(ts || (ts = {}));
99302 var ts;
99303 (function (ts) {
99304     function findConfigFile(searchPath, fileExists, configName) {
99305         if (configName === void 0) { configName = "tsconfig.json"; }
99306         return ts.forEachAncestorDirectory(searchPath, function (ancestor) {
99307             var fileName = ts.combinePaths(ancestor, configName);
99308             return fileExists(fileName) ? fileName : undefined;
99309         });
99310     }
99311     ts.findConfigFile = findConfigFile;
99312     function resolveTripleslashReference(moduleName, containingFile) {
99313         var basePath = ts.getDirectoryPath(containingFile);
99314         var referencedFileName = ts.isRootedDiskPath(moduleName) ? moduleName : ts.combinePaths(basePath, moduleName);
99315         return ts.normalizePath(referencedFileName);
99316     }
99317     ts.resolveTripleslashReference = resolveTripleslashReference;
99318     /* @internal */
99319     function computeCommonSourceDirectoryOfFilenames(fileNames, currentDirectory, getCanonicalFileName) {
99320         var commonPathComponents;
99321         var failed = ts.forEach(fileNames, function (sourceFile) {
99322             // Each file contributes into common source file path
99323             var sourcePathComponents = ts.getNormalizedPathComponents(sourceFile, currentDirectory);
99324             sourcePathComponents.pop(); // The base file name is not part of the common directory path
99325             if (!commonPathComponents) {
99326                 // first file
99327                 commonPathComponents = sourcePathComponents;
99328                 return;
99329             }
99330             var n = Math.min(commonPathComponents.length, sourcePathComponents.length);
99331             for (var i = 0; i < n; i++) {
99332                 if (getCanonicalFileName(commonPathComponents[i]) !== getCanonicalFileName(sourcePathComponents[i])) {
99333                     if (i === 0) {
99334                         // Failed to find any common path component
99335                         return true;
99336                     }
99337                     // New common path found that is 0 -> i-1
99338                     commonPathComponents.length = i;
99339                     break;
99340                 }
99341             }
99342             // If the sourcePathComponents was shorter than the commonPathComponents, truncate to the sourcePathComponents
99343             if (sourcePathComponents.length < commonPathComponents.length) {
99344                 commonPathComponents.length = sourcePathComponents.length;
99345             }
99346         });
99347         // A common path can not be found when paths span multiple drives on windows, for example
99348         if (failed) {
99349             return "";
99350         }
99351         if (!commonPathComponents) { // Can happen when all input files are .d.ts files
99352             return currentDirectory;
99353         }
99354         return ts.getPathFromPathComponents(commonPathComponents);
99355     }
99356     ts.computeCommonSourceDirectoryOfFilenames = computeCommonSourceDirectoryOfFilenames;
99357     function createCompilerHost(options, setParentNodes) {
99358         return createCompilerHostWorker(options, setParentNodes);
99359     }
99360     ts.createCompilerHost = createCompilerHost;
99361     /*@internal*/
99362     // TODO(shkamat): update this after reworking ts build API
99363     function createCompilerHostWorker(options, setParentNodes, system) {
99364         if (system === void 0) { system = ts.sys; }
99365         var existingDirectories = ts.createMap();
99366         var getCanonicalFileName = ts.createGetCanonicalFileName(system.useCaseSensitiveFileNames);
99367         function getSourceFile(fileName, languageVersion, onError) {
99368             var text;
99369             try {
99370                 ts.performance.mark("beforeIORead");
99371                 text = compilerHost.readFile(fileName);
99372                 ts.performance.mark("afterIORead");
99373                 ts.performance.measure("I/O Read", "beforeIORead", "afterIORead");
99374             }
99375             catch (e) {
99376                 if (onError) {
99377                     onError(e.message);
99378                 }
99379                 text = "";
99380             }
99381             return text !== undefined ? ts.createSourceFile(fileName, text, languageVersion, setParentNodes) : undefined;
99382         }
99383         function directoryExists(directoryPath) {
99384             if (existingDirectories.has(directoryPath)) {
99385                 return true;
99386             }
99387             if ((compilerHost.directoryExists || system.directoryExists)(directoryPath)) {
99388                 existingDirectories.set(directoryPath, true);
99389                 return true;
99390             }
99391             return false;
99392         }
99393         function writeFile(fileName, data, writeByteOrderMark, onError) {
99394             try {
99395                 ts.performance.mark("beforeIOWrite");
99396                 // NOTE: If patchWriteFileEnsuringDirectory has been called,
99397                 // the system.writeFile will do its own directory creation and
99398                 // the ensureDirectoriesExist call will always be redundant.
99399                 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); });
99400                 ts.performance.mark("afterIOWrite");
99401                 ts.performance.measure("I/O Write", "beforeIOWrite", "afterIOWrite");
99402             }
99403             catch (e) {
99404                 if (onError) {
99405                     onError(e.message);
99406                 }
99407             }
99408         }
99409         var outputFingerprints;
99410         function writeFileWorker(fileName, data, writeByteOrderMark) {
99411             if (!ts.isWatchSet(options) || !system.createHash || !system.getModifiedTime) {
99412                 system.writeFile(fileName, data, writeByteOrderMark);
99413                 return;
99414             }
99415             if (!outputFingerprints) {
99416                 outputFingerprints = ts.createMap();
99417             }
99418             var hash = system.createHash(data);
99419             var mtimeBefore = system.getModifiedTime(fileName);
99420             if (mtimeBefore) {
99421                 var fingerprint = outputFingerprints.get(fileName);
99422                 // If output has not been changed, and the file has no external modification
99423                 if (fingerprint &&
99424                     fingerprint.byteOrderMark === writeByteOrderMark &&
99425                     fingerprint.hash === hash &&
99426                     fingerprint.mtime.getTime() === mtimeBefore.getTime()) {
99427                     return;
99428                 }
99429             }
99430             system.writeFile(fileName, data, writeByteOrderMark);
99431             var mtimeAfter = system.getModifiedTime(fileName) || ts.missingFileModifiedTime;
99432             outputFingerprints.set(fileName, {
99433                 hash: hash,
99434                 byteOrderMark: writeByteOrderMark,
99435                 mtime: mtimeAfter
99436             });
99437         }
99438         function getDefaultLibLocation() {
99439             return ts.getDirectoryPath(ts.normalizePath(system.getExecutingFilePath()));
99440         }
99441         var newLine = ts.getNewLineCharacter(options, function () { return system.newLine; });
99442         var realpath = system.realpath && (function (path) { return system.realpath(path); });
99443         var compilerHost = {
99444             getSourceFile: getSourceFile,
99445             getDefaultLibLocation: getDefaultLibLocation,
99446             getDefaultLibFileName: function (options) { return ts.combinePaths(getDefaultLibLocation(), ts.getDefaultLibFileName(options)); },
99447             writeFile: writeFile,
99448             getCurrentDirectory: ts.memoize(function () { return system.getCurrentDirectory(); }),
99449             useCaseSensitiveFileNames: function () { return system.useCaseSensitiveFileNames; },
99450             getCanonicalFileName: getCanonicalFileName,
99451             getNewLine: function () { return newLine; },
99452             fileExists: function (fileName) { return system.fileExists(fileName); },
99453             readFile: function (fileName) { return system.readFile(fileName); },
99454             trace: function (s) { return system.write(s + newLine); },
99455             directoryExists: function (directoryName) { return system.directoryExists(directoryName); },
99456             getEnvironmentVariable: function (name) { return system.getEnvironmentVariable ? system.getEnvironmentVariable(name) : ""; },
99457             getDirectories: function (path) { return system.getDirectories(path); },
99458             realpath: realpath,
99459             readDirectory: function (path, extensions, include, exclude, depth) { return system.readDirectory(path, extensions, include, exclude, depth); },
99460             createDirectory: function (d) { return system.createDirectory(d); },
99461             createHash: ts.maybeBind(system, system.createHash)
99462         };
99463         return compilerHost;
99464     }
99465     ts.createCompilerHostWorker = createCompilerHostWorker;
99466     /*@internal*/
99467     function changeCompilerHostLikeToUseCache(host, toPath, getSourceFile) {
99468         var originalReadFile = host.readFile;
99469         var originalFileExists = host.fileExists;
99470         var originalDirectoryExists = host.directoryExists;
99471         var originalCreateDirectory = host.createDirectory;
99472         var originalWriteFile = host.writeFile;
99473         var readFileCache = ts.createMap();
99474         var fileExistsCache = ts.createMap();
99475         var directoryExistsCache = ts.createMap();
99476         var sourceFileCache = ts.createMap();
99477         var readFileWithCache = function (fileName) {
99478             var key = toPath(fileName);
99479             var value = readFileCache.get(key);
99480             if (value !== undefined)
99481                 return value !== false ? value : undefined;
99482             return setReadFileCache(key, fileName);
99483         };
99484         var setReadFileCache = function (key, fileName) {
99485             var newValue = originalReadFile.call(host, fileName);
99486             readFileCache.set(key, newValue !== undefined ? newValue : false);
99487             return newValue;
99488         };
99489         host.readFile = function (fileName) {
99490             var key = toPath(fileName);
99491             var value = readFileCache.get(key);
99492             if (value !== undefined)
99493                 return value !== false ? value : undefined; // could be .d.ts from output
99494             // Cache json or buildInfo
99495             if (!ts.fileExtensionIs(fileName, ".json" /* Json */) && !ts.isBuildInfoFile(fileName)) {
99496                 return originalReadFile.call(host, fileName);
99497             }
99498             return setReadFileCache(key, fileName);
99499         };
99500         var getSourceFileWithCache = getSourceFile ? function (fileName, languageVersion, onError, shouldCreateNewSourceFile) {
99501             var key = toPath(fileName);
99502             var value = sourceFileCache.get(key);
99503             if (value)
99504                 return value;
99505             var sourceFile = getSourceFile(fileName, languageVersion, onError, shouldCreateNewSourceFile);
99506             if (sourceFile && (ts.isDeclarationFileName(fileName) || ts.fileExtensionIs(fileName, ".json" /* Json */))) {
99507                 sourceFileCache.set(key, sourceFile);
99508             }
99509             return sourceFile;
99510         } : undefined;
99511         // fileExists for any kind of extension
99512         host.fileExists = function (fileName) {
99513             var key = toPath(fileName);
99514             var value = fileExistsCache.get(key);
99515             if (value !== undefined)
99516                 return value;
99517             var newValue = originalFileExists.call(host, fileName);
99518             fileExistsCache.set(key, !!newValue);
99519             return newValue;
99520         };
99521         if (originalWriteFile) {
99522             host.writeFile = function (fileName, data, writeByteOrderMark, onError, sourceFiles) {
99523                 var key = toPath(fileName);
99524                 fileExistsCache.delete(key);
99525                 var value = readFileCache.get(key);
99526                 if (value !== undefined && value !== data) {
99527                     readFileCache.delete(key);
99528                     sourceFileCache.delete(key);
99529                 }
99530                 else if (getSourceFileWithCache) {
99531                     var sourceFile = sourceFileCache.get(key);
99532                     if (sourceFile && sourceFile.text !== data) {
99533                         sourceFileCache.delete(key);
99534                     }
99535                 }
99536                 originalWriteFile.call(host, fileName, data, writeByteOrderMark, onError, sourceFiles);
99537             };
99538         }
99539         // directoryExists
99540         if (originalDirectoryExists && originalCreateDirectory) {
99541             host.directoryExists = function (directory) {
99542                 var key = toPath(directory);
99543                 var value = directoryExistsCache.get(key);
99544                 if (value !== undefined)
99545                     return value;
99546                 var newValue = originalDirectoryExists.call(host, directory);
99547                 directoryExistsCache.set(key, !!newValue);
99548                 return newValue;
99549             };
99550             host.createDirectory = function (directory) {
99551                 var key = toPath(directory);
99552                 directoryExistsCache.delete(key);
99553                 originalCreateDirectory.call(host, directory);
99554             };
99555         }
99556         return {
99557             originalReadFile: originalReadFile,
99558             originalFileExists: originalFileExists,
99559             originalDirectoryExists: originalDirectoryExists,
99560             originalCreateDirectory: originalCreateDirectory,
99561             originalWriteFile: originalWriteFile,
99562             getSourceFileWithCache: getSourceFileWithCache,
99563             readFileWithCache: readFileWithCache
99564         };
99565     }
99566     ts.changeCompilerHostLikeToUseCache = changeCompilerHostLikeToUseCache;
99567     function getPreEmitDiagnostics(program, sourceFile, cancellationToken) {
99568         var diagnostics;
99569         diagnostics = ts.addRange(diagnostics, program.getConfigFileParsingDiagnostics());
99570         diagnostics = ts.addRange(diagnostics, program.getOptionsDiagnostics(cancellationToken));
99571         diagnostics = ts.addRange(diagnostics, program.getSyntacticDiagnostics(sourceFile, cancellationToken));
99572         diagnostics = ts.addRange(diagnostics, program.getGlobalDiagnostics(cancellationToken));
99573         diagnostics = ts.addRange(diagnostics, program.getSemanticDiagnostics(sourceFile, cancellationToken));
99574         if (ts.getEmitDeclarations(program.getCompilerOptions())) {
99575             diagnostics = ts.addRange(diagnostics, program.getDeclarationDiagnostics(sourceFile, cancellationToken));
99576         }
99577         return ts.sortAndDeduplicateDiagnostics(diagnostics || ts.emptyArray);
99578     }
99579     ts.getPreEmitDiagnostics = getPreEmitDiagnostics;
99580     function formatDiagnostics(diagnostics, host) {
99581         var output = "";
99582         for (var _i = 0, diagnostics_2 = diagnostics; _i < diagnostics_2.length; _i++) {
99583             var diagnostic = diagnostics_2[_i];
99584             output += formatDiagnostic(diagnostic, host);
99585         }
99586         return output;
99587     }
99588     ts.formatDiagnostics = formatDiagnostics;
99589     function formatDiagnostic(diagnostic, host) {
99590         var errorMessage = ts.diagnosticCategoryName(diagnostic) + " TS" + diagnostic.code + ": " + flattenDiagnosticMessageText(diagnostic.messageText, host.getNewLine()) + host.getNewLine();
99591         if (diagnostic.file) {
99592             var _a = ts.getLineAndCharacterOfPosition(diagnostic.file, diagnostic.start), line = _a.line, character = _a.character; // TODO: GH#18217
99593             var fileName = diagnostic.file.fileName;
99594             var relativeFileName = ts.convertToRelativePath(fileName, host.getCurrentDirectory(), function (fileName) { return host.getCanonicalFileName(fileName); });
99595             return relativeFileName + "(" + (line + 1) + "," + (character + 1) + "): " + errorMessage;
99596         }
99597         return errorMessage;
99598     }
99599     ts.formatDiagnostic = formatDiagnostic;
99600     /** @internal */
99601     var ForegroundColorEscapeSequences;
99602     (function (ForegroundColorEscapeSequences) {
99603         ForegroundColorEscapeSequences["Grey"] = "\u001B[90m";
99604         ForegroundColorEscapeSequences["Red"] = "\u001B[91m";
99605         ForegroundColorEscapeSequences["Yellow"] = "\u001B[93m";
99606         ForegroundColorEscapeSequences["Blue"] = "\u001B[94m";
99607         ForegroundColorEscapeSequences["Cyan"] = "\u001B[96m";
99608     })(ForegroundColorEscapeSequences = ts.ForegroundColorEscapeSequences || (ts.ForegroundColorEscapeSequences = {}));
99609     var gutterStyleSequence = "\u001b[7m";
99610     var gutterSeparator = " ";
99611     var resetEscapeSequence = "\u001b[0m";
99612     var ellipsis = "...";
99613     var halfIndent = "  ";
99614     var indent = "    ";
99615     function getCategoryFormat(category) {
99616         switch (category) {
99617             case ts.DiagnosticCategory.Error: return ForegroundColorEscapeSequences.Red;
99618             case ts.DiagnosticCategory.Warning: return ForegroundColorEscapeSequences.Yellow;
99619             case ts.DiagnosticCategory.Suggestion: return ts.Debug.fail("Should never get an Info diagnostic on the command line.");
99620             case ts.DiagnosticCategory.Message: return ForegroundColorEscapeSequences.Blue;
99621         }
99622     }
99623     /** @internal */
99624     function formatColorAndReset(text, formatStyle) {
99625         return formatStyle + text + resetEscapeSequence;
99626     }
99627     ts.formatColorAndReset = formatColorAndReset;
99628     function formatCodeSpan(file, start, length, indent, squiggleColor, host) {
99629         var _a = ts.getLineAndCharacterOfPosition(file, start), firstLine = _a.line, firstLineChar = _a.character;
99630         var _b = ts.getLineAndCharacterOfPosition(file, start + length), lastLine = _b.line, lastLineChar = _b.character;
99631         var lastLineInFile = ts.getLineAndCharacterOfPosition(file, file.text.length).line;
99632         var hasMoreThanFiveLines = (lastLine - firstLine) >= 4;
99633         var gutterWidth = (lastLine + 1 + "").length;
99634         if (hasMoreThanFiveLines) {
99635             gutterWidth = Math.max(ellipsis.length, gutterWidth);
99636         }
99637         var context = "";
99638         for (var i = firstLine; i <= lastLine; i++) {
99639             context += host.getNewLine();
99640             // If the error spans over 5 lines, we'll only show the first 2 and last 2 lines,
99641             // so we'll skip ahead to the second-to-last line.
99642             if (hasMoreThanFiveLines && firstLine + 1 < i && i < lastLine - 1) {
99643                 context += indent + formatColorAndReset(ts.padLeft(ellipsis, gutterWidth), gutterStyleSequence) + gutterSeparator + host.getNewLine();
99644                 i = lastLine - 1;
99645             }
99646             var lineStart = ts.getPositionOfLineAndCharacter(file, i, 0);
99647             var lineEnd = i < lastLineInFile ? ts.getPositionOfLineAndCharacter(file, i + 1, 0) : file.text.length;
99648             var lineContent = file.text.slice(lineStart, lineEnd);
99649             lineContent = lineContent.replace(/\s+$/g, ""); // trim from end
99650             lineContent = lineContent.replace("\t", " "); // convert tabs to single spaces
99651             // Output the gutter and the actual contents of the line.
99652             context += indent + formatColorAndReset(ts.padLeft(i + 1 + "", gutterWidth), gutterStyleSequence) + gutterSeparator;
99653             context += lineContent + host.getNewLine();
99654             // Output the gutter and the error span for the line using tildes.
99655             context += indent + formatColorAndReset(ts.padLeft("", gutterWidth), gutterStyleSequence) + gutterSeparator;
99656             context += squiggleColor;
99657             if (i === firstLine) {
99658                 // If we're on the last line, then limit it to the last character of the last line.
99659                 // Otherwise, we'll just squiggle the rest of the line, giving 'slice' no end position.
99660                 var lastCharForLine = i === lastLine ? lastLineChar : undefined;
99661                 context += lineContent.slice(0, firstLineChar).replace(/\S/g, " ");
99662                 context += lineContent.slice(firstLineChar, lastCharForLine).replace(/./g, "~");
99663             }
99664             else if (i === lastLine) {
99665                 context += lineContent.slice(0, lastLineChar).replace(/./g, "~");
99666             }
99667             else {
99668                 // Squiggle the entire line.
99669                 context += lineContent.replace(/./g, "~");
99670             }
99671             context += resetEscapeSequence;
99672         }
99673         return context;
99674     }
99675     /* @internal */
99676     function formatLocation(file, start, host, color) {
99677         if (color === void 0) { color = formatColorAndReset; }
99678         var _a = ts.getLineAndCharacterOfPosition(file, start), firstLine = _a.line, firstLineChar = _a.character; // TODO: GH#18217
99679         var relativeFileName = host ? ts.convertToRelativePath(file.fileName, host.getCurrentDirectory(), function (fileName) { return host.getCanonicalFileName(fileName); }) : file.fileName;
99680         var output = "";
99681         output += color(relativeFileName, ForegroundColorEscapeSequences.Cyan);
99682         output += ":";
99683         output += color("" + (firstLine + 1), ForegroundColorEscapeSequences.Yellow);
99684         output += ":";
99685         output += color("" + (firstLineChar + 1), ForegroundColorEscapeSequences.Yellow);
99686         return output;
99687     }
99688     ts.formatLocation = formatLocation;
99689     function formatDiagnosticsWithColorAndContext(diagnostics, host) {
99690         var output = "";
99691         for (var _i = 0, diagnostics_3 = diagnostics; _i < diagnostics_3.length; _i++) {
99692             var diagnostic = diagnostics_3[_i];
99693             if (diagnostic.file) {
99694                 var file = diagnostic.file, start = diagnostic.start;
99695                 output += formatLocation(file, start, host); // TODO: GH#18217
99696                 output += " - ";
99697             }
99698             output += formatColorAndReset(ts.diagnosticCategoryName(diagnostic), getCategoryFormat(diagnostic.category));
99699             output += formatColorAndReset(" TS" + diagnostic.code + ": ", ForegroundColorEscapeSequences.Grey);
99700             output += flattenDiagnosticMessageText(diagnostic.messageText, host.getNewLine());
99701             if (diagnostic.file) {
99702                 output += host.getNewLine();
99703                 output += formatCodeSpan(diagnostic.file, diagnostic.start, diagnostic.length, "", getCategoryFormat(diagnostic.category), host); // TODO: GH#18217
99704                 if (diagnostic.relatedInformation) {
99705                     output += host.getNewLine();
99706                     for (var _a = 0, _b = diagnostic.relatedInformation; _a < _b.length; _a++) {
99707                         var _c = _b[_a], file = _c.file, start = _c.start, length_8 = _c.length, messageText = _c.messageText;
99708                         if (file) {
99709                             output += host.getNewLine();
99710                             output += halfIndent + formatLocation(file, start, host); // TODO: GH#18217
99711                             output += formatCodeSpan(file, start, length_8, indent, ForegroundColorEscapeSequences.Cyan, host); // TODO: GH#18217
99712                         }
99713                         output += host.getNewLine();
99714                         output += indent + flattenDiagnosticMessageText(messageText, host.getNewLine());
99715                     }
99716                 }
99717             }
99718             output += host.getNewLine();
99719         }
99720         return output;
99721     }
99722     ts.formatDiagnosticsWithColorAndContext = formatDiagnosticsWithColorAndContext;
99723     function flattenDiagnosticMessageText(diag, newLine, indent) {
99724         if (indent === void 0) { indent = 0; }
99725         if (ts.isString(diag)) {
99726             return diag;
99727         }
99728         else if (diag === undefined) {
99729             return "";
99730         }
99731         var result = "";
99732         if (indent) {
99733             result += newLine;
99734             for (var i = 0; i < indent; i++) {
99735                 result += "  ";
99736             }
99737         }
99738         result += diag.messageText;
99739         indent++;
99740         if (diag.next) {
99741             for (var _i = 0, _a = diag.next; _i < _a.length; _i++) {
99742                 var kid = _a[_i];
99743                 result += flattenDiagnosticMessageText(kid, newLine, indent);
99744             }
99745         }
99746         return result;
99747     }
99748     ts.flattenDiagnosticMessageText = flattenDiagnosticMessageText;
99749     /* @internal */
99750     function loadWithLocalCache(names, containingFile, redirectedReference, loader) {
99751         if (names.length === 0) {
99752             return [];
99753         }
99754         var resolutions = [];
99755         var cache = ts.createMap();
99756         for (var _i = 0, names_2 = names; _i < names_2.length; _i++) {
99757             var name = names_2[_i];
99758             var result = void 0;
99759             if (cache.has(name)) {
99760                 result = cache.get(name);
99761             }
99762             else {
99763                 cache.set(name, result = loader(name, containingFile, redirectedReference));
99764             }
99765             resolutions.push(result);
99766         }
99767         return resolutions;
99768     }
99769     ts.loadWithLocalCache = loadWithLocalCache;
99770     /* @internal */
99771     ts.inferredTypesContainingFile = "__inferred type names__.ts";
99772     /**
99773      * Determines if program structure is upto date or needs to be recreated
99774      */
99775     /* @internal */
99776     function isProgramUptoDate(program, rootFileNames, newOptions, getSourceVersion, fileExists, hasInvalidatedResolution, hasChangedAutomaticTypeDirectiveNames, projectReferences) {
99777         // If we haven't created a program yet or have changed automatic type directives, then it is not up-to-date
99778         if (!program || hasChangedAutomaticTypeDirectiveNames) {
99779             return false;
99780         }
99781         // If root file names don't match
99782         if (!ts.arrayIsEqualTo(program.getRootFileNames(), rootFileNames)) {
99783             return false;
99784         }
99785         var seenResolvedRefs;
99786         // If project references don't match
99787         if (!ts.arrayIsEqualTo(program.getProjectReferences(), projectReferences, projectReferenceUptoDate)) {
99788             return false;
99789         }
99790         // If any file is not up-to-date, then the whole program is not up-to-date
99791         if (program.getSourceFiles().some(sourceFileNotUptoDate)) {
99792             return false;
99793         }
99794         // If any of the missing file paths are now created
99795         if (program.getMissingFilePaths().some(fileExists)) {
99796             return false;
99797         }
99798         var currentOptions = program.getCompilerOptions();
99799         // If the compilation settings do no match, then the program is not up-to-date
99800         if (!ts.compareDataObjects(currentOptions, newOptions)) {
99801             return false;
99802         }
99803         // If everything matches but the text of config file is changed,
99804         // error locations can change for program options, so update the program
99805         if (currentOptions.configFile && newOptions.configFile) {
99806             return currentOptions.configFile.text === newOptions.configFile.text;
99807         }
99808         return true;
99809         function sourceFileNotUptoDate(sourceFile) {
99810             return !sourceFileVersionUptoDate(sourceFile) ||
99811                 hasInvalidatedResolution(sourceFile.path);
99812         }
99813         function sourceFileVersionUptoDate(sourceFile) {
99814             return sourceFile.version === getSourceVersion(sourceFile.resolvedPath, sourceFile.fileName);
99815         }
99816         function projectReferenceUptoDate(oldRef, newRef, index) {
99817             if (!ts.projectReferenceIsEqualTo(oldRef, newRef)) {
99818                 return false;
99819             }
99820             return resolvedProjectReferenceUptoDate(program.getResolvedProjectReferences()[index], oldRef);
99821         }
99822         function resolvedProjectReferenceUptoDate(oldResolvedRef, oldRef) {
99823             if (oldResolvedRef) {
99824                 if (ts.contains(seenResolvedRefs, oldResolvedRef)) {
99825                     // Assume true
99826                     return true;
99827                 }
99828                 // If sourceFile for the oldResolvedRef existed, check the version for uptodate
99829                 if (!sourceFileVersionUptoDate(oldResolvedRef.sourceFile)) {
99830                     return false;
99831                 }
99832                 // Add to seen before checking the referenced paths of this config file
99833                 (seenResolvedRefs || (seenResolvedRefs = [])).push(oldResolvedRef);
99834                 // If child project references are upto date, this project reference is uptodate
99835                 return !ts.forEach(oldResolvedRef.references, function (childResolvedRef, index) {
99836                     return !resolvedProjectReferenceUptoDate(childResolvedRef, oldResolvedRef.commandLine.projectReferences[index]);
99837                 });
99838             }
99839             // In old program, not able to resolve project reference path,
99840             // so if config file doesnt exist, it is uptodate.
99841             return !fileExists(resolveProjectReferencePath(oldRef));
99842         }
99843     }
99844     ts.isProgramUptoDate = isProgramUptoDate;
99845     function getConfigFileParsingDiagnostics(configFileParseResult) {
99846         return configFileParseResult.options.configFile ? __spreadArrays(configFileParseResult.options.configFile.parseDiagnostics, configFileParseResult.errors) :
99847             configFileParseResult.errors;
99848     }
99849     ts.getConfigFileParsingDiagnostics = getConfigFileParsingDiagnostics;
99850     /**
99851      * Determine if source file needs to be re-created even if its text hasn't changed
99852      */
99853     function shouldProgramCreateNewSourceFiles(program, newOptions) {
99854         if (!program)
99855             return false;
99856         // If any compiler options change, we can't reuse old source file even if version match
99857         // The change in options like these could result in change in syntax tree or `sourceFile.bindDiagnostics`.
99858         var oldOptions = program.getCompilerOptions();
99859         return !!ts.sourceFileAffectingCompilerOptions.some(function (option) {
99860             return !ts.isJsonEqual(ts.getCompilerOptionValue(oldOptions, option), ts.getCompilerOptionValue(newOptions, option));
99861         });
99862     }
99863     function createCreateProgramOptions(rootNames, options, host, oldProgram, configFileParsingDiagnostics) {
99864         return {
99865             rootNames: rootNames,
99866             options: options,
99867             host: host,
99868             oldProgram: oldProgram,
99869             configFileParsingDiagnostics: configFileParsingDiagnostics
99870         };
99871     }
99872     function createProgram(rootNamesOrOptions, _options, _host, _oldProgram, _configFileParsingDiagnostics) {
99873         var _a;
99874         var createProgramOptions = ts.isArray(rootNamesOrOptions) ? createCreateProgramOptions(rootNamesOrOptions, _options, _host, _oldProgram, _configFileParsingDiagnostics) : rootNamesOrOptions; // TODO: GH#18217
99875         var rootNames = createProgramOptions.rootNames, options = createProgramOptions.options, configFileParsingDiagnostics = createProgramOptions.configFileParsingDiagnostics, projectReferences = createProgramOptions.projectReferences;
99876         var oldProgram = createProgramOptions.oldProgram;
99877         var processingDefaultLibFiles;
99878         var processingOtherFiles;
99879         var files;
99880         var symlinks;
99881         var commonSourceDirectory;
99882         var diagnosticsProducingTypeChecker;
99883         var noDiagnosticsTypeChecker;
99884         var classifiableNames;
99885         var ambientModuleNameToUnmodifiedFileName = ts.createMap();
99886         // Todo:: Use this to report why file was included in --extendedDiagnostics
99887         var refFileMap;
99888         var cachedBindAndCheckDiagnosticsForFile = {};
99889         var cachedDeclarationDiagnosticsForFile = {};
99890         var resolvedTypeReferenceDirectives = ts.createMap();
99891         var fileProcessingDiagnostics = ts.createDiagnosticCollection();
99892         // The below settings are to track if a .js file should be add to the program if loaded via searching under node_modules.
99893         // This works as imported modules are discovered recursively in a depth first manner, specifically:
99894         // - For each root file, findSourceFile is called.
99895         // - This calls processImportedModules for each module imported in the source file.
99896         // - This calls resolveModuleNames, and then calls findSourceFile for each resolved module.
99897         // As all these operations happen - and are nested - within the createProgram call, they close over the below variables.
99898         // The current resolution depth is tracked by incrementing/decrementing as the depth first search progresses.
99899         var maxNodeModuleJsDepth = typeof options.maxNodeModuleJsDepth === "number" ? options.maxNodeModuleJsDepth : 0;
99900         var currentNodeModulesDepth = 0;
99901         // If a module has some of its imports skipped due to being at the depth limit under node_modules, then track
99902         // this, as it may be imported at a shallower depth later, and then it will need its skipped imports processed.
99903         var modulesWithElidedImports = ts.createMap();
99904         // Track source files that are source files found by searching under node_modules, as these shouldn't be compiled.
99905         var sourceFilesFoundSearchingNodeModules = ts.createMap();
99906         ts.performance.mark("beforeProgram");
99907         var host = createProgramOptions.host || createCompilerHost(options);
99908         var configParsingHost = parseConfigHostFromCompilerHostLike(host);
99909         var skipDefaultLib = options.noLib;
99910         var getDefaultLibraryFileName = ts.memoize(function () { return host.getDefaultLibFileName(options); });
99911         var defaultLibraryPath = host.getDefaultLibLocation ? host.getDefaultLibLocation() : ts.getDirectoryPath(getDefaultLibraryFileName());
99912         var programDiagnostics = ts.createDiagnosticCollection();
99913         var currentDirectory = host.getCurrentDirectory();
99914         var supportedExtensions = ts.getSupportedExtensions(options);
99915         var supportedExtensionsWithJsonIfResolveJsonModule = ts.getSuppoertedExtensionsWithJsonIfResolveJsonModule(options, supportedExtensions);
99916         // Map storing if there is emit blocking diagnostics for given input
99917         var hasEmitBlockingDiagnostics = ts.createMap();
99918         var _compilerOptionsObjectLiteralSyntax;
99919         var moduleResolutionCache;
99920         var actualResolveModuleNamesWorker;
99921         var hasInvalidatedResolution = host.hasInvalidatedResolution || ts.returnFalse;
99922         if (host.resolveModuleNames) {
99923             actualResolveModuleNamesWorker = function (moduleNames, containingFile, reusedNames, redirectedReference) { return host.resolveModuleNames(ts.Debug.checkEachDefined(moduleNames), containingFile, reusedNames, redirectedReference, options).map(function (resolved) {
99924                 // An older host may have omitted extension, in which case we should infer it from the file extension of resolvedFileName.
99925                 if (!resolved || resolved.extension !== undefined) {
99926                     return resolved;
99927                 }
99928                 var withExtension = ts.clone(resolved);
99929                 withExtension.extension = ts.extensionFromPath(resolved.resolvedFileName);
99930                 return withExtension;
99931             }); };
99932         }
99933         else {
99934             moduleResolutionCache = ts.createModuleResolutionCache(currentDirectory, function (x) { return host.getCanonicalFileName(x); }, options);
99935             var loader_1 = function (moduleName, containingFile, redirectedReference) { return ts.resolveModuleName(moduleName, containingFile, options, host, moduleResolutionCache, redirectedReference).resolvedModule; }; // TODO: GH#18217
99936             actualResolveModuleNamesWorker = function (moduleNames, containingFile, _reusedNames, redirectedReference) { return loadWithLocalCache(ts.Debug.checkEachDefined(moduleNames), containingFile, redirectedReference, loader_1); };
99937         }
99938         var actualResolveTypeReferenceDirectiveNamesWorker;
99939         if (host.resolveTypeReferenceDirectives) {
99940             actualResolveTypeReferenceDirectiveNamesWorker = function (typeDirectiveNames, containingFile, redirectedReference) { return host.resolveTypeReferenceDirectives(ts.Debug.checkEachDefined(typeDirectiveNames), containingFile, redirectedReference, options); };
99941         }
99942         else {
99943             var loader_2 = function (typesRef, containingFile, redirectedReference) { return ts.resolveTypeReferenceDirective(typesRef, containingFile, options, host, redirectedReference).resolvedTypeReferenceDirective; }; // TODO: GH#18217
99944             actualResolveTypeReferenceDirectiveNamesWorker = function (typeReferenceDirectiveNames, containingFile, redirectedReference) { return loadWithLocalCache(ts.Debug.checkEachDefined(typeReferenceDirectiveNames), containingFile, redirectedReference, loader_2); };
99945         }
99946         // Map from a stringified PackageId to the source file with that id.
99947         // Only one source file may have a given packageId. Others become redirects (see createRedirectSourceFile).
99948         // `packageIdToSourceFile` is only used while building the program, while `sourceFileToPackageName` and `isSourceFileTargetOfRedirect` are kept around.
99949         var packageIdToSourceFile = ts.createMap();
99950         // Maps from a SourceFile's `.path` to the name of the package it was imported with.
99951         var sourceFileToPackageName = ts.createMap();
99952         // Key is a file name. Value is the (non-empty, or undefined) list of files that redirect to it.
99953         var redirectTargetsMap = ts.createMultiMap();
99954         /**
99955          * map with
99956          * - SourceFile if present
99957          * - false if sourceFile missing for source of project reference redirect
99958          * - undefined otherwise
99959          */
99960         var filesByName = ts.createMap();
99961         var missingFilePaths;
99962         // stores 'filename -> file association' ignoring case
99963         // used to track cases when two file names differ only in casing
99964         var filesByNameIgnoreCase = host.useCaseSensitiveFileNames() ? ts.createMap() : undefined;
99965         // A parallel array to projectReferences storing the results of reading in the referenced tsconfig files
99966         var resolvedProjectReferences;
99967         var projectReferenceRedirects;
99968         var mapFromFileToProjectReferenceRedirects;
99969         var mapFromToProjectReferenceRedirectSource;
99970         var useSourceOfProjectReferenceRedirect = !!((_a = host.useSourceOfProjectReferenceRedirect) === null || _a === void 0 ? void 0 : _a.call(host)) &&
99971             !options.disableSourceOfProjectReferenceRedirect;
99972         var _b = updateHostForUseSourceOfProjectReferenceRedirect({
99973             compilerHost: host,
99974             useSourceOfProjectReferenceRedirect: useSourceOfProjectReferenceRedirect,
99975             toPath: toPath,
99976             getResolvedProjectReferences: getResolvedProjectReferences,
99977             getSourceOfProjectReferenceRedirect: getSourceOfProjectReferenceRedirect,
99978             forEachResolvedProjectReference: forEachResolvedProjectReference
99979         }), onProgramCreateComplete = _b.onProgramCreateComplete, fileExists = _b.fileExists;
99980         var shouldCreateNewSourceFile = shouldProgramCreateNewSourceFiles(oldProgram, options);
99981         // We set `structuralIsReused` to `undefined` because `tryReuseStructureFromOldProgram` calls `tryReuseStructureFromOldProgram` which checks
99982         // `structuralIsReused`, which would be a TDZ violation if it was not set in advance to `undefined`.
99983         var structuralIsReused;
99984         structuralIsReused = tryReuseStructureFromOldProgram(); // eslint-disable-line prefer-const
99985         if (structuralIsReused !== 2 /* Completely */) {
99986             processingDefaultLibFiles = [];
99987             processingOtherFiles = [];
99988             if (projectReferences) {
99989                 if (!resolvedProjectReferences) {
99990                     resolvedProjectReferences = projectReferences.map(parseProjectReferenceConfigFile);
99991                 }
99992                 if (rootNames.length) {
99993                     for (var _i = 0, resolvedProjectReferences_1 = resolvedProjectReferences; _i < resolvedProjectReferences_1.length; _i++) {
99994                         var parsedRef = resolvedProjectReferences_1[_i];
99995                         if (!parsedRef)
99996                             continue;
99997                         var out = parsedRef.commandLine.options.outFile || parsedRef.commandLine.options.out;
99998                         if (useSourceOfProjectReferenceRedirect) {
99999                             if (out || ts.getEmitModuleKind(parsedRef.commandLine.options) === ts.ModuleKind.None) {
100000                                 for (var _c = 0, _d = parsedRef.commandLine.fileNames; _c < _d.length; _c++) {
100001                                     var fileName = _d[_c];
100002                                     processSourceFile(fileName, /*isDefaultLib*/ false, /*ignoreNoDefaultLib*/ false, /*packageId*/ undefined);
100003                                 }
100004                             }
100005                         }
100006                         else {
100007                             if (out) {
100008                                 processSourceFile(ts.changeExtension(out, ".d.ts"), /*isDefaultLib*/ false, /*ignoreNoDefaultLib*/ false, /*packageId*/ undefined);
100009                             }
100010                             else if (ts.getEmitModuleKind(parsedRef.commandLine.options) === ts.ModuleKind.None) {
100011                                 for (var _e = 0, _f = parsedRef.commandLine.fileNames; _e < _f.length; _e++) {
100012                                     var fileName = _f[_e];
100013                                     if (!ts.fileExtensionIs(fileName, ".d.ts" /* Dts */) && !ts.fileExtensionIs(fileName, ".json" /* Json */)) {
100014                                         processSourceFile(ts.getOutputDeclarationFileName(fileName, parsedRef.commandLine, !host.useCaseSensitiveFileNames()), /*isDefaultLib*/ false, /*ignoreNoDefaultLib*/ false, /*packageId*/ undefined);
100015                                     }
100016                                 }
100017                             }
100018                         }
100019                     }
100020                 }
100021             }
100022             ts.forEach(rootNames, function (name) { return processRootFile(name, /*isDefaultLib*/ false, /*ignoreNoDefaultLib*/ false); });
100023             // load type declarations specified via 'types' argument or implicitly from types/ and node_modules/@types folders
100024             var typeReferences = rootNames.length ? ts.getAutomaticTypeDirectiveNames(options, host) : ts.emptyArray;
100025             if (typeReferences.length) {
100026                 // This containingFilename needs to match with the one used in managed-side
100027                 var containingDirectory = options.configFilePath ? ts.getDirectoryPath(options.configFilePath) : host.getCurrentDirectory();
100028                 var containingFilename = ts.combinePaths(containingDirectory, ts.inferredTypesContainingFile);
100029                 var resolutions = resolveTypeReferenceDirectiveNamesWorker(typeReferences, containingFilename);
100030                 for (var i = 0; i < typeReferences.length; i++) {
100031                     processTypeReferenceDirective(typeReferences[i], resolutions[i]);
100032                 }
100033             }
100034             // Do not process the default library if:
100035             //  - The '--noLib' flag is used.
100036             //  - A 'no-default-lib' reference comment is encountered in
100037             //      processing the root files.
100038             if (rootNames.length && !skipDefaultLib) {
100039                 // If '--lib' is not specified, include default library file according to '--target'
100040                 // otherwise, using options specified in '--lib' instead of '--target' default library file
100041                 var defaultLibraryFileName = getDefaultLibraryFileName();
100042                 if (!options.lib && defaultLibraryFileName) {
100043                     processRootFile(defaultLibraryFileName, /*isDefaultLib*/ true, /*ignoreNoDefaultLib*/ false);
100044                 }
100045                 else {
100046                     ts.forEach(options.lib, function (libFileName) {
100047                         processRootFile(ts.combinePaths(defaultLibraryPath, libFileName), /*isDefaultLib*/ true, /*ignoreNoDefaultLib*/ false);
100048                     });
100049                 }
100050             }
100051             missingFilePaths = ts.arrayFrom(ts.mapDefinedIterator(filesByName.entries(), function (_a) {
100052                 var path = _a[0], file = _a[1];
100053                 return file === undefined ? path : undefined;
100054             }));
100055             files = ts.stableSort(processingDefaultLibFiles, compareDefaultLibFiles).concat(processingOtherFiles);
100056             processingDefaultLibFiles = undefined;
100057             processingOtherFiles = undefined;
100058         }
100059         ts.Debug.assert(!!missingFilePaths);
100060         // Release any files we have acquired in the old program but are
100061         // not part of the new program.
100062         if (oldProgram && host.onReleaseOldSourceFile) {
100063             var oldSourceFiles = oldProgram.getSourceFiles();
100064             for (var _g = 0, oldSourceFiles_1 = oldSourceFiles; _g < oldSourceFiles_1.length; _g++) {
100065                 var oldSourceFile = oldSourceFiles_1[_g];
100066                 var newFile = getSourceFileByPath(oldSourceFile.resolvedPath);
100067                 if (shouldCreateNewSourceFile || !newFile ||
100068                     // old file wasnt redirect but new file is
100069                     (oldSourceFile.resolvedPath === oldSourceFile.path && newFile.resolvedPath !== oldSourceFile.path)) {
100070                     host.onReleaseOldSourceFile(oldSourceFile, oldProgram.getCompilerOptions(), !!getSourceFileByPath(oldSourceFile.path));
100071                 }
100072             }
100073             oldProgram.forEachResolvedProjectReference(function (resolvedProjectReference, resolvedProjectReferencePath) {
100074                 if (resolvedProjectReference && !getResolvedProjectReferenceByPath(resolvedProjectReferencePath)) {
100075                     host.onReleaseOldSourceFile(resolvedProjectReference.sourceFile, oldProgram.getCompilerOptions(), /*hasSourceFileByPath*/ false);
100076                 }
100077             });
100078         }
100079         // unconditionally set oldProgram to undefined to prevent it from being captured in closure
100080         oldProgram = undefined;
100081         var program = {
100082             getRootFileNames: function () { return rootNames; },
100083             getSourceFile: getSourceFile,
100084             getSourceFileByPath: getSourceFileByPath,
100085             getSourceFiles: function () { return files; },
100086             getMissingFilePaths: function () { return missingFilePaths; },
100087             getRefFileMap: function () { return refFileMap; },
100088             getFilesByNameMap: function () { return filesByName; },
100089             getCompilerOptions: function () { return options; },
100090             getSyntacticDiagnostics: getSyntacticDiagnostics,
100091             getOptionsDiagnostics: getOptionsDiagnostics,
100092             getGlobalDiagnostics: getGlobalDiagnostics,
100093             getSemanticDiagnostics: getSemanticDiagnostics,
100094             getSuggestionDiagnostics: getSuggestionDiagnostics,
100095             getDeclarationDiagnostics: getDeclarationDiagnostics,
100096             getBindAndCheckDiagnostics: getBindAndCheckDiagnostics,
100097             getProgramDiagnostics: getProgramDiagnostics,
100098             getTypeChecker: getTypeChecker,
100099             getClassifiableNames: getClassifiableNames,
100100             getDiagnosticsProducingTypeChecker: getDiagnosticsProducingTypeChecker,
100101             getCommonSourceDirectory: getCommonSourceDirectory,
100102             emit: emit,
100103             getCurrentDirectory: function () { return currentDirectory; },
100104             getNodeCount: function () { return getDiagnosticsProducingTypeChecker().getNodeCount(); },
100105             getIdentifierCount: function () { return getDiagnosticsProducingTypeChecker().getIdentifierCount(); },
100106             getSymbolCount: function () { return getDiagnosticsProducingTypeChecker().getSymbolCount(); },
100107             getTypeCount: function () { return getDiagnosticsProducingTypeChecker().getTypeCount(); },
100108             getInstantiationCount: function () { return getDiagnosticsProducingTypeChecker().getInstantiationCount(); },
100109             getRelationCacheSizes: function () { return getDiagnosticsProducingTypeChecker().getRelationCacheSizes(); },
100110             getFileProcessingDiagnostics: function () { return fileProcessingDiagnostics; },
100111             getResolvedTypeReferenceDirectives: function () { return resolvedTypeReferenceDirectives; },
100112             isSourceFileFromExternalLibrary: isSourceFileFromExternalLibrary,
100113             isSourceFileDefaultLibrary: isSourceFileDefaultLibrary,
100114             dropDiagnosticsProducingTypeChecker: dropDiagnosticsProducingTypeChecker,
100115             getSourceFileFromReference: getSourceFileFromReference,
100116             getLibFileFromReference: getLibFileFromReference,
100117             sourceFileToPackageName: sourceFileToPackageName,
100118             redirectTargetsMap: redirectTargetsMap,
100119             isEmittedFile: isEmittedFile,
100120             getConfigFileParsingDiagnostics: getConfigFileParsingDiagnostics,
100121             getResolvedModuleWithFailedLookupLocationsFromCache: getResolvedModuleWithFailedLookupLocationsFromCache,
100122             getProjectReferences: getProjectReferences,
100123             getResolvedProjectReferences: getResolvedProjectReferences,
100124             getProjectReferenceRedirect: getProjectReferenceRedirect,
100125             getResolvedProjectReferenceToRedirect: getResolvedProjectReferenceToRedirect,
100126             getResolvedProjectReferenceByPath: getResolvedProjectReferenceByPath,
100127             forEachResolvedProjectReference: forEachResolvedProjectReference,
100128             isSourceOfProjectReferenceRedirect: isSourceOfProjectReferenceRedirect,
100129             emitBuildInfo: emitBuildInfo,
100130             fileExists: fileExists,
100131             getProbableSymlinks: getProbableSymlinks,
100132             useCaseSensitiveFileNames: function () { return host.useCaseSensitiveFileNames(); },
100133         };
100134         onProgramCreateComplete();
100135         verifyCompilerOptions();
100136         ts.performance.mark("afterProgram");
100137         ts.performance.measure("Program", "beforeProgram", "afterProgram");
100138         return program;
100139         function resolveModuleNamesWorker(moduleNames, containingFile, reusedNames, redirectedReference) {
100140             ts.performance.mark("beforeResolveModule");
100141             var result = actualResolveModuleNamesWorker(moduleNames, containingFile, reusedNames, redirectedReference);
100142             ts.performance.mark("afterResolveModule");
100143             ts.performance.measure("ResolveModule", "beforeResolveModule", "afterResolveModule");
100144             return result;
100145         }
100146         function resolveTypeReferenceDirectiveNamesWorker(typeDirectiveNames, containingFile, redirectedReference) {
100147             ts.performance.mark("beforeResolveTypeReference");
100148             var result = actualResolveTypeReferenceDirectiveNamesWorker(typeDirectiveNames, containingFile, redirectedReference);
100149             ts.performance.mark("afterResolveTypeReference");
100150             ts.performance.measure("ResolveTypeReference", "beforeResolveTypeReference", "afterResolveTypeReference");
100151             return result;
100152         }
100153         function compareDefaultLibFiles(a, b) {
100154             return ts.compareValues(getDefaultLibFilePriority(a), getDefaultLibFilePriority(b));
100155         }
100156         function getDefaultLibFilePriority(a) {
100157             if (ts.containsPath(defaultLibraryPath, a.fileName, /*ignoreCase*/ false)) {
100158                 var basename = ts.getBaseFileName(a.fileName);
100159                 if (basename === "lib.d.ts" || basename === "lib.es6.d.ts")
100160                     return 0;
100161                 var name = ts.removeSuffix(ts.removePrefix(basename, "lib."), ".d.ts");
100162                 var index = ts.libs.indexOf(name);
100163                 if (index !== -1)
100164                     return index + 1;
100165             }
100166             return ts.libs.length + 2;
100167         }
100168         function getResolvedModuleWithFailedLookupLocationsFromCache(moduleName, containingFile) {
100169             return moduleResolutionCache && ts.resolveModuleNameFromCache(moduleName, containingFile, moduleResolutionCache);
100170         }
100171         function toPath(fileName) {
100172             return ts.toPath(fileName, currentDirectory, getCanonicalFileName);
100173         }
100174         function getCommonSourceDirectory() {
100175             if (commonSourceDirectory === undefined) {
100176                 var emittedFiles = ts.filter(files, function (file) { return ts.sourceFileMayBeEmitted(file, program); });
100177                 if (options.rootDir && checkSourceFilesBelongToPath(emittedFiles, options.rootDir)) {
100178                     // If a rootDir is specified use it as the commonSourceDirectory
100179                     commonSourceDirectory = ts.getNormalizedAbsolutePath(options.rootDir, currentDirectory);
100180                 }
100181                 else if (options.composite && options.configFilePath) {
100182                     // Project compilations never infer their root from the input source paths
100183                     commonSourceDirectory = ts.getDirectoryPath(ts.normalizeSlashes(options.configFilePath));
100184                     checkSourceFilesBelongToPath(emittedFiles, commonSourceDirectory);
100185                 }
100186                 else {
100187                     commonSourceDirectory = computeCommonSourceDirectory(emittedFiles);
100188                 }
100189                 if (commonSourceDirectory && commonSourceDirectory[commonSourceDirectory.length - 1] !== ts.directorySeparator) {
100190                     // Make sure directory path ends with directory separator so this string can directly
100191                     // used to replace with "" to get the relative path of the source file and the relative path doesn't
100192                     // start with / making it rooted path
100193                     commonSourceDirectory += ts.directorySeparator;
100194                 }
100195             }
100196             return commonSourceDirectory;
100197         }
100198         function getClassifiableNames() {
100199             if (!classifiableNames) {
100200                 // Initialize a checker so that all our files are bound.
100201                 getTypeChecker();
100202                 classifiableNames = ts.createUnderscoreEscapedMap();
100203                 for (var _i = 0, files_2 = files; _i < files_2.length; _i++) {
100204                     var sourceFile = files_2[_i];
100205                     ts.copyEntries(sourceFile.classifiableNames, classifiableNames);
100206                 }
100207             }
100208             return classifiableNames;
100209         }
100210         function resolveModuleNamesReusingOldState(moduleNames, containingFile, file) {
100211             if (structuralIsReused === 0 /* Not */ && !file.ambientModuleNames.length) {
100212                 // If the old program state does not permit reusing resolutions and `file` does not contain locally defined ambient modules,
100213                 // the best we can do is fallback to the default logic.
100214                 return resolveModuleNamesWorker(moduleNames, containingFile, /*reusedNames*/ undefined, getResolvedProjectReferenceToRedirect(file.originalFileName));
100215             }
100216             var oldSourceFile = oldProgram && oldProgram.getSourceFile(containingFile);
100217             if (oldSourceFile !== file && file.resolvedModules) {
100218                 // `file` was created for the new program.
100219                 //
100220                 // We only set `file.resolvedModules` via work from the current function,
100221                 // so it is defined iff we already called the current function on `file`.
100222                 // That call happened no later than the creation of the `file` object,
100223                 // which per above occurred during the current program creation.
100224                 // Since we assume the filesystem does not change during program creation,
100225                 // it is safe to reuse resolutions from the earlier call.
100226                 var result_11 = [];
100227                 for (var _i = 0, moduleNames_1 = moduleNames; _i < moduleNames_1.length; _i++) {
100228                     var moduleName = moduleNames_1[_i];
100229                     var resolvedModule = file.resolvedModules.get(moduleName);
100230                     result_11.push(resolvedModule);
100231                 }
100232                 return result_11;
100233             }
100234             // At this point, we know at least one of the following hold:
100235             // - file has local declarations for ambient modules
100236             // - old program state is available
100237             // With this information, we can infer some module resolutions without performing resolution.
100238             /** An ordered list of module names for which we cannot recover the resolution. */
100239             var unknownModuleNames;
100240             /**
100241              * The indexing of elements in this list matches that of `moduleNames`.
100242              *
100243              * Before combining results, result[i] is in one of the following states:
100244              * * undefined: needs to be recomputed,
100245              * * predictedToResolveToAmbientModuleMarker: known to be an ambient module.
100246              * Needs to be reset to undefined before returning,
100247              * * ResolvedModuleFull instance: can be reused.
100248              */
100249             var result;
100250             var reusedNames;
100251             /** A transient placeholder used to mark predicted resolution in the result list. */
100252             var predictedToResolveToAmbientModuleMarker = {};
100253             for (var i = 0; i < moduleNames.length; i++) {
100254                 var moduleName = moduleNames[i];
100255                 // If the source file is unchanged and doesnt have invalidated resolution, reuse the module resolutions
100256                 if (file === oldSourceFile && !hasInvalidatedResolution(oldSourceFile.path)) {
100257                     var oldResolvedModule = oldSourceFile && oldSourceFile.resolvedModules.get(moduleName);
100258                     if (oldResolvedModule) {
100259                         if (ts.isTraceEnabled(options, host)) {
100260                             ts.trace(host, ts.Diagnostics.Reusing_resolution_of_module_0_to_file_1_from_old_program, moduleName, containingFile);
100261                         }
100262                         (result || (result = new Array(moduleNames.length)))[i] = oldResolvedModule;
100263                         (reusedNames || (reusedNames = [])).push(moduleName);
100264                         continue;
100265                     }
100266                 }
100267                 // We know moduleName resolves to an ambient module provided that moduleName:
100268                 // - is in the list of ambient modules locally declared in the current source file.
100269                 // - resolved to an ambient module in the old program whose declaration is in an unmodified file
100270                 //   (so the same module declaration will land in the new program)
100271                 var resolvesToAmbientModuleInNonModifiedFile = false;
100272                 if (ts.contains(file.ambientModuleNames, moduleName)) {
100273                     resolvesToAmbientModuleInNonModifiedFile = true;
100274                     if (ts.isTraceEnabled(options, host)) {
100275                         ts.trace(host, ts.Diagnostics.Module_0_was_resolved_as_locally_declared_ambient_module_in_file_1, moduleName, containingFile);
100276                     }
100277                 }
100278                 else {
100279                     resolvesToAmbientModuleInNonModifiedFile = moduleNameResolvesToAmbientModuleInNonModifiedFile(moduleName);
100280                 }
100281                 if (resolvesToAmbientModuleInNonModifiedFile) {
100282                     (result || (result = new Array(moduleNames.length)))[i] = predictedToResolveToAmbientModuleMarker;
100283                 }
100284                 else {
100285                     // Resolution failed in the old program, or resolved to an ambient module for which we can't reuse the result.
100286                     (unknownModuleNames || (unknownModuleNames = [])).push(moduleName);
100287                 }
100288             }
100289             var resolutions = unknownModuleNames && unknownModuleNames.length
100290                 ? resolveModuleNamesWorker(unknownModuleNames, containingFile, reusedNames, getResolvedProjectReferenceToRedirect(file.originalFileName))
100291                 : ts.emptyArray;
100292             // Combine results of resolutions and predicted results
100293             if (!result) {
100294                 // There were no unresolved/ambient resolutions.
100295                 ts.Debug.assert(resolutions.length === moduleNames.length);
100296                 return resolutions;
100297             }
100298             var j = 0;
100299             for (var i = 0; i < result.length; i++) {
100300                 if (result[i]) {
100301                     // `result[i]` is either a `ResolvedModuleFull` or a marker.
100302                     // If it is the former, we can leave it as is.
100303                     if (result[i] === predictedToResolveToAmbientModuleMarker) {
100304                         result[i] = undefined; // TODO: GH#18217
100305                     }
100306                 }
100307                 else {
100308                     result[i] = resolutions[j];
100309                     j++;
100310                 }
100311             }
100312             ts.Debug.assert(j === resolutions.length);
100313             return result;
100314             // If we change our policy of rechecking failed lookups on each program create,
100315             // we should adjust the value returned here.
100316             function moduleNameResolvesToAmbientModuleInNonModifiedFile(moduleName) {
100317                 var resolutionToFile = ts.getResolvedModule(oldSourceFile, moduleName);
100318                 var resolvedFile = resolutionToFile && oldProgram.getSourceFile(resolutionToFile.resolvedFileName);
100319                 if (resolutionToFile && resolvedFile) {
100320                     // In the old program, we resolved to an ambient module that was in the same
100321                     //   place as we expected to find an actual module file.
100322                     // We actually need to return 'false' here even though this seems like a 'true' case
100323                     //   because the normal module resolution algorithm will find this anyway.
100324                     return false;
100325                 }
100326                 // at least one of declarations should come from non-modified source file
100327                 var unmodifiedFile = ambientModuleNameToUnmodifiedFileName.get(moduleName);
100328                 if (!unmodifiedFile) {
100329                     return false;
100330                 }
100331                 if (ts.isTraceEnabled(options, host)) {
100332                     ts.trace(host, ts.Diagnostics.Module_0_was_resolved_as_ambient_module_declared_in_1_since_this_file_was_not_modified, moduleName, unmodifiedFile);
100333                 }
100334                 return true;
100335             }
100336         }
100337         function canReuseProjectReferences() {
100338             return !forEachProjectReference(oldProgram.getProjectReferences(), oldProgram.getResolvedProjectReferences(), function (oldResolvedRef, index, parent) {
100339                 var newRef = (parent ? parent.commandLine.projectReferences : projectReferences)[index];
100340                 var newResolvedRef = parseProjectReferenceConfigFile(newRef);
100341                 if (oldResolvedRef) {
100342                     // Resolved project reference has gone missing or changed
100343                     return !newResolvedRef || newResolvedRef.sourceFile !== oldResolvedRef.sourceFile;
100344                 }
100345                 else {
100346                     // A previously-unresolved reference may be resolved now
100347                     return newResolvedRef !== undefined;
100348                 }
100349             }, function (oldProjectReferences, parent) {
100350                 // If array of references is changed, we cant resue old program
100351                 var newReferences = parent ? getResolvedProjectReferenceByPath(parent.sourceFile.path).commandLine.projectReferences : projectReferences;
100352                 return !ts.arrayIsEqualTo(oldProjectReferences, newReferences, ts.projectReferenceIsEqualTo);
100353             });
100354         }
100355         function tryReuseStructureFromOldProgram() {
100356             if (!oldProgram) {
100357                 return 0 /* Not */;
100358             }
100359             // check properties that can affect structure of the program or module resolution strategy
100360             // if any of these properties has changed - structure cannot be reused
100361             var oldOptions = oldProgram.getCompilerOptions();
100362             if (ts.changesAffectModuleResolution(oldOptions, options)) {
100363                 return oldProgram.structureIsReused = 0 /* Not */;
100364             }
100365             ts.Debug.assert(!(oldProgram.structureIsReused & (2 /* Completely */ | 1 /* SafeModules */)));
100366             // there is an old program, check if we can reuse its structure
100367             var oldRootNames = oldProgram.getRootFileNames();
100368             if (!ts.arrayIsEqualTo(oldRootNames, rootNames)) {
100369                 return oldProgram.structureIsReused = 0 /* Not */;
100370             }
100371             if (!ts.arrayIsEqualTo(options.types, oldOptions.types)) {
100372                 return oldProgram.structureIsReused = 0 /* Not */;
100373             }
100374             // Check if any referenced project tsconfig files are different
100375             if (!canReuseProjectReferences()) {
100376                 return oldProgram.structureIsReused = 0 /* Not */;
100377             }
100378             if (projectReferences) {
100379                 resolvedProjectReferences = projectReferences.map(parseProjectReferenceConfigFile);
100380             }
100381             // check if program source files has changed in the way that can affect structure of the program
100382             var newSourceFiles = [];
100383             var modifiedSourceFiles = [];
100384             oldProgram.structureIsReused = 2 /* Completely */;
100385             // If the missing file paths are now present, it can change the progam structure,
100386             // and hence cant reuse the structure.
100387             // This is same as how we dont reuse the structure if one of the file from old program is now missing
100388             if (oldProgram.getMissingFilePaths().some(function (missingFilePath) { return host.fileExists(missingFilePath); })) {
100389                 return oldProgram.structureIsReused = 0 /* Not */;
100390             }
100391             var oldSourceFiles = oldProgram.getSourceFiles();
100392             var SeenPackageName;
100393             (function (SeenPackageName) {
100394                 SeenPackageName[SeenPackageName["Exists"] = 0] = "Exists";
100395                 SeenPackageName[SeenPackageName["Modified"] = 1] = "Modified";
100396             })(SeenPackageName || (SeenPackageName = {}));
100397             var seenPackageNames = ts.createMap();
100398             for (var _i = 0, oldSourceFiles_2 = oldSourceFiles; _i < oldSourceFiles_2.length; _i++) {
100399                 var oldSourceFile = oldSourceFiles_2[_i];
100400                 var newSourceFile = host.getSourceFileByPath
100401                     ? host.getSourceFileByPath(oldSourceFile.fileName, oldSourceFile.resolvedPath, options.target, /*onError*/ undefined, shouldCreateNewSourceFile)
100402                     : host.getSourceFile(oldSourceFile.fileName, options.target, /*onError*/ undefined, shouldCreateNewSourceFile); // TODO: GH#18217
100403                 if (!newSourceFile) {
100404                     return oldProgram.structureIsReused = 0 /* Not */;
100405                 }
100406                 ts.Debug.assert(!newSourceFile.redirectInfo, "Host should not return a redirect source file from `getSourceFile`");
100407                 var fileChanged = void 0;
100408                 if (oldSourceFile.redirectInfo) {
100409                     // We got `newSourceFile` by path, so it is actually for the unredirected file.
100410                     // This lets us know if the unredirected file has changed. If it has we should break the redirect.
100411                     if (newSourceFile !== oldSourceFile.redirectInfo.unredirected) {
100412                         // Underlying file has changed. Might not redirect anymore. Must rebuild program.
100413                         return oldProgram.structureIsReused = 0 /* Not */;
100414                     }
100415                     fileChanged = false;
100416                     newSourceFile = oldSourceFile; // Use the redirect.
100417                 }
100418                 else if (oldProgram.redirectTargetsMap.has(oldSourceFile.path)) {
100419                     // If a redirected-to source file changes, the redirect may be broken.
100420                     if (newSourceFile !== oldSourceFile) {
100421                         return oldProgram.structureIsReused = 0 /* Not */;
100422                     }
100423                     fileChanged = false;
100424                 }
100425                 else {
100426                     fileChanged = newSourceFile !== oldSourceFile;
100427                 }
100428                 // Since the project references havent changed, its right to set originalFileName and resolvedPath here
100429                 newSourceFile.path = oldSourceFile.path;
100430                 newSourceFile.originalFileName = oldSourceFile.originalFileName;
100431                 newSourceFile.resolvedPath = oldSourceFile.resolvedPath;
100432                 newSourceFile.fileName = oldSourceFile.fileName;
100433                 var packageName = oldProgram.sourceFileToPackageName.get(oldSourceFile.path);
100434                 if (packageName !== undefined) {
100435                     // If there are 2 different source files for the same package name and at least one of them changes,
100436                     // they might become redirects. So we must rebuild the program.
100437                     var prevKind = seenPackageNames.get(packageName);
100438                     var newKind = fileChanged ? 1 /* Modified */ : 0 /* Exists */;
100439                     if ((prevKind !== undefined && newKind === 1 /* Modified */) || prevKind === 1 /* Modified */) {
100440                         return oldProgram.structureIsReused = 0 /* Not */;
100441                     }
100442                     seenPackageNames.set(packageName, newKind);
100443                 }
100444                 if (fileChanged) {
100445                     // The `newSourceFile` object was created for the new program.
100446                     if (!ts.arrayIsEqualTo(oldSourceFile.libReferenceDirectives, newSourceFile.libReferenceDirectives, fileReferenceIsEqualTo)) {
100447                         // 'lib' references has changed. Matches behavior in changesAffectModuleResolution
100448                         return oldProgram.structureIsReused = 0 /* Not */;
100449                     }
100450                     if (oldSourceFile.hasNoDefaultLib !== newSourceFile.hasNoDefaultLib) {
100451                         // value of no-default-lib has changed
100452                         // this will affect if default library is injected into the list of files
100453                         oldProgram.structureIsReused = 1 /* SafeModules */;
100454                     }
100455                     // check tripleslash references
100456                     if (!ts.arrayIsEqualTo(oldSourceFile.referencedFiles, newSourceFile.referencedFiles, fileReferenceIsEqualTo)) {
100457                         // tripleslash references has changed
100458                         oldProgram.structureIsReused = 1 /* SafeModules */;
100459                     }
100460                     // check imports and module augmentations
100461                     collectExternalModuleReferences(newSourceFile);
100462                     if (!ts.arrayIsEqualTo(oldSourceFile.imports, newSourceFile.imports, moduleNameIsEqualTo)) {
100463                         // imports has changed
100464                         oldProgram.structureIsReused = 1 /* SafeModules */;
100465                     }
100466                     if (!ts.arrayIsEqualTo(oldSourceFile.moduleAugmentations, newSourceFile.moduleAugmentations, moduleNameIsEqualTo)) {
100467                         // moduleAugmentations has changed
100468                         oldProgram.structureIsReused = 1 /* SafeModules */;
100469                     }
100470                     if ((oldSourceFile.flags & 3145728 /* PermanentlySetIncrementalFlags */) !== (newSourceFile.flags & 3145728 /* PermanentlySetIncrementalFlags */)) {
100471                         // dynamicImport has changed
100472                         oldProgram.structureIsReused = 1 /* SafeModules */;
100473                     }
100474                     if (!ts.arrayIsEqualTo(oldSourceFile.typeReferenceDirectives, newSourceFile.typeReferenceDirectives, fileReferenceIsEqualTo)) {
100475                         // 'types' references has changed
100476                         oldProgram.structureIsReused = 1 /* SafeModules */;
100477                     }
100478                     // tentatively approve the file
100479                     modifiedSourceFiles.push({ oldFile: oldSourceFile, newFile: newSourceFile });
100480                 }
100481                 else if (hasInvalidatedResolution(oldSourceFile.path)) {
100482                     // 'module/types' references could have changed
100483                     oldProgram.structureIsReused = 1 /* SafeModules */;
100484                     // add file to the modified list so that we will resolve it later
100485                     modifiedSourceFiles.push({ oldFile: oldSourceFile, newFile: newSourceFile });
100486                 }
100487                 // if file has passed all checks it should be safe to reuse it
100488                 newSourceFiles.push(newSourceFile);
100489             }
100490             if (oldProgram.structureIsReused !== 2 /* Completely */) {
100491                 return oldProgram.structureIsReused;
100492             }
100493             var modifiedFiles = modifiedSourceFiles.map(function (f) { return f.oldFile; });
100494             for (var _a = 0, oldSourceFiles_3 = oldSourceFiles; _a < oldSourceFiles_3.length; _a++) {
100495                 var oldFile = oldSourceFiles_3[_a];
100496                 if (!ts.contains(modifiedFiles, oldFile)) {
100497                     for (var _b = 0, _c = oldFile.ambientModuleNames; _b < _c.length; _b++) {
100498                         var moduleName = _c[_b];
100499                         ambientModuleNameToUnmodifiedFileName.set(moduleName, oldFile.fileName);
100500                     }
100501                 }
100502             }
100503             // try to verify results of module resolution
100504             for (var _d = 0, modifiedSourceFiles_1 = modifiedSourceFiles; _d < modifiedSourceFiles_1.length; _d++) {
100505                 var _e = modifiedSourceFiles_1[_d], oldSourceFile = _e.oldFile, newSourceFile = _e.newFile;
100506                 var newSourceFilePath = ts.getNormalizedAbsolutePath(newSourceFile.originalFileName, currentDirectory);
100507                 var moduleNames = getModuleNames(newSourceFile);
100508                 var resolutions = resolveModuleNamesReusingOldState(moduleNames, newSourceFilePath, newSourceFile);
100509                 // ensure that module resolution results are still correct
100510                 var resolutionsChanged = ts.hasChangesInResolutions(moduleNames, resolutions, oldSourceFile.resolvedModules, ts.moduleResolutionIsEqualTo);
100511                 if (resolutionsChanged) {
100512                     oldProgram.structureIsReused = 1 /* SafeModules */;
100513                     newSourceFile.resolvedModules = ts.zipToMap(moduleNames, resolutions);
100514                 }
100515                 else {
100516                     newSourceFile.resolvedModules = oldSourceFile.resolvedModules;
100517                 }
100518                 if (resolveTypeReferenceDirectiveNamesWorker) {
100519                     // We lower-case all type references because npm automatically lowercases all packages. See GH#9824.
100520                     var typesReferenceDirectives = ts.map(newSourceFile.typeReferenceDirectives, function (ref) { return ts.toFileNameLowerCase(ref.fileName); });
100521                     var resolutions_1 = resolveTypeReferenceDirectiveNamesWorker(typesReferenceDirectives, newSourceFilePath, getResolvedProjectReferenceToRedirect(newSourceFile.originalFileName));
100522                     // ensure that types resolutions are still correct
100523                     var resolutionsChanged_1 = ts.hasChangesInResolutions(typesReferenceDirectives, resolutions_1, oldSourceFile.resolvedTypeReferenceDirectiveNames, ts.typeDirectiveIsEqualTo);
100524                     if (resolutionsChanged_1) {
100525                         oldProgram.structureIsReused = 1 /* SafeModules */;
100526                         newSourceFile.resolvedTypeReferenceDirectiveNames = ts.zipToMap(typesReferenceDirectives, resolutions_1);
100527                     }
100528                     else {
100529                         newSourceFile.resolvedTypeReferenceDirectiveNames = oldSourceFile.resolvedTypeReferenceDirectiveNames;
100530                     }
100531                 }
100532             }
100533             if (oldProgram.structureIsReused !== 2 /* Completely */) {
100534                 return oldProgram.structureIsReused;
100535             }
100536             if (host.hasChangedAutomaticTypeDirectiveNames) {
100537                 return oldProgram.structureIsReused = 1 /* SafeModules */;
100538             }
100539             missingFilePaths = oldProgram.getMissingFilePaths();
100540             refFileMap = oldProgram.getRefFileMap();
100541             // update fileName -> file mapping
100542             ts.Debug.assert(newSourceFiles.length === oldProgram.getSourceFiles().length);
100543             for (var _f = 0, newSourceFiles_1 = newSourceFiles; _f < newSourceFiles_1.length; _f++) {
100544                 var newSourceFile = newSourceFiles_1[_f];
100545                 filesByName.set(newSourceFile.path, newSourceFile);
100546             }
100547             var oldFilesByNameMap = oldProgram.getFilesByNameMap();
100548             oldFilesByNameMap.forEach(function (oldFile, path) {
100549                 if (!oldFile) {
100550                     filesByName.set(path, oldFile);
100551                     return;
100552                 }
100553                 if (oldFile.path === path) {
100554                     // Set the file as found during node modules search if it was found that way in old progra,
100555                     if (oldProgram.isSourceFileFromExternalLibrary(oldFile)) {
100556                         sourceFilesFoundSearchingNodeModules.set(oldFile.path, true);
100557                     }
100558                     return;
100559                 }
100560                 filesByName.set(path, filesByName.get(oldFile.path));
100561             });
100562             files = newSourceFiles;
100563             fileProcessingDiagnostics = oldProgram.getFileProcessingDiagnostics();
100564             for (var _g = 0, modifiedSourceFiles_2 = modifiedSourceFiles; _g < modifiedSourceFiles_2.length; _g++) {
100565                 var modifiedFile = modifiedSourceFiles_2[_g];
100566                 fileProcessingDiagnostics.reattachFileDiagnostics(modifiedFile.newFile);
100567             }
100568             resolvedTypeReferenceDirectives = oldProgram.getResolvedTypeReferenceDirectives();
100569             sourceFileToPackageName = oldProgram.sourceFileToPackageName;
100570             redirectTargetsMap = oldProgram.redirectTargetsMap;
100571             return oldProgram.structureIsReused = 2 /* Completely */;
100572         }
100573         function getEmitHost(writeFileCallback) {
100574             return {
100575                 getPrependNodes: getPrependNodes,
100576                 getCanonicalFileName: getCanonicalFileName,
100577                 getCommonSourceDirectory: program.getCommonSourceDirectory,
100578                 getCompilerOptions: program.getCompilerOptions,
100579                 getCurrentDirectory: function () { return currentDirectory; },
100580                 getNewLine: function () { return host.getNewLine(); },
100581                 getSourceFile: program.getSourceFile,
100582                 getSourceFileByPath: program.getSourceFileByPath,
100583                 getSourceFiles: program.getSourceFiles,
100584                 getLibFileFromReference: program.getLibFileFromReference,
100585                 isSourceFileFromExternalLibrary: isSourceFileFromExternalLibrary,
100586                 getResolvedProjectReferenceToRedirect: getResolvedProjectReferenceToRedirect,
100587                 getProjectReferenceRedirect: getProjectReferenceRedirect,
100588                 isSourceOfProjectReferenceRedirect: isSourceOfProjectReferenceRedirect,
100589                 getProbableSymlinks: getProbableSymlinks,
100590                 writeFile: writeFileCallback || (function (fileName, data, writeByteOrderMark, onError, sourceFiles) { return host.writeFile(fileName, data, writeByteOrderMark, onError, sourceFiles); }),
100591                 isEmitBlocked: isEmitBlocked,
100592                 readFile: function (f) { return host.readFile(f); },
100593                 fileExists: function (f) {
100594                     // Use local caches
100595                     var path = toPath(f);
100596                     if (getSourceFileByPath(path))
100597                         return true;
100598                     if (ts.contains(missingFilePaths, path))
100599                         return false;
100600                     // Before falling back to the host
100601                     return host.fileExists(f);
100602                 },
100603                 useCaseSensitiveFileNames: function () { return host.useCaseSensitiveFileNames(); },
100604                 getProgramBuildInfo: function () { return program.getProgramBuildInfo && program.getProgramBuildInfo(); },
100605                 getSourceFileFromReference: function (file, ref) { return program.getSourceFileFromReference(file, ref); },
100606                 redirectTargetsMap: redirectTargetsMap,
100607             };
100608         }
100609         function emitBuildInfo(writeFileCallback) {
100610             ts.Debug.assert(!options.out && !options.outFile);
100611             ts.performance.mark("beforeEmit");
100612             var emitResult = ts.emitFiles(ts.notImplementedResolver, getEmitHost(writeFileCallback), 
100613             /*targetSourceFile*/ undefined, 
100614             /*transformers*/ ts.noTransformers, 
100615             /*emitOnlyDtsFiles*/ false, 
100616             /*onlyBuildInfo*/ true);
100617             ts.performance.mark("afterEmit");
100618             ts.performance.measure("Emit", "beforeEmit", "afterEmit");
100619             return emitResult;
100620         }
100621         function getResolvedProjectReferences() {
100622             return resolvedProjectReferences;
100623         }
100624         function getProjectReferences() {
100625             return projectReferences;
100626         }
100627         function getPrependNodes() {
100628             return createPrependNodes(projectReferences, function (_ref, index) { return resolvedProjectReferences[index].commandLine; }, function (fileName) {
100629                 var path = toPath(fileName);
100630                 var sourceFile = getSourceFileByPath(path);
100631                 return sourceFile ? sourceFile.text : filesByName.has(path) ? undefined : host.readFile(path);
100632             });
100633         }
100634         function isSourceFileFromExternalLibrary(file) {
100635             return !!sourceFilesFoundSearchingNodeModules.get(file.path);
100636         }
100637         function isSourceFileDefaultLibrary(file) {
100638             if (file.hasNoDefaultLib) {
100639                 return true;
100640             }
100641             if (!options.noLib) {
100642                 return false;
100643             }
100644             // If '--lib' is not specified, include default library file according to '--target'
100645             // otherwise, using options specified in '--lib' instead of '--target' default library file
100646             var equalityComparer = host.useCaseSensitiveFileNames() ? ts.equateStringsCaseSensitive : ts.equateStringsCaseInsensitive;
100647             if (!options.lib) {
100648                 return equalityComparer(file.fileName, getDefaultLibraryFileName());
100649             }
100650             else {
100651                 return ts.some(options.lib, function (libFileName) { return equalityComparer(file.fileName, ts.combinePaths(defaultLibraryPath, libFileName)); });
100652             }
100653         }
100654         function getDiagnosticsProducingTypeChecker() {
100655             return diagnosticsProducingTypeChecker || (diagnosticsProducingTypeChecker = ts.createTypeChecker(program, /*produceDiagnostics:*/ true));
100656         }
100657         function dropDiagnosticsProducingTypeChecker() {
100658             diagnosticsProducingTypeChecker = undefined;
100659         }
100660         function getTypeChecker() {
100661             return noDiagnosticsTypeChecker || (noDiagnosticsTypeChecker = ts.createTypeChecker(program, /*produceDiagnostics:*/ false));
100662         }
100663         function emit(sourceFile, writeFileCallback, cancellationToken, emitOnlyDtsFiles, transformers, forceDtsEmit) {
100664             return runWithCancellationToken(function () { return emitWorker(program, sourceFile, writeFileCallback, cancellationToken, emitOnlyDtsFiles, transformers, forceDtsEmit); });
100665         }
100666         function isEmitBlocked(emitFileName) {
100667             return hasEmitBlockingDiagnostics.has(toPath(emitFileName));
100668         }
100669         function emitWorker(program, sourceFile, writeFileCallback, cancellationToken, emitOnlyDtsFiles, customTransformers, forceDtsEmit) {
100670             if (!forceDtsEmit) {
100671                 var result = handleNoEmitOptions(program, sourceFile, cancellationToken);
100672                 if (result)
100673                     return result;
100674             }
100675             // Create the emit resolver outside of the "emitTime" tracking code below.  That way
100676             // any cost associated with it (like type checking) are appropriate associated with
100677             // the type-checking counter.
100678             //
100679             // If the -out option is specified, we should not pass the source file to getEmitResolver.
100680             // This is because in the -out scenario all files need to be emitted, and therefore all
100681             // files need to be type checked. And the way to specify that all files need to be type
100682             // checked is to not pass the file to getEmitResolver.
100683             var emitResolver = getDiagnosticsProducingTypeChecker().getEmitResolver((options.outFile || options.out) ? undefined : sourceFile, cancellationToken);
100684             ts.performance.mark("beforeEmit");
100685             var emitResult = ts.emitFiles(emitResolver, getEmitHost(writeFileCallback), sourceFile, ts.getTransformers(options, customTransformers, emitOnlyDtsFiles), emitOnlyDtsFiles, 
100686             /*onlyBuildInfo*/ false, forceDtsEmit);
100687             ts.performance.mark("afterEmit");
100688             ts.performance.measure("Emit", "beforeEmit", "afterEmit");
100689             return emitResult;
100690         }
100691         function getSourceFile(fileName) {
100692             return getSourceFileByPath(toPath(fileName));
100693         }
100694         function getSourceFileByPath(path) {
100695             return filesByName.get(path) || undefined;
100696         }
100697         function getDiagnosticsHelper(sourceFile, getDiagnostics, cancellationToken) {
100698             if (sourceFile) {
100699                 return getDiagnostics(sourceFile, cancellationToken);
100700             }
100701             return ts.sortAndDeduplicateDiagnostics(ts.flatMap(program.getSourceFiles(), function (sourceFile) {
100702                 if (cancellationToken) {
100703                     cancellationToken.throwIfCancellationRequested();
100704                 }
100705                 return getDiagnostics(sourceFile, cancellationToken);
100706             }));
100707         }
100708         function getSyntacticDiagnostics(sourceFile, cancellationToken) {
100709             return getDiagnosticsHelper(sourceFile, getSyntacticDiagnosticsForFile, cancellationToken);
100710         }
100711         function getSemanticDiagnostics(sourceFile, cancellationToken) {
100712             return getDiagnosticsHelper(sourceFile, getSemanticDiagnosticsForFile, cancellationToken);
100713         }
100714         function getBindAndCheckDiagnostics(sourceFile, cancellationToken) {
100715             return getBindAndCheckDiagnosticsForFile(sourceFile, cancellationToken);
100716         }
100717         function getProgramDiagnostics(sourceFile) {
100718             if (ts.skipTypeChecking(sourceFile, options, program)) {
100719                 return ts.emptyArray;
100720             }
100721             var fileProcessingDiagnosticsInFile = fileProcessingDiagnostics.getDiagnostics(sourceFile.fileName);
100722             var programDiagnosticsInFile = programDiagnostics.getDiagnostics(sourceFile.fileName);
100723             return getMergedProgramDiagnostics(sourceFile, fileProcessingDiagnosticsInFile, programDiagnosticsInFile);
100724         }
100725         function getMergedProgramDiagnostics(sourceFile) {
100726             var _a;
100727             var allDiagnostics = [];
100728             for (var _i = 1; _i < arguments.length; _i++) {
100729                 allDiagnostics[_i - 1] = arguments[_i];
100730             }
100731             var flatDiagnostics = ts.flatten(allDiagnostics);
100732             if (!((_a = sourceFile.commentDirectives) === null || _a === void 0 ? void 0 : _a.length)) {
100733                 return flatDiagnostics;
100734             }
100735             return getDiagnosticsWithPrecedingDirectives(sourceFile, sourceFile.commentDirectives, flatDiagnostics).diagnostics;
100736         }
100737         function getDeclarationDiagnostics(sourceFile, cancellationToken) {
100738             var options = program.getCompilerOptions();
100739             // collect diagnostics from the program only once if either no source file was specified or out/outFile is set (bundled emit)
100740             if (!sourceFile || options.out || options.outFile) {
100741                 return getDeclarationDiagnosticsWorker(sourceFile, cancellationToken);
100742             }
100743             else {
100744                 return getDiagnosticsHelper(sourceFile, getDeclarationDiagnosticsForFile, cancellationToken);
100745             }
100746         }
100747         function getSyntacticDiagnosticsForFile(sourceFile) {
100748             // For JavaScript files, we report semantic errors for using TypeScript-only
100749             // constructs from within a JavaScript file as syntactic errors.
100750             if (ts.isSourceFileJS(sourceFile)) {
100751                 if (!sourceFile.additionalSyntacticDiagnostics) {
100752                     sourceFile.additionalSyntacticDiagnostics = getJSSyntacticDiagnosticsForFile(sourceFile);
100753                 }
100754                 return ts.concatenate(sourceFile.additionalSyntacticDiagnostics, sourceFile.parseDiagnostics);
100755             }
100756             return sourceFile.parseDiagnostics;
100757         }
100758         function runWithCancellationToken(func) {
100759             try {
100760                 return func();
100761             }
100762             catch (e) {
100763                 if (e instanceof ts.OperationCanceledException) {
100764                     // We were canceled while performing the operation.  Because our type checker
100765                     // might be a bad state, we need to throw it away.
100766                     //
100767                     // Note: we are overly aggressive here.  We do not actually *have* to throw away
100768                     // the "noDiagnosticsTypeChecker".  However, for simplicity, i'd like to keep
100769                     // the lifetimes of these two TypeCheckers the same.  Also, we generally only
100770                     // cancel when the user has made a change anyways.  And, in that case, we (the
100771                     // program instance) will get thrown away anyways.  So trying to keep one of
100772                     // these type checkers alive doesn't serve much purpose.
100773                     noDiagnosticsTypeChecker = undefined;
100774                     diagnosticsProducingTypeChecker = undefined;
100775                 }
100776                 throw e;
100777             }
100778         }
100779         function getSemanticDiagnosticsForFile(sourceFile, cancellationToken) {
100780             return ts.concatenate(getBindAndCheckDiagnosticsForFile(sourceFile, cancellationToken), getProgramDiagnostics(sourceFile));
100781         }
100782         function getBindAndCheckDiagnosticsForFile(sourceFile, cancellationToken) {
100783             return getAndCacheDiagnostics(sourceFile, cancellationToken, cachedBindAndCheckDiagnosticsForFile, getBindAndCheckDiagnosticsForFileNoCache);
100784         }
100785         function getBindAndCheckDiagnosticsForFileNoCache(sourceFile, cancellationToken) {
100786             return runWithCancellationToken(function () {
100787                 if (ts.skipTypeChecking(sourceFile, options, program)) {
100788                     return ts.emptyArray;
100789                 }
100790                 var typeChecker = getDiagnosticsProducingTypeChecker();
100791                 ts.Debug.assert(!!sourceFile.bindDiagnostics);
100792                 var isCheckJs = ts.isCheckJsEnabledForFile(sourceFile, options);
100793                 var isTsNoCheck = !!sourceFile.checkJsDirective && sourceFile.checkJsDirective.enabled === false;
100794                 // By default, only type-check .ts, .tsx, 'Deferred' and 'External' files (external files are added by plugins)
100795                 var includeBindAndCheckDiagnostics = !isTsNoCheck && (sourceFile.scriptKind === 3 /* TS */ || sourceFile.scriptKind === 4 /* TSX */ ||
100796                     sourceFile.scriptKind === 5 /* External */ || isCheckJs || sourceFile.scriptKind === 7 /* Deferred */);
100797                 var bindDiagnostics = includeBindAndCheckDiagnostics ? sourceFile.bindDiagnostics : ts.emptyArray;
100798                 var checkDiagnostics = includeBindAndCheckDiagnostics ? typeChecker.getDiagnostics(sourceFile, cancellationToken) : ts.emptyArray;
100799                 return getMergedBindAndCheckDiagnostics(sourceFile, bindDiagnostics, checkDiagnostics, isCheckJs ? sourceFile.jsDocDiagnostics : undefined);
100800             });
100801         }
100802         function getMergedBindAndCheckDiagnostics(sourceFile) {
100803             var _a;
100804             var allDiagnostics = [];
100805             for (var _i = 1; _i < arguments.length; _i++) {
100806                 allDiagnostics[_i - 1] = arguments[_i];
100807             }
100808             var flatDiagnostics = ts.flatten(allDiagnostics);
100809             if (!((_a = sourceFile.commentDirectives) === null || _a === void 0 ? void 0 : _a.length)) {
100810                 return flatDiagnostics;
100811             }
100812             var _b = getDiagnosticsWithPrecedingDirectives(sourceFile, sourceFile.commentDirectives, flatDiagnostics), diagnostics = _b.diagnostics, directives = _b.directives;
100813             for (var _c = 0, _d = directives.getUnusedExpectations(); _c < _d.length; _c++) {
100814                 var errorExpectation = _d[_c];
100815                 diagnostics.push(ts.createDiagnosticForRange(sourceFile, errorExpectation.range, ts.Diagnostics.Unused_ts_expect_error_directive));
100816             }
100817             return diagnostics;
100818         }
100819         /**
100820          * Creates a map of comment directives along with the diagnostics immediately preceded by one of them.
100821          * Comments that match to any of those diagnostics are marked as used.
100822          */
100823         function getDiagnosticsWithPrecedingDirectives(sourceFile, commentDirectives, flatDiagnostics) {
100824             // Diagnostics are only reported if there is no comment directive preceding them
100825             // This will modify the directives map by marking "used" ones with a corresponding diagnostic
100826             var directives = ts.createCommentDirectivesMap(sourceFile, commentDirectives);
100827             var diagnostics = flatDiagnostics.filter(function (diagnostic) { return markPrecedingCommentDirectiveLine(diagnostic, directives) === -1; });
100828             return { diagnostics: diagnostics, directives: directives };
100829         }
100830         function getSuggestionDiagnostics(sourceFile, cancellationToken) {
100831             return runWithCancellationToken(function () {
100832                 return getDiagnosticsProducingTypeChecker().getSuggestionDiagnostics(sourceFile, cancellationToken);
100833             });
100834         }
100835         /**
100836          * @returns The line index marked as preceding the diagnostic, or -1 if none was.
100837          */
100838         function markPrecedingCommentDirectiveLine(diagnostic, directives) {
100839             var file = diagnostic.file, start = diagnostic.start;
100840             if (!file) {
100841                 return -1;
100842             }
100843             // Start out with the line just before the text
100844             var lineStarts = ts.getLineStarts(file);
100845             var line = ts.computeLineAndCharacterOfPosition(lineStarts, start).line - 1; // TODO: GH#18217
100846             while (line >= 0) {
100847                 // As soon as that line is known to have a comment directive, use that
100848                 if (directives.markUsed(line)) {
100849                     return line;
100850                 }
100851                 // Stop searching if the line is not empty and not a comment
100852                 var lineText = file.text.slice(lineStarts[line], lineStarts[line + 1]).trim();
100853                 if (lineText !== "" && !/^(\s*)\/\/(.*)$/.test(lineText)) {
100854                     return -1;
100855                 }
100856                 line--;
100857             }
100858             return -1;
100859         }
100860         function getJSSyntacticDiagnosticsForFile(sourceFile) {
100861             return runWithCancellationToken(function () {
100862                 var diagnostics = [];
100863                 walk(sourceFile, sourceFile);
100864                 ts.forEachChildRecursively(sourceFile, walk, walkArray);
100865                 return diagnostics;
100866                 function walk(node, parent) {
100867                     // Return directly from the case if the given node doesnt want to visit each child
100868                     // Otherwise break to visit each child
100869                     switch (parent.kind) {
100870                         case 156 /* Parameter */:
100871                         case 159 /* PropertyDeclaration */:
100872                         case 161 /* MethodDeclaration */:
100873                             if (parent.questionToken === node) {
100874                                 diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.The_0_modifier_can_only_be_used_in_TypeScript_files, "?"));
100875                                 return "skip";
100876                             }
100877                         // falls through
100878                         case 160 /* MethodSignature */:
100879                         case 162 /* Constructor */:
100880                         case 163 /* GetAccessor */:
100881                         case 164 /* SetAccessor */:
100882                         case 201 /* FunctionExpression */:
100883                         case 244 /* FunctionDeclaration */:
100884                         case 202 /* ArrowFunction */:
100885                         case 242 /* VariableDeclaration */:
100886                             // type annotation
100887                             if (parent.type === node) {
100888                                 diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.Type_annotations_can_only_be_used_in_TypeScript_files));
100889                                 return "skip";
100890                             }
100891                     }
100892                     switch (node.kind) {
100893                         case 255 /* ImportClause */:
100894                             if (node.isTypeOnly) {
100895                                 diagnostics.push(createDiagnosticForNode(node.parent, ts.Diagnostics._0_declarations_can_only_be_used_in_TypeScript_files, "import type"));
100896                                 return "skip";
100897                             }
100898                             break;
100899                         case 260 /* ExportDeclaration */:
100900                             if (node.isTypeOnly) {
100901                                 diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics._0_declarations_can_only_be_used_in_TypeScript_files, "export type"));
100902                                 return "skip";
100903                             }
100904                             break;
100905                         case 253 /* ImportEqualsDeclaration */:
100906                             diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.import_can_only_be_used_in_TypeScript_files));
100907                             return "skip";
100908                         case 259 /* ExportAssignment */:
100909                             if (node.isExportEquals) {
100910                                 diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.export_can_only_be_used_in_TypeScript_files));
100911                                 return "skip";
100912                             }
100913                             break;
100914                         case 279 /* HeritageClause */:
100915                             var heritageClause = node;
100916                             if (heritageClause.token === 113 /* ImplementsKeyword */) {
100917                                 diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.implements_clauses_can_only_be_used_in_TypeScript_files));
100918                                 return "skip";
100919                             }
100920                             break;
100921                         case 246 /* InterfaceDeclaration */:
100922                             var interfaceKeyword = ts.tokenToString(114 /* InterfaceKeyword */);
100923                             ts.Debug.assertIsDefined(interfaceKeyword);
100924                             diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics._0_declarations_can_only_be_used_in_TypeScript_files, interfaceKeyword));
100925                             return "skip";
100926                         case 249 /* ModuleDeclaration */:
100927                             var moduleKeyword = node.flags & 16 /* Namespace */ ? ts.tokenToString(136 /* NamespaceKeyword */) : ts.tokenToString(135 /* ModuleKeyword */);
100928                             ts.Debug.assertIsDefined(moduleKeyword);
100929                             diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics._0_declarations_can_only_be_used_in_TypeScript_files, moduleKeyword));
100930                             return "skip";
100931                         case 247 /* TypeAliasDeclaration */:
100932                             diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.Type_aliases_can_only_be_used_in_TypeScript_files));
100933                             return "skip";
100934                         case 248 /* EnumDeclaration */:
100935                             var enumKeyword = ts.Debug.checkDefined(ts.tokenToString(88 /* EnumKeyword */));
100936                             diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics._0_declarations_can_only_be_used_in_TypeScript_files, enumKeyword));
100937                             return "skip";
100938                         case 218 /* NonNullExpression */:
100939                             diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.Non_null_assertions_can_only_be_used_in_TypeScript_files));
100940                             return "skip";
100941                         case 217 /* AsExpression */:
100942                             diagnostics.push(createDiagnosticForNode(node.type, ts.Diagnostics.Type_assertion_expressions_can_only_be_used_in_TypeScript_files));
100943                             return "skip";
100944                         case 199 /* TypeAssertionExpression */:
100945                             ts.Debug.fail(); // Won't parse these in a JS file anyway, as they are interpreted as JSX.
100946                     }
100947                 }
100948                 function walkArray(nodes, parent) {
100949                     if (parent.decorators === nodes && !options.experimentalDecorators) {
100950                         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));
100951                     }
100952                     switch (parent.kind) {
100953                         case 245 /* ClassDeclaration */:
100954                         case 214 /* ClassExpression */:
100955                         case 161 /* MethodDeclaration */:
100956                         case 162 /* Constructor */:
100957                         case 163 /* GetAccessor */:
100958                         case 164 /* SetAccessor */:
100959                         case 201 /* FunctionExpression */:
100960                         case 244 /* FunctionDeclaration */:
100961                         case 202 /* ArrowFunction */:
100962                             // Check type parameters
100963                             if (nodes === parent.typeParameters) {
100964                                 diagnostics.push(createDiagnosticForNodeArray(nodes, ts.Diagnostics.Type_parameter_declarations_can_only_be_used_in_TypeScript_files));
100965                                 return "skip";
100966                             }
100967                         // falls through
100968                         case 225 /* VariableStatement */:
100969                             // Check modifiers
100970                             if (nodes === parent.modifiers) {
100971                                 checkModifiers(parent.modifiers, parent.kind === 225 /* VariableStatement */);
100972                                 return "skip";
100973                             }
100974                             break;
100975                         case 159 /* PropertyDeclaration */:
100976                             // Check modifiers of property declaration
100977                             if (nodes === parent.modifiers) {
100978                                 for (var _i = 0, _a = nodes; _i < _a.length; _i++) {
100979                                     var modifier = _a[_i];
100980                                     if (modifier.kind !== 120 /* StaticKeyword */) {
100981                                         diagnostics.push(createDiagnosticForNode(modifier, ts.Diagnostics.The_0_modifier_can_only_be_used_in_TypeScript_files, ts.tokenToString(modifier.kind)));
100982                                     }
100983                                 }
100984                                 return "skip";
100985                             }
100986                             break;
100987                         case 156 /* Parameter */:
100988                             // Check modifiers of parameter declaration
100989                             if (nodes === parent.modifiers) {
100990                                 diagnostics.push(createDiagnosticForNodeArray(nodes, ts.Diagnostics.Parameter_modifiers_can_only_be_used_in_TypeScript_files));
100991                                 return "skip";
100992                             }
100993                             break;
100994                         case 196 /* CallExpression */:
100995                         case 197 /* NewExpression */:
100996                         case 216 /* ExpressionWithTypeArguments */:
100997                         case 267 /* JsxSelfClosingElement */:
100998                         case 268 /* JsxOpeningElement */:
100999                         case 198 /* TaggedTemplateExpression */:
101000                             // Check type arguments
101001                             if (nodes === parent.typeArguments) {
101002                                 diagnostics.push(createDiagnosticForNodeArray(nodes, ts.Diagnostics.Type_arguments_can_only_be_used_in_TypeScript_files));
101003                                 return "skip";
101004                             }
101005                             break;
101006                     }
101007                 }
101008                 function checkModifiers(modifiers, isConstValid) {
101009                     for (var _i = 0, modifiers_1 = modifiers; _i < modifiers_1.length; _i++) {
101010                         var modifier = modifiers_1[_i];
101011                         switch (modifier.kind) {
101012                             case 81 /* ConstKeyword */:
101013                                 if (isConstValid) {
101014                                     continue;
101015                                 }
101016                             // to report error,
101017                             // falls through
101018                             case 119 /* PublicKeyword */:
101019                             case 117 /* PrivateKeyword */:
101020                             case 118 /* ProtectedKeyword */:
101021                             case 138 /* ReadonlyKeyword */:
101022                             case 130 /* DeclareKeyword */:
101023                             case 122 /* AbstractKeyword */:
101024                                 diagnostics.push(createDiagnosticForNode(modifier, ts.Diagnostics.The_0_modifier_can_only_be_used_in_TypeScript_files, ts.tokenToString(modifier.kind)));
101025                                 break;
101026                             // These are all legal modifiers.
101027                             case 120 /* StaticKeyword */:
101028                             case 89 /* ExportKeyword */:
101029                             case 84 /* DefaultKeyword */:
101030                         }
101031                     }
101032                 }
101033                 function createDiagnosticForNodeArray(nodes, message, arg0, arg1, arg2) {
101034                     var start = nodes.pos;
101035                     return ts.createFileDiagnostic(sourceFile, start, nodes.end - start, message, arg0, arg1, arg2);
101036                 }
101037                 // Since these are syntactic diagnostics, parent might not have been set
101038                 // this means the sourceFile cannot be infered from the node
101039                 function createDiagnosticForNode(node, message, arg0, arg1, arg2) {
101040                     return ts.createDiagnosticForNodeInSourceFile(sourceFile, node, message, arg0, arg1, arg2);
101041                 }
101042             });
101043         }
101044         function getDeclarationDiagnosticsWorker(sourceFile, cancellationToken) {
101045             return getAndCacheDiagnostics(sourceFile, cancellationToken, cachedDeclarationDiagnosticsForFile, getDeclarationDiagnosticsForFileNoCache);
101046         }
101047         function getDeclarationDiagnosticsForFileNoCache(sourceFile, cancellationToken) {
101048             return runWithCancellationToken(function () {
101049                 var resolver = getDiagnosticsProducingTypeChecker().getEmitResolver(sourceFile, cancellationToken);
101050                 // Don't actually write any files since we're just getting diagnostics.
101051                 return ts.getDeclarationDiagnostics(getEmitHost(ts.noop), resolver, sourceFile) || ts.emptyArray;
101052             });
101053         }
101054         function getAndCacheDiagnostics(sourceFile, cancellationToken, cache, getDiagnostics) {
101055             var cachedResult = sourceFile
101056                 ? cache.perFile && cache.perFile.get(sourceFile.path)
101057                 : cache.allDiagnostics;
101058             if (cachedResult) {
101059                 return cachedResult;
101060             }
101061             var result = getDiagnostics(sourceFile, cancellationToken);
101062             if (sourceFile) {
101063                 if (!cache.perFile) {
101064                     cache.perFile = ts.createMap();
101065                 }
101066                 cache.perFile.set(sourceFile.path, result);
101067             }
101068             else {
101069                 cache.allDiagnostics = result;
101070             }
101071             return result;
101072         }
101073         function getDeclarationDiagnosticsForFile(sourceFile, cancellationToken) {
101074             return sourceFile.isDeclarationFile ? [] : getDeclarationDiagnosticsWorker(sourceFile, cancellationToken);
101075         }
101076         function getOptionsDiagnostics() {
101077             return ts.sortAndDeduplicateDiagnostics(ts.concatenate(fileProcessingDiagnostics.getGlobalDiagnostics(), ts.concatenate(programDiagnostics.getGlobalDiagnostics(), getOptionsDiagnosticsOfConfigFile())));
101078         }
101079         function getOptionsDiagnosticsOfConfigFile() {
101080             if (!options.configFile) {
101081                 return ts.emptyArray;
101082             }
101083             var diagnostics = programDiagnostics.getDiagnostics(options.configFile.fileName);
101084             forEachResolvedProjectReference(function (resolvedRef) {
101085                 if (resolvedRef) {
101086                     diagnostics = ts.concatenate(diagnostics, programDiagnostics.getDiagnostics(resolvedRef.sourceFile.fileName));
101087                 }
101088             });
101089             return diagnostics;
101090         }
101091         function getGlobalDiagnostics() {
101092             return rootNames.length ? ts.sortAndDeduplicateDiagnostics(getDiagnosticsProducingTypeChecker().getGlobalDiagnostics().slice()) : ts.emptyArray;
101093         }
101094         function getConfigFileParsingDiagnostics() {
101095             return configFileParsingDiagnostics || ts.emptyArray;
101096         }
101097         function processRootFile(fileName, isDefaultLib, ignoreNoDefaultLib) {
101098             processSourceFile(ts.normalizePath(fileName), isDefaultLib, ignoreNoDefaultLib, /*packageId*/ undefined);
101099         }
101100         function fileReferenceIsEqualTo(a, b) {
101101             return a.fileName === b.fileName;
101102         }
101103         function moduleNameIsEqualTo(a, b) {
101104             return a.kind === 75 /* Identifier */
101105                 ? b.kind === 75 /* Identifier */ && a.escapedText === b.escapedText
101106                 : b.kind === 10 /* StringLiteral */ && a.text === b.text;
101107         }
101108         function collectExternalModuleReferences(file) {
101109             if (file.imports) {
101110                 return;
101111             }
101112             var isJavaScriptFile = ts.isSourceFileJS(file);
101113             var isExternalModuleFile = ts.isExternalModule(file);
101114             // file.imports may not be undefined if there exists dynamic import
101115             var imports;
101116             var moduleAugmentations;
101117             var ambientModules;
101118             // If we are importing helpers, we need to add a synthetic reference to resolve the
101119             // helpers library.
101120             if (options.importHelpers
101121                 && (options.isolatedModules || isExternalModuleFile)
101122                 && !file.isDeclarationFile) {
101123                 // synthesize 'import "tslib"' declaration
101124                 var externalHelpersModuleReference = ts.createLiteral(ts.externalHelpersModuleNameText);
101125                 var importDecl = ts.createImportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, /*importClause*/ undefined, externalHelpersModuleReference);
101126                 ts.addEmitFlags(importDecl, 67108864 /* NeverApplyImportHelper */);
101127                 externalHelpersModuleReference.parent = importDecl;
101128                 importDecl.parent = file;
101129                 imports = [externalHelpersModuleReference];
101130             }
101131             for (var _i = 0, _a = file.statements; _i < _a.length; _i++) {
101132                 var node = _a[_i];
101133                 collectModuleReferences(node, /*inAmbientModule*/ false);
101134             }
101135             if ((file.flags & 1048576 /* PossiblyContainsDynamicImport */) || isJavaScriptFile) {
101136                 collectDynamicImportOrRequireCalls(file);
101137             }
101138             file.imports = imports || ts.emptyArray;
101139             file.moduleAugmentations = moduleAugmentations || ts.emptyArray;
101140             file.ambientModuleNames = ambientModules || ts.emptyArray;
101141             return;
101142             function collectModuleReferences(node, inAmbientModule) {
101143                 if (ts.isAnyImportOrReExport(node)) {
101144                     var moduleNameExpr = ts.getExternalModuleName(node);
101145                     // TypeScript 1.0 spec (April 2014): 12.1.6
101146                     // An ExternalImportDeclaration in an AmbientExternalModuleDeclaration may reference other external modules
101147                     // only through top - level external module names. Relative external module names are not permitted.
101148                     if (moduleNameExpr && ts.isStringLiteral(moduleNameExpr) && moduleNameExpr.text && (!inAmbientModule || !ts.isExternalModuleNameRelative(moduleNameExpr.text))) {
101149                         imports = ts.append(imports, moduleNameExpr);
101150                     }
101151                 }
101152                 else if (ts.isModuleDeclaration(node)) {
101153                     if (ts.isAmbientModule(node) && (inAmbientModule || ts.hasModifier(node, 2 /* Ambient */) || file.isDeclarationFile)) {
101154                         var nameText = ts.getTextOfIdentifierOrLiteral(node.name);
101155                         // Ambient module declarations can be interpreted as augmentations for some existing external modules.
101156                         // This will happen in two cases:
101157                         // - if current file is external module then module augmentation is a ambient module declaration defined in the top level scope
101158                         // - if current file is not external module then module augmentation is an ambient module declaration with non-relative module name
101159                         //   immediately nested in top level ambient module declaration .
101160                         if (isExternalModuleFile || (inAmbientModule && !ts.isExternalModuleNameRelative(nameText))) {
101161                             (moduleAugmentations || (moduleAugmentations = [])).push(node.name);
101162                         }
101163                         else if (!inAmbientModule) {
101164                             if (file.isDeclarationFile) {
101165                                 // for global .d.ts files record name of ambient module
101166                                 (ambientModules || (ambientModules = [])).push(nameText);
101167                             }
101168                             // An AmbientExternalModuleDeclaration declares an external module.
101169                             // This type of declaration is permitted only in the global module.
101170                             // The StringLiteral must specify a top - level external module name.
101171                             // Relative external module names are not permitted
101172                             // NOTE: body of ambient module is always a module block, if it exists
101173                             var body = node.body;
101174                             if (body) {
101175                                 for (var _i = 0, _a = body.statements; _i < _a.length; _i++) {
101176                                     var statement = _a[_i];
101177                                     collectModuleReferences(statement, /*inAmbientModule*/ true);
101178                                 }
101179                             }
101180                         }
101181                     }
101182                 }
101183             }
101184             function collectDynamicImportOrRequireCalls(file) {
101185                 var r = /import|require/g;
101186                 while (r.exec(file.text) !== null) { // eslint-disable-line no-null/no-null
101187                     var node = getNodeAtPosition(file, r.lastIndex);
101188                     if (ts.isRequireCall(node, /*checkArgumentIsStringLiteralLike*/ true)) {
101189                         imports = ts.append(imports, node.arguments[0]);
101190                     }
101191                     // we have to check the argument list has length of 1. We will still have to process these even though we have parsing error.
101192                     else if (ts.isImportCall(node) && node.arguments.length === 1 && ts.isStringLiteralLike(node.arguments[0])) {
101193                         imports = ts.append(imports, node.arguments[0]);
101194                     }
101195                     else if (ts.isLiteralImportTypeNode(node)) {
101196                         imports = ts.append(imports, node.argument.literal);
101197                     }
101198                 }
101199             }
101200             /** Returns a token if position is in [start-of-leading-trivia, end), includes JSDoc only in JS files */
101201             function getNodeAtPosition(sourceFile, position) {
101202                 var current = sourceFile;
101203                 var getContainingChild = function (child) {
101204                     if (child.pos <= position && (position < child.end || (position === child.end && (child.kind === 1 /* EndOfFileToken */)))) {
101205                         return child;
101206                     }
101207                 };
101208                 while (true) {
101209                     var child = isJavaScriptFile && ts.hasJSDocNodes(current) && ts.forEach(current.jsDoc, getContainingChild) || ts.forEachChild(current, getContainingChild);
101210                     if (!child) {
101211                         return current;
101212                     }
101213                     current = child;
101214                 }
101215             }
101216         }
101217         function getLibFileFromReference(ref) {
101218             var libName = ts.toFileNameLowerCase(ref.fileName);
101219             var libFileName = ts.libMap.get(libName);
101220             if (libFileName) {
101221                 return getSourceFile(ts.combinePaths(defaultLibraryPath, libFileName));
101222             }
101223         }
101224         /** This should have similar behavior to 'processSourceFile' without diagnostics or mutation. */
101225         function getSourceFileFromReference(referencingFile, ref) {
101226             return getSourceFileFromReferenceWorker(resolveTripleslashReference(ref.fileName, referencingFile.fileName), function (fileName) { return filesByName.get(toPath(fileName)) || undefined; });
101227         }
101228         function getSourceFileFromReferenceWorker(fileName, getSourceFile, fail, refFile) {
101229             if (ts.hasExtension(fileName)) {
101230                 var canonicalFileName_1 = host.getCanonicalFileName(fileName);
101231                 if (!options.allowNonTsExtensions && !ts.forEach(supportedExtensionsWithJsonIfResolveJsonModule, function (extension) { return ts.fileExtensionIs(canonicalFileName_1, extension); })) {
101232                     if (fail) {
101233                         if (ts.hasJSFileExtension(canonicalFileName_1)) {
101234                             fail(ts.Diagnostics.File_0_is_a_JavaScript_file_Did_you_mean_to_enable_the_allowJs_option, fileName);
101235                         }
101236                         else {
101237                             fail(ts.Diagnostics.File_0_has_an_unsupported_extension_The_only_supported_extensions_are_1, fileName, "'" + supportedExtensions.join("', '") + "'");
101238                         }
101239                     }
101240                     return undefined;
101241                 }
101242                 var sourceFile = getSourceFile(fileName);
101243                 if (fail) {
101244                     if (!sourceFile) {
101245                         var redirect = getProjectReferenceRedirect(fileName);
101246                         if (redirect) {
101247                             fail(ts.Diagnostics.Output_file_0_has_not_been_built_from_source_file_1, redirect, fileName);
101248                         }
101249                         else {
101250                             fail(ts.Diagnostics.File_0_not_found, fileName);
101251                         }
101252                     }
101253                     else if (refFile && canonicalFileName_1 === host.getCanonicalFileName(refFile.fileName)) {
101254                         fail(ts.Diagnostics.A_file_cannot_have_a_reference_to_itself);
101255                     }
101256                 }
101257                 return sourceFile;
101258             }
101259             else {
101260                 var sourceFileNoExtension = options.allowNonTsExtensions && getSourceFile(fileName);
101261                 if (sourceFileNoExtension)
101262                     return sourceFileNoExtension;
101263                 if (fail && options.allowNonTsExtensions) {
101264                     fail(ts.Diagnostics.File_0_not_found, fileName);
101265                     return undefined;
101266                 }
101267                 var sourceFileWithAddedExtension = ts.forEach(supportedExtensions, function (extension) { return getSourceFile(fileName + extension); });
101268                 if (fail && !sourceFileWithAddedExtension)
101269                     fail(ts.Diagnostics.Could_not_resolve_the_path_0_with_the_extensions_Colon_1, fileName, "'" + supportedExtensions.join("', '") + "'");
101270                 return sourceFileWithAddedExtension;
101271             }
101272         }
101273         /** This has side effects through `findSourceFile`. */
101274         function processSourceFile(fileName, isDefaultLib, ignoreNoDefaultLib, packageId, refFile) {
101275             getSourceFileFromReferenceWorker(fileName, function (fileName) { return findSourceFile(fileName, toPath(fileName), isDefaultLib, ignoreNoDefaultLib, refFile, packageId); }, // TODO: GH#18217
101276             function (diagnostic) {
101277                 var args = [];
101278                 for (var _i = 1; _i < arguments.length; _i++) {
101279                     args[_i - 1] = arguments[_i];
101280                 }
101281                 return fileProcessingDiagnostics.add(createRefFileDiagnostic.apply(void 0, __spreadArrays([refFile, diagnostic], args)));
101282             }, refFile && refFile.file);
101283         }
101284         function reportFileNamesDifferOnlyInCasingError(fileName, existingFile, refFile) {
101285             var refs = !refFile ? refFileMap && refFileMap.get(existingFile.path) : undefined;
101286             var refToReportErrorOn = refs && ts.find(refs, function (ref) { return ref.referencedFileName === existingFile.fileName; });
101287             fileProcessingDiagnostics.add(refToReportErrorOn ?
101288                 createFileDiagnosticAtReference(refToReportErrorOn, ts.Diagnostics.Already_included_file_name_0_differs_from_file_name_1_only_in_casing, existingFile.fileName, fileName) :
101289                 createRefFileDiagnostic(refFile, ts.Diagnostics.File_name_0_differs_from_already_included_file_name_1_only_in_casing, fileName, existingFile.fileName));
101290         }
101291         function createRedirectSourceFile(redirectTarget, unredirected, fileName, path, resolvedPath, originalFileName) {
101292             var redirect = Object.create(redirectTarget);
101293             redirect.fileName = fileName;
101294             redirect.path = path;
101295             redirect.resolvedPath = resolvedPath;
101296             redirect.originalFileName = originalFileName;
101297             redirect.redirectInfo = { redirectTarget: redirectTarget, unredirected: unredirected };
101298             sourceFilesFoundSearchingNodeModules.set(path, currentNodeModulesDepth > 0);
101299             Object.defineProperties(redirect, {
101300                 id: {
101301                     get: function () { return this.redirectInfo.redirectTarget.id; },
101302                     set: function (value) { this.redirectInfo.redirectTarget.id = value; },
101303                 },
101304                 symbol: {
101305                     get: function () { return this.redirectInfo.redirectTarget.symbol; },
101306                     set: function (value) { this.redirectInfo.redirectTarget.symbol = value; },
101307                 },
101308             });
101309             return redirect;
101310         }
101311         // Get source file from normalized fileName
101312         function findSourceFile(fileName, path, isDefaultLib, ignoreNoDefaultLib, refFile, packageId) {
101313             if (useSourceOfProjectReferenceRedirect) {
101314                 var source = getSourceOfProjectReferenceRedirect(fileName);
101315                 // If preserveSymlinks is true, module resolution wont jump the symlink
101316                 // but the resolved real path may be the .d.ts from project reference
101317                 // Note:: Currently we try the real path only if the
101318                 // file is from node_modules to avoid having to run real path on all file paths
101319                 if (!source &&
101320                     host.realpath &&
101321                     options.preserveSymlinks &&
101322                     ts.isDeclarationFileName(fileName) &&
101323                     ts.stringContains(fileName, ts.nodeModulesPathPart)) {
101324                     var realPath = host.realpath(fileName);
101325                     if (realPath !== fileName)
101326                         source = getSourceOfProjectReferenceRedirect(realPath);
101327                 }
101328                 if (source) {
101329                     var file_1 = ts.isString(source) ?
101330                         findSourceFile(source, toPath(source), isDefaultLib, ignoreNoDefaultLib, refFile, packageId) :
101331                         undefined;
101332                     if (file_1)
101333                         addFileToFilesByName(file_1, path, /*redirectedPath*/ undefined);
101334                     return file_1;
101335                 }
101336             }
101337             var originalFileName = fileName;
101338             if (filesByName.has(path)) {
101339                 var file_2 = filesByName.get(path);
101340                 addFileToRefFileMap(fileName, file_2 || undefined, refFile);
101341                 // try to check if we've already seen this file but with a different casing in path
101342                 // NOTE: this only makes sense for case-insensitive file systems, and only on files which are not redirected
101343                 if (file_2 && options.forceConsistentCasingInFileNames) {
101344                     var checkedName = file_2.fileName;
101345                     var isRedirect = toPath(checkedName) !== toPath(fileName);
101346                     if (isRedirect) {
101347                         fileName = getProjectReferenceRedirect(fileName) || fileName;
101348                     }
101349                     // Check if it differs only in drive letters its ok to ignore that error:
101350                     var checkedAbsolutePath = ts.getNormalizedAbsolutePathWithoutRoot(checkedName, currentDirectory);
101351                     var inputAbsolutePath = ts.getNormalizedAbsolutePathWithoutRoot(fileName, currentDirectory);
101352                     if (checkedAbsolutePath !== inputAbsolutePath) {
101353                         reportFileNamesDifferOnlyInCasingError(fileName, file_2, refFile);
101354                     }
101355                 }
101356                 // If the file was previously found via a node_modules search, but is now being processed as a root file,
101357                 // then everything it sucks in may also be marked incorrectly, and needs to be checked again.
101358                 if (file_2 && sourceFilesFoundSearchingNodeModules.get(file_2.path) && currentNodeModulesDepth === 0) {
101359                     sourceFilesFoundSearchingNodeModules.set(file_2.path, false);
101360                     if (!options.noResolve) {
101361                         processReferencedFiles(file_2, isDefaultLib);
101362                         processTypeReferenceDirectives(file_2);
101363                     }
101364                     if (!options.noLib) {
101365                         processLibReferenceDirectives(file_2);
101366                     }
101367                     modulesWithElidedImports.set(file_2.path, false);
101368                     processImportedModules(file_2);
101369                 }
101370                 // See if we need to reprocess the imports due to prior skipped imports
101371                 else if (file_2 && modulesWithElidedImports.get(file_2.path)) {
101372                     if (currentNodeModulesDepth < maxNodeModuleJsDepth) {
101373                         modulesWithElidedImports.set(file_2.path, false);
101374                         processImportedModules(file_2);
101375                     }
101376                 }
101377                 return file_2 || undefined;
101378             }
101379             var redirectedPath;
101380             if (refFile && !useSourceOfProjectReferenceRedirect) {
101381                 var redirectProject = getProjectReferenceRedirectProject(fileName);
101382                 if (redirectProject) {
101383                     if (redirectProject.commandLine.options.outFile || redirectProject.commandLine.options.out) {
101384                         // Shouldnt create many to 1 mapping file in --out scenario
101385                         return undefined;
101386                     }
101387                     var redirect = getProjectReferenceOutputName(redirectProject, fileName);
101388                     fileName = redirect;
101389                     // Once we start redirecting to a file, we can potentially come back to it
101390                     // via a back-reference from another file in the .d.ts folder. If that happens we'll
101391                     // end up trying to add it to the program *again* because we were tracking it via its
101392                     // original (un-redirected) name. So we have to map both the original path and the redirected path
101393                     // to the source file we're about to find/create
101394                     redirectedPath = toPath(redirect);
101395                 }
101396             }
101397             // We haven't looked for this file, do so now and cache result
101398             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);
101399             if (packageId) {
101400                 var packageIdKey = ts.packageIdToString(packageId);
101401                 var fileFromPackageId = packageIdToSourceFile.get(packageIdKey);
101402                 if (fileFromPackageId) {
101403                     // Some other SourceFile already exists with this package name and version.
101404                     // Instead of creating a duplicate, just redirect to the existing one.
101405                     var dupFile = createRedirectSourceFile(fileFromPackageId, file, fileName, path, toPath(fileName), originalFileName); // TODO: GH#18217
101406                     redirectTargetsMap.add(fileFromPackageId.path, fileName);
101407                     addFileToFilesByName(dupFile, path, redirectedPath);
101408                     sourceFileToPackageName.set(path, packageId.name);
101409                     processingOtherFiles.push(dupFile);
101410                     return dupFile;
101411                 }
101412                 else if (file) {
101413                     // This is the first source file to have this packageId.
101414                     packageIdToSourceFile.set(packageIdKey, file);
101415                     sourceFileToPackageName.set(path, packageId.name);
101416                 }
101417             }
101418             addFileToFilesByName(file, path, redirectedPath);
101419             if (file) {
101420                 sourceFilesFoundSearchingNodeModules.set(path, currentNodeModulesDepth > 0);
101421                 file.fileName = fileName; // Ensure that source file has same name as what we were looking for
101422                 file.path = path;
101423                 file.resolvedPath = toPath(fileName);
101424                 file.originalFileName = originalFileName;
101425                 addFileToRefFileMap(fileName, file, refFile);
101426                 if (host.useCaseSensitiveFileNames()) {
101427                     var pathLowerCase = ts.toFileNameLowerCase(path);
101428                     // for case-sensitive file systems check if we've already seen some file with similar filename ignoring case
101429                     var existingFile = filesByNameIgnoreCase.get(pathLowerCase);
101430                     if (existingFile) {
101431                         reportFileNamesDifferOnlyInCasingError(fileName, existingFile, refFile);
101432                     }
101433                     else {
101434                         filesByNameIgnoreCase.set(pathLowerCase, file);
101435                     }
101436                 }
101437                 skipDefaultLib = skipDefaultLib || (file.hasNoDefaultLib && !ignoreNoDefaultLib);
101438                 if (!options.noResolve) {
101439                     processReferencedFiles(file, isDefaultLib);
101440                     processTypeReferenceDirectives(file);
101441                 }
101442                 if (!options.noLib) {
101443                     processLibReferenceDirectives(file);
101444                 }
101445                 // always process imported modules to record module name resolutions
101446                 processImportedModules(file);
101447                 if (isDefaultLib) {
101448                     processingDefaultLibFiles.push(file);
101449                 }
101450                 else {
101451                     processingOtherFiles.push(file);
101452                 }
101453             }
101454             return file;
101455         }
101456         function addFileToRefFileMap(referencedFileName, file, refFile) {
101457             if (refFile && file) {
101458                 (refFileMap || (refFileMap = ts.createMultiMap())).add(file.path, {
101459                     referencedFileName: referencedFileName,
101460                     kind: refFile.kind,
101461                     index: refFile.index,
101462                     file: refFile.file.path
101463                 });
101464             }
101465         }
101466         function addFileToFilesByName(file, path, redirectedPath) {
101467             if (redirectedPath) {
101468                 filesByName.set(redirectedPath, file);
101469                 filesByName.set(path, file || false);
101470             }
101471             else {
101472                 filesByName.set(path, file);
101473             }
101474         }
101475         function getProjectReferenceRedirect(fileName) {
101476             var referencedProject = getProjectReferenceRedirectProject(fileName);
101477             return referencedProject && getProjectReferenceOutputName(referencedProject, fileName);
101478         }
101479         function getProjectReferenceRedirectProject(fileName) {
101480             // Ignore dts or any json files
101481             if (!resolvedProjectReferences || !resolvedProjectReferences.length || ts.fileExtensionIs(fileName, ".d.ts" /* Dts */) || ts.fileExtensionIs(fileName, ".json" /* Json */)) {
101482                 return undefined;
101483             }
101484             // If this file is produced by a referenced project, we need to rewrite it to
101485             // look in the output folder of the referenced project rather than the input
101486             return getResolvedProjectReferenceToRedirect(fileName);
101487         }
101488         function getProjectReferenceOutputName(referencedProject, fileName) {
101489             var out = referencedProject.commandLine.options.outFile || referencedProject.commandLine.options.out;
101490             return out ?
101491                 ts.changeExtension(out, ".d.ts" /* Dts */) :
101492                 ts.getOutputDeclarationFileName(fileName, referencedProject.commandLine, !host.useCaseSensitiveFileNames());
101493         }
101494         /**
101495          * Get the referenced project if the file is input file from that reference project
101496          */
101497         function getResolvedProjectReferenceToRedirect(fileName) {
101498             if (mapFromFileToProjectReferenceRedirects === undefined) {
101499                 mapFromFileToProjectReferenceRedirects = ts.createMap();
101500                 forEachResolvedProjectReference(function (referencedProject, referenceProjectPath) {
101501                     // not input file from the referenced project, ignore
101502                     if (referencedProject &&
101503                         toPath(options.configFilePath) !== referenceProjectPath) {
101504                         referencedProject.commandLine.fileNames.forEach(function (f) {
101505                             return mapFromFileToProjectReferenceRedirects.set(toPath(f), referenceProjectPath);
101506                         });
101507                     }
101508                 });
101509             }
101510             var referencedProjectPath = mapFromFileToProjectReferenceRedirects.get(toPath(fileName));
101511             return referencedProjectPath && getResolvedProjectReferenceByPath(referencedProjectPath);
101512         }
101513         function forEachResolvedProjectReference(cb) {
101514             return forEachProjectReference(projectReferences, resolvedProjectReferences, function (resolvedRef, index, parent) {
101515                 var ref = (parent ? parent.commandLine.projectReferences : projectReferences)[index];
101516                 var resolvedRefPath = toPath(resolveProjectReferencePath(ref));
101517                 return cb(resolvedRef, resolvedRefPath);
101518             });
101519         }
101520         function getSourceOfProjectReferenceRedirect(file) {
101521             if (!ts.isDeclarationFileName(file))
101522                 return undefined;
101523             if (mapFromToProjectReferenceRedirectSource === undefined) {
101524                 mapFromToProjectReferenceRedirectSource = ts.createMap();
101525                 forEachResolvedProjectReference(function (resolvedRef) {
101526                     if (resolvedRef) {
101527                         var out = resolvedRef.commandLine.options.outFile || resolvedRef.commandLine.options.out;
101528                         if (out) {
101529                             // Dont know which source file it means so return true?
101530                             var outputDts = ts.changeExtension(out, ".d.ts" /* Dts */);
101531                             mapFromToProjectReferenceRedirectSource.set(toPath(outputDts), true);
101532                         }
101533                         else {
101534                             ts.forEach(resolvedRef.commandLine.fileNames, function (fileName) {
101535                                 if (!ts.fileExtensionIs(fileName, ".d.ts" /* Dts */) && !ts.fileExtensionIs(fileName, ".json" /* Json */)) {
101536                                     var outputDts = ts.getOutputDeclarationFileName(fileName, resolvedRef.commandLine, host.useCaseSensitiveFileNames());
101537                                     mapFromToProjectReferenceRedirectSource.set(toPath(outputDts), fileName);
101538                                 }
101539                             });
101540                         }
101541                     }
101542                 });
101543             }
101544             return mapFromToProjectReferenceRedirectSource.get(toPath(file));
101545         }
101546         function isSourceOfProjectReferenceRedirect(fileName) {
101547             return useSourceOfProjectReferenceRedirect && !!getResolvedProjectReferenceToRedirect(fileName);
101548         }
101549         function forEachProjectReference(projectReferences, resolvedProjectReferences, cbResolvedRef, cbRef) {
101550             var seenResolvedRefs;
101551             return worker(projectReferences, resolvedProjectReferences, /*parent*/ undefined, cbResolvedRef, cbRef);
101552             function worker(projectReferences, resolvedProjectReferences, parent, cbResolvedRef, cbRef) {
101553                 // Visit project references first
101554                 if (cbRef) {
101555                     var result = cbRef(projectReferences, parent);
101556                     if (result) {
101557                         return result;
101558                     }
101559                 }
101560                 return ts.forEach(resolvedProjectReferences, function (resolvedRef, index) {
101561                     if (ts.contains(seenResolvedRefs, resolvedRef)) {
101562                         // ignore recursives
101563                         return undefined;
101564                     }
101565                     var result = cbResolvedRef(resolvedRef, index, parent);
101566                     if (result) {
101567                         return result;
101568                     }
101569                     if (!resolvedRef)
101570                         return undefined;
101571                     (seenResolvedRefs || (seenResolvedRefs = [])).push(resolvedRef);
101572                     return worker(resolvedRef.commandLine.projectReferences, resolvedRef.references, resolvedRef, cbResolvedRef, cbRef);
101573                 });
101574             }
101575         }
101576         function getResolvedProjectReferenceByPath(projectReferencePath) {
101577             if (!projectReferenceRedirects) {
101578                 return undefined;
101579             }
101580             return projectReferenceRedirects.get(projectReferencePath) || undefined;
101581         }
101582         function processReferencedFiles(file, isDefaultLib) {
101583             ts.forEach(file.referencedFiles, function (ref, index) {
101584                 var referencedFileName = resolveTripleslashReference(ref.fileName, file.originalFileName);
101585                 processSourceFile(referencedFileName, isDefaultLib, 
101586                 /*ignoreNoDefaultLib*/ false, 
101587                 /*packageId*/ undefined, {
101588                     kind: ts.RefFileKind.ReferenceFile,
101589                     index: index,
101590                     file: file,
101591                     pos: ref.pos,
101592                     end: ref.end
101593                 });
101594             });
101595         }
101596         function processTypeReferenceDirectives(file) {
101597             // We lower-case all type references because npm automatically lowercases all packages. See GH#9824.
101598             var typeDirectives = ts.map(file.typeReferenceDirectives, function (ref) { return ts.toFileNameLowerCase(ref.fileName); });
101599             if (!typeDirectives) {
101600                 return;
101601             }
101602             var resolutions = resolveTypeReferenceDirectiveNamesWorker(typeDirectives, file.originalFileName, getResolvedProjectReferenceToRedirect(file.originalFileName));
101603             for (var i = 0; i < typeDirectives.length; i++) {
101604                 var ref = file.typeReferenceDirectives[i];
101605                 var resolvedTypeReferenceDirective = resolutions[i];
101606                 // store resolved type directive on the file
101607                 var fileName = ts.toFileNameLowerCase(ref.fileName);
101608                 ts.setResolvedTypeReferenceDirective(file, fileName, resolvedTypeReferenceDirective);
101609                 processTypeReferenceDirective(fileName, resolvedTypeReferenceDirective, {
101610                     kind: ts.RefFileKind.TypeReferenceDirective,
101611                     index: i,
101612                     file: file,
101613                     pos: ref.pos,
101614                     end: ref.end
101615                 });
101616             }
101617         }
101618         function processTypeReferenceDirective(typeReferenceDirective, resolvedTypeReferenceDirective, refFile) {
101619             // If we already found this library as a primary reference - nothing to do
101620             var previousResolution = resolvedTypeReferenceDirectives.get(typeReferenceDirective);
101621             if (previousResolution && previousResolution.primary) {
101622                 return;
101623             }
101624             var saveResolution = true;
101625             if (resolvedTypeReferenceDirective) {
101626                 if (resolvedTypeReferenceDirective.isExternalLibraryImport)
101627                     currentNodeModulesDepth++;
101628                 if (resolvedTypeReferenceDirective.primary) {
101629                     // resolved from the primary path
101630                     processSourceFile(resolvedTypeReferenceDirective.resolvedFileName, /*isDefaultLib*/ false, /*ignoreNoDefaultLib*/ false, resolvedTypeReferenceDirective.packageId, refFile); // TODO: GH#18217
101631                 }
101632                 else {
101633                     // If we already resolved to this file, it must have been a secondary reference. Check file contents
101634                     // for sameness and possibly issue an error
101635                     if (previousResolution) {
101636                         // Don't bother reading the file again if it's the same file.
101637                         if (resolvedTypeReferenceDirective.resolvedFileName !== previousResolution.resolvedFileName) {
101638                             var otherFileText = host.readFile(resolvedTypeReferenceDirective.resolvedFileName);
101639                             var existingFile_1 = getSourceFile(previousResolution.resolvedFileName);
101640                             if (otherFileText !== existingFile_1.text) {
101641                                 // Try looking up ref for original file
101642                                 var refs = !refFile ? refFileMap && refFileMap.get(existingFile_1.path) : undefined;
101643                                 var refToReportErrorOn = refs && ts.find(refs, function (ref) { return ref.referencedFileName === existingFile_1.fileName; });
101644                                 fileProcessingDiagnostics.add(refToReportErrorOn ?
101645                                     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) :
101646                                     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));
101647                             }
101648                         }
101649                         // don't overwrite previous resolution result
101650                         saveResolution = false;
101651                     }
101652                     else {
101653                         // First resolution of this library
101654                         processSourceFile(resolvedTypeReferenceDirective.resolvedFileName, /*isDefaultLib*/ false, /*ignoreNoDefaultLib*/ false, resolvedTypeReferenceDirective.packageId, refFile);
101655                     }
101656                 }
101657                 if (resolvedTypeReferenceDirective.isExternalLibraryImport)
101658                     currentNodeModulesDepth--;
101659             }
101660             else {
101661                 fileProcessingDiagnostics.add(createRefFileDiagnostic(refFile, ts.Diagnostics.Cannot_find_type_definition_file_for_0, typeReferenceDirective));
101662             }
101663             if (saveResolution) {
101664                 resolvedTypeReferenceDirectives.set(typeReferenceDirective, resolvedTypeReferenceDirective);
101665             }
101666         }
101667         function processLibReferenceDirectives(file) {
101668             ts.forEach(file.libReferenceDirectives, function (libReference) {
101669                 var libName = ts.toFileNameLowerCase(libReference.fileName);
101670                 var libFileName = ts.libMap.get(libName);
101671                 if (libFileName) {
101672                     // we ignore any 'no-default-lib' reference set on this file.
101673                     processRootFile(ts.combinePaths(defaultLibraryPath, libFileName), /*isDefaultLib*/ true, /*ignoreNoDefaultLib*/ true);
101674                 }
101675                 else {
101676                     var unqualifiedLibName = ts.removeSuffix(ts.removePrefix(libName, "lib."), ".d.ts");
101677                     var suggestion = ts.getSpellingSuggestion(unqualifiedLibName, ts.libs, ts.identity);
101678                     var message = suggestion ? ts.Diagnostics.Cannot_find_lib_definition_for_0_Did_you_mean_1 : ts.Diagnostics.Cannot_find_lib_definition_for_0;
101679                     fileProcessingDiagnostics.add(ts.createFileDiagnostic(file, libReference.pos, libReference.end - libReference.pos, message, libName, suggestion));
101680                 }
101681             });
101682         }
101683         function createRefFileDiagnostic(refFile, message) {
101684             var args = [];
101685             for (var _i = 2; _i < arguments.length; _i++) {
101686                 args[_i - 2] = arguments[_i];
101687             }
101688             if (!refFile) {
101689                 return ts.createCompilerDiagnostic.apply(void 0, __spreadArrays([message], args));
101690             }
101691             else {
101692                 return ts.createFileDiagnostic.apply(void 0, __spreadArrays([refFile.file, refFile.pos, refFile.end - refFile.pos, message], args));
101693             }
101694         }
101695         function getCanonicalFileName(fileName) {
101696             return host.getCanonicalFileName(fileName);
101697         }
101698         function processImportedModules(file) {
101699             collectExternalModuleReferences(file);
101700             if (file.imports.length || file.moduleAugmentations.length) {
101701                 // Because global augmentation doesn't have string literal name, we can check for global augmentation as such.
101702                 var moduleNames = getModuleNames(file);
101703                 var resolutions = resolveModuleNamesReusingOldState(moduleNames, ts.getNormalizedAbsolutePath(file.originalFileName, currentDirectory), file);
101704                 ts.Debug.assert(resolutions.length === moduleNames.length);
101705                 for (var i = 0; i < moduleNames.length; i++) {
101706                     var resolution = resolutions[i];
101707                     ts.setResolvedModule(file, moduleNames[i], resolution);
101708                     if (!resolution) {
101709                         continue;
101710                     }
101711                     var isFromNodeModulesSearch = resolution.isExternalLibraryImport;
101712                     var isJsFile = !ts.resolutionExtensionIsTSOrJson(resolution.extension);
101713                     var isJsFileFromNodeModules = isFromNodeModulesSearch && isJsFile;
101714                     var resolvedFileName = resolution.resolvedFileName;
101715                     if (isFromNodeModulesSearch) {
101716                         currentNodeModulesDepth++;
101717                     }
101718                     // add file to program only if:
101719                     // - resolution was successful
101720                     // - noResolve is falsy
101721                     // - module name comes from the list of imports
101722                     // - it's not a top level JavaScript module that exceeded the search max
101723                     var elideImport = isJsFileFromNodeModules && currentNodeModulesDepth > maxNodeModuleJsDepth;
101724                     // Don't add the file if it has a bad extension (e.g. 'tsx' if we don't have '--allowJs')
101725                     // This may still end up being an untyped module -- the file won't be included but imports will be allowed.
101726                     var shouldAddFile = resolvedFileName
101727                         && !getResolutionDiagnostic(options, resolution)
101728                         && !options.noResolve
101729                         && i < file.imports.length
101730                         && !elideImport
101731                         && !(isJsFile && !options.allowJs)
101732                         && (ts.isInJSFile(file.imports[i]) || !(file.imports[i].flags & 4194304 /* JSDoc */));
101733                     if (elideImport) {
101734                         modulesWithElidedImports.set(file.path, true);
101735                     }
101736                     else if (shouldAddFile) {
101737                         var path = toPath(resolvedFileName);
101738                         var pos = ts.skipTrivia(file.text, file.imports[i].pos);
101739                         findSourceFile(resolvedFileName, path, 
101740                         /*isDefaultLib*/ false, 
101741                         /*ignoreNoDefaultLib*/ false, {
101742                             kind: ts.RefFileKind.Import,
101743                             index: i,
101744                             file: file,
101745                             pos: pos,
101746                             end: file.imports[i].end
101747                         }, resolution.packageId);
101748                     }
101749                     if (isFromNodeModulesSearch) {
101750                         currentNodeModulesDepth--;
101751                     }
101752                 }
101753             }
101754             else {
101755                 // no imports - drop cached module resolutions
101756                 file.resolvedModules = undefined;
101757             }
101758         }
101759         function computeCommonSourceDirectory(sourceFiles) {
101760             var fileNames = ts.mapDefined(sourceFiles, function (file) { return file.isDeclarationFile ? undefined : file.fileName; });
101761             return computeCommonSourceDirectoryOfFilenames(fileNames, currentDirectory, getCanonicalFileName);
101762         }
101763         function checkSourceFilesBelongToPath(sourceFiles, rootDirectory) {
101764             var allFilesBelongToPath = true;
101765             var absoluteRootDirectoryPath = host.getCanonicalFileName(ts.getNormalizedAbsolutePath(rootDirectory, currentDirectory));
101766             var rootPaths;
101767             for (var _i = 0, sourceFiles_2 = sourceFiles; _i < sourceFiles_2.length; _i++) {
101768                 var sourceFile = sourceFiles_2[_i];
101769                 if (!sourceFile.isDeclarationFile) {
101770                     var absoluteSourceFilePath = host.getCanonicalFileName(ts.getNormalizedAbsolutePath(sourceFile.fileName, currentDirectory));
101771                     if (absoluteSourceFilePath.indexOf(absoluteRootDirectoryPath) !== 0) {
101772                         if (!rootPaths)
101773                             rootPaths = ts.arrayToSet(rootNames, toPath);
101774                         addProgramDiagnosticAtRefPath(sourceFile, rootPaths, ts.Diagnostics.File_0_is_not_under_rootDir_1_rootDir_is_expected_to_contain_all_source_files, sourceFile.fileName, rootDirectory);
101775                         allFilesBelongToPath = false;
101776                     }
101777                 }
101778             }
101779             return allFilesBelongToPath;
101780         }
101781         function parseProjectReferenceConfigFile(ref) {
101782             if (!projectReferenceRedirects) {
101783                 projectReferenceRedirects = ts.createMap();
101784             }
101785             // The actual filename (i.e. add "/tsconfig.json" if necessary)
101786             var refPath = resolveProjectReferencePath(ref);
101787             var sourceFilePath = toPath(refPath);
101788             var fromCache = projectReferenceRedirects.get(sourceFilePath);
101789             if (fromCache !== undefined) {
101790                 return fromCache || undefined;
101791             }
101792             var commandLine;
101793             var sourceFile;
101794             if (host.getParsedCommandLine) {
101795                 commandLine = host.getParsedCommandLine(refPath);
101796                 if (!commandLine) {
101797                     addFileToFilesByName(/*sourceFile*/ undefined, sourceFilePath, /*redirectedPath*/ undefined);
101798                     projectReferenceRedirects.set(sourceFilePath, false);
101799                     return undefined;
101800                 }
101801                 sourceFile = ts.Debug.checkDefined(commandLine.options.configFile);
101802                 ts.Debug.assert(!sourceFile.path || sourceFile.path === sourceFilePath);
101803                 addFileToFilesByName(sourceFile, sourceFilePath, /*redirectedPath*/ undefined);
101804             }
101805             else {
101806                 // An absolute path pointing to the containing directory of the config file
101807                 var basePath = ts.getNormalizedAbsolutePath(ts.getDirectoryPath(refPath), host.getCurrentDirectory());
101808                 sourceFile = host.getSourceFile(refPath, 100 /* JSON */);
101809                 addFileToFilesByName(sourceFile, sourceFilePath, /*redirectedPath*/ undefined);
101810                 if (sourceFile === undefined) {
101811                     projectReferenceRedirects.set(sourceFilePath, false);
101812                     return undefined;
101813                 }
101814                 commandLine = ts.parseJsonSourceFileConfigFileContent(sourceFile, configParsingHost, basePath, /*existingOptions*/ undefined, refPath);
101815             }
101816             sourceFile.fileName = refPath;
101817             sourceFile.path = sourceFilePath;
101818             sourceFile.resolvedPath = sourceFilePath;
101819             sourceFile.originalFileName = refPath;
101820             var resolvedRef = { commandLine: commandLine, sourceFile: sourceFile };
101821             projectReferenceRedirects.set(sourceFilePath, resolvedRef);
101822             if (commandLine.projectReferences) {
101823                 resolvedRef.references = commandLine.projectReferences.map(parseProjectReferenceConfigFile);
101824             }
101825             return resolvedRef;
101826         }
101827         function verifyCompilerOptions() {
101828             if (options.strictPropertyInitialization && !ts.getStrictOptionValue(options, "strictNullChecks")) {
101829                 createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "strictPropertyInitialization", "strictNullChecks");
101830             }
101831             if (options.isolatedModules) {
101832                 if (options.out) {
101833                     createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "out", "isolatedModules");
101834                 }
101835                 if (options.outFile) {
101836                     createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "outFile", "isolatedModules");
101837                 }
101838             }
101839             if (options.inlineSourceMap) {
101840                 if (options.sourceMap) {
101841                     createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "sourceMap", "inlineSourceMap");
101842                 }
101843                 if (options.mapRoot) {
101844                     createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "mapRoot", "inlineSourceMap");
101845                 }
101846             }
101847             if (options.paths && options.baseUrl === undefined) {
101848                 createDiagnosticForOptionName(ts.Diagnostics.Option_paths_cannot_be_used_without_specifying_baseUrl_option, "paths");
101849             }
101850             if (options.composite) {
101851                 if (options.declaration === false) {
101852                     createDiagnosticForOptionName(ts.Diagnostics.Composite_projects_may_not_disable_declaration_emit, "declaration");
101853                 }
101854                 if (options.incremental === false) {
101855                     createDiagnosticForOptionName(ts.Diagnostics.Composite_projects_may_not_disable_incremental_compilation, "declaration");
101856                 }
101857             }
101858             if (options.tsBuildInfoFile) {
101859                 if (!ts.isIncrementalCompilation(options)) {
101860                     createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1_or_option_2, "tsBuildInfoFile", "incremental", "composite");
101861                 }
101862             }
101863             else if (options.incremental && !options.outFile && !options.out && !options.configFilePath) {
101864                 programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_incremental_can_only_be_specified_using_tsconfig_emitting_to_single_file_or_when_option_tsBuildInfoFile_is_specified));
101865             }
101866             if (!options.listFilesOnly && options.noEmit && ts.isIncrementalCompilation(options)) {
101867                 createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "noEmit", options.incremental ? "incremental" : "composite");
101868             }
101869             verifyProjectReferences();
101870             // List of collected files is complete; validate exhautiveness if this is a project with a file list
101871             if (options.composite) {
101872                 var rootPaths = ts.arrayToSet(rootNames, toPath);
101873                 for (var _i = 0, files_3 = files; _i < files_3.length; _i++) {
101874                     var file = files_3[_i];
101875                     // Ignore file that is not emitted
101876                     if (ts.sourceFileMayBeEmitted(file, program) && !rootPaths.has(file.path)) {
101877                         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 || "");
101878                     }
101879                 }
101880             }
101881             if (options.paths) {
101882                 for (var key in options.paths) {
101883                     if (!ts.hasProperty(options.paths, key)) {
101884                         continue;
101885                     }
101886                     if (!ts.hasZeroOrOneAsteriskCharacter(key)) {
101887                         createDiagnosticForOptionPaths(/*onKey*/ true, key, ts.Diagnostics.Pattern_0_can_have_at_most_one_Asterisk_character, key);
101888                     }
101889                     if (ts.isArray(options.paths[key])) {
101890                         var len = options.paths[key].length;
101891                         if (len === 0) {
101892                             createDiagnosticForOptionPaths(/*onKey*/ false, key, ts.Diagnostics.Substitutions_for_pattern_0_shouldn_t_be_an_empty_array, key);
101893                         }
101894                         for (var i = 0; i < len; i++) {
101895                             var subst = options.paths[key][i];
101896                             var typeOfSubst = typeof subst;
101897                             if (typeOfSubst === "string") {
101898                                 if (!ts.hasZeroOrOneAsteriskCharacter(subst)) {
101899                                     createDiagnosticForOptionPathKeyValue(key, i, ts.Diagnostics.Substitution_0_in_pattern_1_can_have_at_most_one_Asterisk_character, subst, key);
101900                                 }
101901                             }
101902                             else {
101903                                 createDiagnosticForOptionPathKeyValue(key, i, ts.Diagnostics.Substitution_0_for_pattern_1_has_incorrect_type_expected_string_got_2, subst, key, typeOfSubst);
101904                             }
101905                         }
101906                     }
101907                     else {
101908                         createDiagnosticForOptionPaths(/*onKey*/ false, key, ts.Diagnostics.Substitutions_for_pattern_0_should_be_an_array, key);
101909                     }
101910                 }
101911             }
101912             if (!options.sourceMap && !options.inlineSourceMap) {
101913                 if (options.inlineSources) {
101914                     createDiagnosticForOptionName(ts.Diagnostics.Option_0_can_only_be_used_when_either_option_inlineSourceMap_or_option_sourceMap_is_provided, "inlineSources");
101915                 }
101916                 if (options.sourceRoot) {
101917                     createDiagnosticForOptionName(ts.Diagnostics.Option_0_can_only_be_used_when_either_option_inlineSourceMap_or_option_sourceMap_is_provided, "sourceRoot");
101918                 }
101919             }
101920             if (options.out && options.outFile) {
101921                 createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "out", "outFile");
101922             }
101923             if (options.mapRoot && !(options.sourceMap || options.declarationMap)) {
101924                 // Error to specify --mapRoot without --sourcemap
101925                 createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1_or_option_2, "mapRoot", "sourceMap", "declarationMap");
101926             }
101927             if (options.declarationDir) {
101928                 if (!ts.getEmitDeclarations(options)) {
101929                     createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1_or_option_2, "declarationDir", "declaration", "composite");
101930                 }
101931                 if (options.out || options.outFile) {
101932                     createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "declarationDir", options.out ? "out" : "outFile");
101933                 }
101934             }
101935             if (options.declarationMap && !ts.getEmitDeclarations(options)) {
101936                 createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1_or_option_2, "declarationMap", "declaration", "composite");
101937             }
101938             if (options.lib && options.noLib) {
101939                 createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "lib", "noLib");
101940             }
101941             if (options.noImplicitUseStrict && ts.getStrictOptionValue(options, "alwaysStrict")) {
101942                 createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "noImplicitUseStrict", "alwaysStrict");
101943             }
101944             var languageVersion = options.target || 0 /* ES3 */;
101945             var outFile = options.outFile || options.out;
101946             var firstNonAmbientExternalModuleSourceFile = ts.find(files, function (f) { return ts.isExternalModule(f) && !f.isDeclarationFile; });
101947             if (options.isolatedModules) {
101948                 if (options.module === ts.ModuleKind.None && languageVersion < 2 /* ES2015 */) {
101949                     createDiagnosticForOptionName(ts.Diagnostics.Option_isolatedModules_can_only_be_used_when_either_option_module_is_provided_or_option_target_is_ES2015_or_higher, "isolatedModules", "target");
101950                 }
101951                 var firstNonExternalModuleSourceFile = ts.find(files, function (f) { return !ts.isExternalModule(f) && !ts.isSourceFileJS(f) && !f.isDeclarationFile && f.scriptKind !== 6 /* JSON */; });
101952                 if (firstNonExternalModuleSourceFile) {
101953                     var span = ts.getErrorSpanForNode(firstNonExternalModuleSourceFile, firstNonExternalModuleSourceFile);
101954                     programDiagnostics.add(ts.createFileDiagnostic(firstNonExternalModuleSourceFile, span.start, span.length, ts.Diagnostics.All_files_must_be_modules_when_the_isolatedModules_flag_is_provided));
101955                 }
101956             }
101957             else if (firstNonAmbientExternalModuleSourceFile && languageVersion < 2 /* ES2015 */ && options.module === ts.ModuleKind.None) {
101958                 // We cannot use createDiagnosticFromNode because nodes do not have parents yet
101959                 var span = ts.getErrorSpanForNode(firstNonAmbientExternalModuleSourceFile, firstNonAmbientExternalModuleSourceFile.externalModuleIndicator);
101960                 programDiagnostics.add(ts.createFileDiagnostic(firstNonAmbientExternalModuleSourceFile, span.start, span.length, ts.Diagnostics.Cannot_use_imports_exports_or_module_augmentations_when_module_is_none));
101961             }
101962             // Cannot specify module gen that isn't amd or system with --out
101963             if (outFile && !options.emitDeclarationOnly) {
101964                 if (options.module && !(options.module === ts.ModuleKind.AMD || options.module === ts.ModuleKind.System)) {
101965                     createDiagnosticForOptionName(ts.Diagnostics.Only_amd_and_system_modules_are_supported_alongside_0, options.out ? "out" : "outFile", "module");
101966                 }
101967                 else if (options.module === undefined && firstNonAmbientExternalModuleSourceFile) {
101968                     var span = ts.getErrorSpanForNode(firstNonAmbientExternalModuleSourceFile, firstNonAmbientExternalModuleSourceFile.externalModuleIndicator);
101969                     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"));
101970                 }
101971             }
101972             if (options.resolveJsonModule) {
101973                 if (ts.getEmitModuleResolutionKind(options) !== ts.ModuleResolutionKind.NodeJs) {
101974                     createDiagnosticForOptionName(ts.Diagnostics.Option_resolveJsonModule_cannot_be_specified_without_node_module_resolution_strategy, "resolveJsonModule");
101975                 }
101976                 // Any emit other than common js, amd, es2015 or esnext is error
101977                 else if (!ts.hasJsonModuleEmitEnabled(options)) {
101978                     createDiagnosticForOptionName(ts.Diagnostics.Option_resolveJsonModule_can_only_be_specified_when_module_code_generation_is_commonjs_amd_es2015_or_esNext, "resolveJsonModule", "module");
101979                 }
101980             }
101981             // there has to be common source directory if user specified --outdir || --sourceRoot
101982             // if user specified --mapRoot, there needs to be common source directory if there would be multiple files being emitted
101983             if (options.outDir || // there is --outDir specified
101984                 options.sourceRoot || // there is --sourceRoot specified
101985                 options.mapRoot) { // there is --mapRoot specified
101986                 // Precalculate and cache the common source directory
101987                 var dir = getCommonSourceDirectory();
101988                 // 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
101989                 if (options.outDir && dir === "" && files.some(function (file) { return ts.getRootLength(file.fileName) > 1; })) {
101990                     createDiagnosticForOptionName(ts.Diagnostics.Cannot_find_the_common_subdirectory_path_for_the_input_files, "outDir");
101991                 }
101992             }
101993             if (options.useDefineForClassFields && languageVersion === 0 /* ES3 */) {
101994                 createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_when_option_target_is_ES3, "useDefineForClassFields");
101995             }
101996             if (options.checkJs && !options.allowJs) {
101997                 programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "checkJs", "allowJs"));
101998             }
101999             if (options.emitDeclarationOnly) {
102000                 if (!ts.getEmitDeclarations(options)) {
102001                     createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1_or_option_2, "emitDeclarationOnly", "declaration", "composite");
102002                 }
102003                 if (options.noEmit) {
102004                     createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "emitDeclarationOnly", "noEmit");
102005                 }
102006             }
102007             if (options.emitDecoratorMetadata &&
102008                 !options.experimentalDecorators) {
102009                 createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "emitDecoratorMetadata", "experimentalDecorators");
102010             }
102011             if (options.jsxFactory) {
102012                 if (options.reactNamespace) {
102013                     createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "reactNamespace", "jsxFactory");
102014                 }
102015                 if (!ts.parseIsolatedEntityName(options.jsxFactory, languageVersion)) {
102016                     createOptionValueDiagnostic("jsxFactory", ts.Diagnostics.Invalid_value_for_jsxFactory_0_is_not_a_valid_identifier_or_qualified_name, options.jsxFactory);
102017                 }
102018             }
102019             else if (options.reactNamespace && !ts.isIdentifierText(options.reactNamespace, languageVersion)) {
102020                 createOptionValueDiagnostic("reactNamespace", ts.Diagnostics.Invalid_value_for_reactNamespace_0_is_not_a_valid_identifier, options.reactNamespace);
102021             }
102022             // If the emit is enabled make sure that every output file is unique and not overwriting any of the input files
102023             if (!options.noEmit && !options.suppressOutputPathCheck) {
102024                 var emitHost = getEmitHost();
102025                 var emitFilesSeen_1 = ts.createMap();
102026                 ts.forEachEmittedFile(emitHost, function (emitFileNames) {
102027                     if (!options.emitDeclarationOnly) {
102028                         verifyEmitFilePath(emitFileNames.jsFilePath, emitFilesSeen_1);
102029                     }
102030                     verifyEmitFilePath(emitFileNames.declarationFilePath, emitFilesSeen_1);
102031                 });
102032             }
102033             // Verify that all the emit files are unique and don't overwrite input files
102034             function verifyEmitFilePath(emitFileName, emitFilesSeen) {
102035                 if (emitFileName) {
102036                     var emitFilePath = toPath(emitFileName);
102037                     // Report error if the output overwrites input file
102038                     if (filesByName.has(emitFilePath)) {
102039                         var chain = void 0;
102040                         if (!options.configFilePath) {
102041                             // The program is from either an inferred project or an external project
102042                             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);
102043                         }
102044                         chain = ts.chainDiagnosticMessages(chain, ts.Diagnostics.Cannot_write_file_0_because_it_would_overwrite_input_file, emitFileName);
102045                         blockEmittingOfFile(emitFileName, ts.createCompilerDiagnosticFromMessageChain(chain));
102046                     }
102047                     var emitFileKey = !host.useCaseSensitiveFileNames() ? ts.toFileNameLowerCase(emitFilePath) : emitFilePath;
102048                     // Report error if multiple files write into same file
102049                     if (emitFilesSeen.has(emitFileKey)) {
102050                         // Already seen the same emit file - report error
102051                         blockEmittingOfFile(emitFileName, ts.createCompilerDiagnostic(ts.Diagnostics.Cannot_write_file_0_because_it_would_be_overwritten_by_multiple_input_files, emitFileName));
102052                     }
102053                     else {
102054                         emitFilesSeen.set(emitFileKey, true);
102055                     }
102056                 }
102057             }
102058         }
102059         function createFileDiagnosticAtReference(refPathToReportErrorOn, message) {
102060             var _a, _b;
102061             var args = [];
102062             for (var _i = 2; _i < arguments.length; _i++) {
102063                 args[_i - 2] = arguments[_i];
102064             }
102065             var refFile = ts.Debug.checkDefined(getSourceFileByPath(refPathToReportErrorOn.file));
102066             var kind = refPathToReportErrorOn.kind, index = refPathToReportErrorOn.index;
102067             var pos, end;
102068             switch (kind) {
102069                 case ts.RefFileKind.Import:
102070                     pos = ts.skipTrivia(refFile.text, refFile.imports[index].pos);
102071                     end = refFile.imports[index].end;
102072                     break;
102073                 case ts.RefFileKind.ReferenceFile:
102074                     (_a = refFile.referencedFiles[index], pos = _a.pos, end = _a.end);
102075                     break;
102076                 case ts.RefFileKind.TypeReferenceDirective:
102077                     (_b = refFile.typeReferenceDirectives[index], pos = _b.pos, end = _b.end);
102078                     break;
102079                 default:
102080                     return ts.Debug.assertNever(kind);
102081             }
102082             return ts.createFileDiagnostic.apply(void 0, __spreadArrays([refFile, pos, end - pos, message], args));
102083         }
102084         function addProgramDiagnosticAtRefPath(file, rootPaths, message) {
102085             var args = [];
102086             for (var _i = 3; _i < arguments.length; _i++) {
102087                 args[_i - 3] = arguments[_i];
102088             }
102089             var refPaths = refFileMap && refFileMap.get(file.path);
102090             var refPathToReportErrorOn = ts.forEach(refPaths, function (refPath) { return rootPaths.has(refPath.file) ? refPath : undefined; }) ||
102091                 ts.elementAt(refPaths, 0);
102092             programDiagnostics.add(refPathToReportErrorOn ? createFileDiagnosticAtReference.apply(void 0, __spreadArrays([refPathToReportErrorOn, message], args)) : ts.createCompilerDiagnostic.apply(void 0, __spreadArrays([message], args)));
102093         }
102094         function verifyProjectReferences() {
102095             var buildInfoPath = !options.noEmit && !options.suppressOutputPathCheck ? ts.getTsBuildInfoEmitOutputFilePath(options) : undefined;
102096             forEachProjectReference(projectReferences, resolvedProjectReferences, function (resolvedRef, index, parent) {
102097                 var ref = (parent ? parent.commandLine.projectReferences : projectReferences)[index];
102098                 var parentFile = parent && parent.sourceFile;
102099                 if (!resolvedRef) {
102100                     createDiagnosticForReference(parentFile, index, ts.Diagnostics.File_0_not_found, ref.path);
102101                     return;
102102                 }
102103                 var options = resolvedRef.commandLine.options;
102104                 if (!options.composite) {
102105                     // ok to not have composite if the current program is container only
102106                     var inputs = parent ? parent.commandLine.fileNames : rootNames;
102107                     if (inputs.length) {
102108                         createDiagnosticForReference(parentFile, index, ts.Diagnostics.Referenced_project_0_must_have_setting_composite_Colon_true, ref.path);
102109                     }
102110                 }
102111                 if (ref.prepend) {
102112                     var out = options.outFile || options.out;
102113                     if (out) {
102114                         if (!host.fileExists(out)) {
102115                             createDiagnosticForReference(parentFile, index, ts.Diagnostics.Output_file_0_from_project_1_does_not_exist, out, ref.path);
102116                         }
102117                     }
102118                     else {
102119                         createDiagnosticForReference(parentFile, index, ts.Diagnostics.Cannot_prepend_project_0_because_it_does_not_have_outFile_set, ref.path);
102120                     }
102121                 }
102122                 if (!parent && buildInfoPath && buildInfoPath === ts.getTsBuildInfoEmitOutputFilePath(options)) {
102123                     createDiagnosticForReference(parentFile, index, ts.Diagnostics.Cannot_write_file_0_because_it_will_overwrite_tsbuildinfo_file_generated_by_referenced_project_1, buildInfoPath, ref.path);
102124                     hasEmitBlockingDiagnostics.set(toPath(buildInfoPath), true);
102125                 }
102126             });
102127         }
102128         function createDiagnosticForOptionPathKeyValue(key, valueIndex, message, arg0, arg1, arg2) {
102129             var needCompilerDiagnostic = true;
102130             var pathsSyntax = getOptionPathsSyntax();
102131             for (var _i = 0, pathsSyntax_1 = pathsSyntax; _i < pathsSyntax_1.length; _i++) {
102132                 var pathProp = pathsSyntax_1[_i];
102133                 if (ts.isObjectLiteralExpression(pathProp.initializer)) {
102134                     for (var _a = 0, _b = ts.getPropertyAssignment(pathProp.initializer, key); _a < _b.length; _a++) {
102135                         var keyProps = _b[_a];
102136                         var initializer = keyProps.initializer;
102137                         if (ts.isArrayLiteralExpression(initializer) && initializer.elements.length > valueIndex) {
102138                             programDiagnostics.add(ts.createDiagnosticForNodeInSourceFile(options.configFile, initializer.elements[valueIndex], message, arg0, arg1, arg2));
102139                             needCompilerDiagnostic = false;
102140                         }
102141                     }
102142                 }
102143             }
102144             if (needCompilerDiagnostic) {
102145                 programDiagnostics.add(ts.createCompilerDiagnostic(message, arg0, arg1, arg2));
102146             }
102147         }
102148         function createDiagnosticForOptionPaths(onKey, key, message, arg0) {
102149             var needCompilerDiagnostic = true;
102150             var pathsSyntax = getOptionPathsSyntax();
102151             for (var _i = 0, pathsSyntax_2 = pathsSyntax; _i < pathsSyntax_2.length; _i++) {
102152                 var pathProp = pathsSyntax_2[_i];
102153                 if (ts.isObjectLiteralExpression(pathProp.initializer) &&
102154                     createOptionDiagnosticInObjectLiteralSyntax(pathProp.initializer, onKey, key, /*key2*/ undefined, message, arg0)) {
102155                     needCompilerDiagnostic = false;
102156                 }
102157             }
102158             if (needCompilerDiagnostic) {
102159                 programDiagnostics.add(ts.createCompilerDiagnostic(message, arg0));
102160             }
102161         }
102162         function getOptionsSyntaxByName(name) {
102163             var compilerOptionsObjectLiteralSyntax = getCompilerOptionsObjectLiteralSyntax();
102164             if (compilerOptionsObjectLiteralSyntax) {
102165                 return ts.getPropertyAssignment(compilerOptionsObjectLiteralSyntax, name);
102166             }
102167             return undefined;
102168         }
102169         function getOptionPathsSyntax() {
102170             return getOptionsSyntaxByName("paths") || ts.emptyArray;
102171         }
102172         function createDiagnosticForOptionName(message, option1, option2, option3) {
102173             createDiagnosticForOption(/*onKey*/ true, option1, option2, message, option1, option2, option3);
102174         }
102175         function createOptionValueDiagnostic(option1, message, arg0) {
102176             createDiagnosticForOption(/*onKey*/ false, option1, /*option2*/ undefined, message, arg0);
102177         }
102178         function createDiagnosticForReference(sourceFile, index, message, arg0, arg1) {
102179             var referencesSyntax = ts.firstDefined(ts.getTsConfigPropArray(sourceFile || options.configFile, "references"), function (property) { return ts.isArrayLiteralExpression(property.initializer) ? property.initializer : undefined; });
102180             if (referencesSyntax && referencesSyntax.elements.length > index) {
102181                 programDiagnostics.add(ts.createDiagnosticForNodeInSourceFile(sourceFile || options.configFile, referencesSyntax.elements[index], message, arg0, arg1));
102182             }
102183             else {
102184                 programDiagnostics.add(ts.createCompilerDiagnostic(message, arg0, arg1));
102185             }
102186         }
102187         function createDiagnosticForOption(onKey, option1, option2, message, arg0, arg1, arg2) {
102188             var compilerOptionsObjectLiteralSyntax = getCompilerOptionsObjectLiteralSyntax();
102189             var needCompilerDiagnostic = !compilerOptionsObjectLiteralSyntax ||
102190                 !createOptionDiagnosticInObjectLiteralSyntax(compilerOptionsObjectLiteralSyntax, onKey, option1, option2, message, arg0, arg1, arg2);
102191             if (needCompilerDiagnostic) {
102192                 programDiagnostics.add(ts.createCompilerDiagnostic(message, arg0, arg1, arg2));
102193             }
102194         }
102195         function getCompilerOptionsObjectLiteralSyntax() {
102196             if (_compilerOptionsObjectLiteralSyntax === undefined) {
102197                 _compilerOptionsObjectLiteralSyntax = null; // eslint-disable-line no-null/no-null
102198                 var jsonObjectLiteral = ts.getTsConfigObjectLiteralExpression(options.configFile);
102199                 if (jsonObjectLiteral) {
102200                     for (var _i = 0, _a = ts.getPropertyAssignment(jsonObjectLiteral, "compilerOptions"); _i < _a.length; _i++) {
102201                         var prop = _a[_i];
102202                         if (ts.isObjectLiteralExpression(prop.initializer)) {
102203                             _compilerOptionsObjectLiteralSyntax = prop.initializer;
102204                             break;
102205                         }
102206                     }
102207                 }
102208             }
102209             return _compilerOptionsObjectLiteralSyntax;
102210         }
102211         function createOptionDiagnosticInObjectLiteralSyntax(objectLiteral, onKey, key1, key2, message, arg0, arg1, arg2) {
102212             var props = ts.getPropertyAssignment(objectLiteral, key1, key2);
102213             for (var _i = 0, props_3 = props; _i < props_3.length; _i++) {
102214                 var prop = props_3[_i];
102215                 programDiagnostics.add(ts.createDiagnosticForNodeInSourceFile(options.configFile, onKey ? prop.name : prop.initializer, message, arg0, arg1, arg2));
102216             }
102217             return !!props.length;
102218         }
102219         function blockEmittingOfFile(emitFileName, diag) {
102220             hasEmitBlockingDiagnostics.set(toPath(emitFileName), true);
102221             programDiagnostics.add(diag);
102222         }
102223         function isEmittedFile(file) {
102224             if (options.noEmit) {
102225                 return false;
102226             }
102227             // If this is source file, its not emitted file
102228             var filePath = toPath(file);
102229             if (getSourceFileByPath(filePath)) {
102230                 return false;
102231             }
102232             // If options have --outFile or --out just check that
102233             var out = options.outFile || options.out;
102234             if (out) {
102235                 return isSameFile(filePath, out) || isSameFile(filePath, ts.removeFileExtension(out) + ".d.ts" /* Dts */);
102236             }
102237             // If declarationDir is specified, return if its a file in that directory
102238             if (options.declarationDir && ts.containsPath(options.declarationDir, filePath, currentDirectory, !host.useCaseSensitiveFileNames())) {
102239                 return true;
102240             }
102241             // If --outDir, check if file is in that directory
102242             if (options.outDir) {
102243                 return ts.containsPath(options.outDir, filePath, currentDirectory, !host.useCaseSensitiveFileNames());
102244             }
102245             if (ts.fileExtensionIsOneOf(filePath, ts.supportedJSExtensions) || ts.fileExtensionIs(filePath, ".d.ts" /* Dts */)) {
102246                 // Otherwise just check if sourceFile with the name exists
102247                 var filePathWithoutExtension = ts.removeFileExtension(filePath);
102248                 return !!getSourceFileByPath((filePathWithoutExtension + ".ts" /* Ts */)) ||
102249                     !!getSourceFileByPath((filePathWithoutExtension + ".tsx" /* Tsx */));
102250             }
102251             return false;
102252         }
102253         function isSameFile(file1, file2) {
102254             return ts.comparePaths(file1, file2, currentDirectory, !host.useCaseSensitiveFileNames()) === 0 /* EqualTo */;
102255         }
102256         function getProbableSymlinks() {
102257             if (host.getSymlinks) {
102258                 return host.getSymlinks();
102259             }
102260             return symlinks || (symlinks = ts.discoverProbableSymlinks(files, getCanonicalFileName, host.getCurrentDirectory()));
102261         }
102262     }
102263     ts.createProgram = createProgram;
102264     function updateHostForUseSourceOfProjectReferenceRedirect(host) {
102265         var mapOfDeclarationDirectories;
102266         var symlinkedDirectories;
102267         var symlinkedFiles;
102268         var originalFileExists = host.compilerHost.fileExists;
102269         var originalDirectoryExists = host.compilerHost.directoryExists;
102270         var originalGetDirectories = host.compilerHost.getDirectories;
102271         var originalRealpath = host.compilerHost.realpath;
102272         if (!host.useSourceOfProjectReferenceRedirect)
102273             return { onProgramCreateComplete: ts.noop, fileExists: fileExists };
102274         host.compilerHost.fileExists = fileExists;
102275         if (originalDirectoryExists) {
102276             // This implementation of directoryExists checks if the directory being requested is
102277             // directory of .d.ts file for the referenced Project.
102278             // If it is it returns true irrespective of whether that directory exists on host
102279             host.compilerHost.directoryExists = function (path) {
102280                 if (originalDirectoryExists.call(host.compilerHost, path)) {
102281                     handleDirectoryCouldBeSymlink(path);
102282                     return true;
102283                 }
102284                 if (!host.getResolvedProjectReferences())
102285                     return false;
102286                 if (!mapOfDeclarationDirectories) {
102287                     mapOfDeclarationDirectories = ts.createMap();
102288                     host.forEachResolvedProjectReference(function (ref) {
102289                         if (!ref)
102290                             return;
102291                         var out = ref.commandLine.options.outFile || ref.commandLine.options.out;
102292                         if (out) {
102293                             mapOfDeclarationDirectories.set(ts.getDirectoryPath(host.toPath(out)), true);
102294                         }
102295                         else {
102296                             // Set declaration's in different locations only, if they are next to source the directory present doesnt change
102297                             var declarationDir = ref.commandLine.options.declarationDir || ref.commandLine.options.outDir;
102298                             if (declarationDir) {
102299                                 mapOfDeclarationDirectories.set(host.toPath(declarationDir), true);
102300                             }
102301                         }
102302                     });
102303                 }
102304                 return fileOrDirectoryExistsUsingSource(path, /*isFile*/ false);
102305             };
102306         }
102307         if (originalGetDirectories) {
102308             // Call getDirectories only if directory actually present on the host
102309             // This is needed to ensure that we arent getting directories that we fake about presence for
102310             host.compilerHost.getDirectories = function (path) {
102311                 return !host.getResolvedProjectReferences() || (originalDirectoryExists && originalDirectoryExists.call(host.compilerHost, path)) ?
102312                     originalGetDirectories.call(host.compilerHost, path) :
102313                     [];
102314             };
102315         }
102316         // This is something we keep for life time of the host
102317         if (originalRealpath) {
102318             host.compilerHost.realpath = function (s) {
102319                 return (symlinkedFiles === null || symlinkedFiles === void 0 ? void 0 : symlinkedFiles.get(host.toPath(s))) ||
102320                     originalRealpath.call(host.compilerHost, s);
102321             };
102322         }
102323         return { onProgramCreateComplete: onProgramCreateComplete, fileExists: fileExists };
102324         function onProgramCreateComplete() {
102325             host.compilerHost.fileExists = originalFileExists;
102326             host.compilerHost.directoryExists = originalDirectoryExists;
102327             host.compilerHost.getDirectories = originalGetDirectories;
102328             // DO not revert realpath as it could be used later
102329         }
102330         // This implementation of fileExists checks if the file being requested is
102331         // .d.ts file for the referenced Project.
102332         // If it is it returns true irrespective of whether that file exists on host
102333         function fileExists(file) {
102334             if (originalFileExists.call(host.compilerHost, file))
102335                 return true;
102336             if (!host.getResolvedProjectReferences())
102337                 return false;
102338             if (!ts.isDeclarationFileName(file))
102339                 return false;
102340             // Project references go to source file instead of .d.ts file
102341             return fileOrDirectoryExistsUsingSource(file, /*isFile*/ true);
102342         }
102343         function fileExistsIfProjectReferenceDts(file) {
102344             var source = host.getSourceOfProjectReferenceRedirect(file);
102345             return source !== undefined ?
102346                 ts.isString(source) ? originalFileExists.call(host.compilerHost, source) : true :
102347                 undefined;
102348         }
102349         function directoryExistsIfProjectReferenceDeclDir(dir) {
102350             var dirPath = host.toPath(dir);
102351             var dirPathWithTrailingDirectorySeparator = "" + dirPath + ts.directorySeparator;
102352             return ts.forEachKey(mapOfDeclarationDirectories, function (declDirPath) { return dirPath === declDirPath ||
102353                 // Any parent directory of declaration dir
102354                 ts.startsWith(declDirPath, dirPathWithTrailingDirectorySeparator) ||
102355                 // Any directory inside declaration dir
102356                 ts.startsWith(dirPath, declDirPath + "/"); });
102357         }
102358         function handleDirectoryCouldBeSymlink(directory) {
102359             if (!host.getResolvedProjectReferences())
102360                 return;
102361             // Because we already watch node_modules, handle symlinks in there
102362             if (!originalRealpath || !ts.stringContains(directory, ts.nodeModulesPathPart))
102363                 return;
102364             if (!symlinkedDirectories)
102365                 symlinkedDirectories = ts.createMap();
102366             var directoryPath = ts.ensureTrailingDirectorySeparator(host.toPath(directory));
102367             if (symlinkedDirectories.has(directoryPath))
102368                 return;
102369             var real = ts.normalizePath(originalRealpath.call(host.compilerHost, directory));
102370             var realPath;
102371             if (real === directory ||
102372                 (realPath = ts.ensureTrailingDirectorySeparator(host.toPath(real))) === directoryPath) {
102373                 // not symlinked
102374                 symlinkedDirectories.set(directoryPath, false);
102375                 return;
102376             }
102377             symlinkedDirectories.set(directoryPath, {
102378                 real: ts.ensureTrailingDirectorySeparator(real),
102379                 realPath: realPath
102380             });
102381         }
102382         function fileOrDirectoryExistsUsingSource(fileOrDirectory, isFile) {
102383             var fileOrDirectoryExistsUsingSource = isFile ?
102384                 function (file) { return fileExistsIfProjectReferenceDts(file); } :
102385                 function (dir) { return directoryExistsIfProjectReferenceDeclDir(dir); };
102386             // Check current directory or file
102387             var result = fileOrDirectoryExistsUsingSource(fileOrDirectory);
102388             if (result !== undefined)
102389                 return result;
102390             if (!symlinkedDirectories)
102391                 return false;
102392             var fileOrDirectoryPath = host.toPath(fileOrDirectory);
102393             if (!ts.stringContains(fileOrDirectoryPath, ts.nodeModulesPathPart))
102394                 return false;
102395             if (isFile && symlinkedFiles && symlinkedFiles.has(fileOrDirectoryPath))
102396                 return true;
102397             // If it contains node_modules check if its one of the symlinked path we know of
102398             return ts.firstDefinedIterator(symlinkedDirectories.entries(), function (_a) {
102399                 var directoryPath = _a[0], symlinkedDirectory = _a[1];
102400                 if (!symlinkedDirectory || !ts.startsWith(fileOrDirectoryPath, directoryPath))
102401                     return undefined;
102402                 var result = fileOrDirectoryExistsUsingSource(fileOrDirectoryPath.replace(directoryPath, symlinkedDirectory.realPath));
102403                 if (isFile && result) {
102404                     if (!symlinkedFiles)
102405                         symlinkedFiles = ts.createMap();
102406                     // Store the real path for the file'
102407                     var absolutePath = ts.getNormalizedAbsolutePath(fileOrDirectory, host.compilerHost.getCurrentDirectory());
102408                     symlinkedFiles.set(fileOrDirectoryPath, "" + symlinkedDirectory.real + absolutePath.replace(new RegExp(directoryPath, "i"), ""));
102409                 }
102410                 return result;
102411             }) || false;
102412         }
102413     }
102414     /*@internal*/
102415     function handleNoEmitOptions(program, sourceFile, cancellationToken) {
102416         var options = program.getCompilerOptions();
102417         if (options.noEmit) {
102418             return { diagnostics: ts.emptyArray, sourceMaps: undefined, emittedFiles: undefined, emitSkipped: true };
102419         }
102420         // If the noEmitOnError flag is set, then check if we have any errors so far.  If so,
102421         // immediately bail out.  Note that we pass 'undefined' for 'sourceFile' so that we
102422         // get any preEmit diagnostics, not just the ones
102423         if (!options.noEmitOnError)
102424             return undefined;
102425         var diagnostics = __spreadArrays(program.getOptionsDiagnostics(cancellationToken), program.getSyntacticDiagnostics(sourceFile, cancellationToken), program.getGlobalDiagnostics(cancellationToken), program.getSemanticDiagnostics(sourceFile, cancellationToken));
102426         if (diagnostics.length === 0 && ts.getEmitDeclarations(program.getCompilerOptions())) {
102427             diagnostics = program.getDeclarationDiagnostics(/*sourceFile*/ undefined, cancellationToken);
102428         }
102429         return diagnostics.length > 0 ?
102430             { diagnostics: diagnostics, sourceMaps: undefined, emittedFiles: undefined, emitSkipped: true } :
102431             undefined;
102432     }
102433     ts.handleNoEmitOptions = handleNoEmitOptions;
102434     /* @internal */
102435     function parseConfigHostFromCompilerHostLike(host, directoryStructureHost) {
102436         if (directoryStructureHost === void 0) { directoryStructureHost = host; }
102437         return {
102438             fileExists: function (f) { return directoryStructureHost.fileExists(f); },
102439             readDirectory: function (root, extensions, excludes, includes, depth) {
102440                 ts.Debug.assertIsDefined(directoryStructureHost.readDirectory, "'CompilerHost.readDirectory' must be implemented to correctly process 'projectReferences'");
102441                 return directoryStructureHost.readDirectory(root, extensions, excludes, includes, depth);
102442             },
102443             readFile: function (f) { return directoryStructureHost.readFile(f); },
102444             useCaseSensitiveFileNames: host.useCaseSensitiveFileNames(),
102445             getCurrentDirectory: function () { return host.getCurrentDirectory(); },
102446             onUnRecoverableConfigFileDiagnostic: host.onUnRecoverableConfigFileDiagnostic || ts.returnUndefined,
102447             trace: host.trace ? function (s) { return host.trace(s); } : undefined
102448         };
102449     }
102450     ts.parseConfigHostFromCompilerHostLike = parseConfigHostFromCompilerHostLike;
102451     /* @internal */
102452     function createPrependNodes(projectReferences, getCommandLine, readFile) {
102453         if (!projectReferences)
102454             return ts.emptyArray;
102455         var nodes;
102456         for (var i = 0; i < projectReferences.length; i++) {
102457             var ref = projectReferences[i];
102458             var resolvedRefOpts = getCommandLine(ref, i);
102459             if (ref.prepend && resolvedRefOpts && resolvedRefOpts.options) {
102460                 var out = resolvedRefOpts.options.outFile || resolvedRefOpts.options.out;
102461                 // Upstream project didn't have outFile set -- skip (error will have been issued earlier)
102462                 if (!out)
102463                     continue;
102464                 var _a = ts.getOutputPathsForBundle(resolvedRefOpts.options, /*forceDtsPaths*/ true), jsFilePath = _a.jsFilePath, sourceMapFilePath = _a.sourceMapFilePath, declarationFilePath = _a.declarationFilePath, declarationMapPath = _a.declarationMapPath, buildInfoPath = _a.buildInfoPath;
102465                 var node = ts.createInputFiles(readFile, jsFilePath, sourceMapFilePath, declarationFilePath, declarationMapPath, buildInfoPath);
102466                 (nodes || (nodes = [])).push(node);
102467             }
102468         }
102469         return nodes || ts.emptyArray;
102470     }
102471     ts.createPrependNodes = createPrependNodes;
102472     function resolveProjectReferencePath(hostOrRef, ref) {
102473         var passedInRef = ref ? ref : hostOrRef;
102474         return ts.resolveConfigFileProjectName(passedInRef.path);
102475     }
102476     ts.resolveProjectReferencePath = resolveProjectReferencePath;
102477     /* @internal */
102478     /**
102479      * Returns a DiagnosticMessage if we won't include a resolved module due to its extension.
102480      * The DiagnosticMessage's parameters are the imported module name, and the filename it resolved to.
102481      * This returns a diagnostic even if the module will be an untyped module.
102482      */
102483     function getResolutionDiagnostic(options, _a) {
102484         var extension = _a.extension;
102485         switch (extension) {
102486             case ".ts" /* Ts */:
102487             case ".d.ts" /* Dts */:
102488                 // These are always allowed.
102489                 return undefined;
102490             case ".tsx" /* Tsx */:
102491                 return needJsx();
102492             case ".jsx" /* Jsx */:
102493                 return needJsx() || needAllowJs();
102494             case ".js" /* Js */:
102495                 return needAllowJs();
102496             case ".json" /* Json */:
102497                 return needResolveJsonModule();
102498         }
102499         function needJsx() {
102500             return options.jsx ? undefined : ts.Diagnostics.Module_0_was_resolved_to_1_but_jsx_is_not_set;
102501         }
102502         function needAllowJs() {
102503             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;
102504         }
102505         function needResolveJsonModule() {
102506             return options.resolveJsonModule ? undefined : ts.Diagnostics.Module_0_was_resolved_to_1_but_resolveJsonModule_is_not_used;
102507         }
102508     }
102509     ts.getResolutionDiagnostic = getResolutionDiagnostic;
102510     function getModuleNames(_a) {
102511         var imports = _a.imports, moduleAugmentations = _a.moduleAugmentations;
102512         var res = imports.map(function (i) { return i.text; });
102513         for (var _i = 0, moduleAugmentations_1 = moduleAugmentations; _i < moduleAugmentations_1.length; _i++) {
102514             var aug = moduleAugmentations_1[_i];
102515             if (aug.kind === 10 /* StringLiteral */) {
102516                 res.push(aug.text);
102517             }
102518             // Do nothing if it's an Identifier; we don't need to do module resolution for `declare global`.
102519         }
102520         return res;
102521     }
102522 })(ts || (ts = {}));
102523 /*@internal*/
102524 var ts;
102525 (function (ts) {
102526     function getFileEmitOutput(program, sourceFile, emitOnlyDtsFiles, cancellationToken, customTransformers, forceDtsEmit) {
102527         var outputFiles = [];
102528         var _a = program.emit(sourceFile, writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers, forceDtsEmit), emitSkipped = _a.emitSkipped, diagnostics = _a.diagnostics, exportedModulesFromDeclarationEmit = _a.exportedModulesFromDeclarationEmit;
102529         return { outputFiles: outputFiles, emitSkipped: emitSkipped, diagnostics: diagnostics, exportedModulesFromDeclarationEmit: exportedModulesFromDeclarationEmit };
102530         function writeFile(fileName, text, writeByteOrderMark) {
102531             outputFiles.push({ name: fileName, writeByteOrderMark: writeByteOrderMark, text: text });
102532         }
102533     }
102534     ts.getFileEmitOutput = getFileEmitOutput;
102535     var BuilderState;
102536     (function (BuilderState) {
102537         /**
102538          * Get the referencedFile from the imported module symbol
102539          */
102540         function getReferencedFileFromImportedModuleSymbol(symbol) {
102541             if (symbol.declarations && symbol.declarations[0]) {
102542                 var declarationSourceFile = ts.getSourceFileOfNode(symbol.declarations[0]);
102543                 return declarationSourceFile && declarationSourceFile.resolvedPath;
102544             }
102545         }
102546         /**
102547          * Get the referencedFile from the import name node from file
102548          */
102549         function getReferencedFileFromImportLiteral(checker, importName) {
102550             var symbol = checker.getSymbolAtLocation(importName);
102551             return symbol && getReferencedFileFromImportedModuleSymbol(symbol);
102552         }
102553         /**
102554          * Gets the path to reference file from file name, it could be resolvedPath if present otherwise path
102555          */
102556         function getReferencedFileFromFileName(program, fileName, sourceFileDirectory, getCanonicalFileName) {
102557             return ts.toPath(program.getProjectReferenceRedirect(fileName) || fileName, sourceFileDirectory, getCanonicalFileName);
102558         }
102559         /**
102560          * Gets the referenced files for a file from the program with values for the keys as referenced file's path to be true
102561          */
102562         function getReferencedFiles(program, sourceFile, getCanonicalFileName) {
102563             var referencedFiles;
102564             // We need to use a set here since the code can contain the same import twice,
102565             // but that will only be one dependency.
102566             // To avoid invernal conversion, the key of the referencedFiles map must be of type Path
102567             if (sourceFile.imports && sourceFile.imports.length > 0) {
102568                 var checker = program.getTypeChecker();
102569                 for (var _i = 0, _a = sourceFile.imports; _i < _a.length; _i++) {
102570                     var importName = _a[_i];
102571                     var declarationSourceFilePath = getReferencedFileFromImportLiteral(checker, importName);
102572                     if (declarationSourceFilePath) {
102573                         addReferencedFile(declarationSourceFilePath);
102574                     }
102575                 }
102576             }
102577             var sourceFileDirectory = ts.getDirectoryPath(sourceFile.resolvedPath);
102578             // Handle triple slash references
102579             if (sourceFile.referencedFiles && sourceFile.referencedFiles.length > 0) {
102580                 for (var _b = 0, _c = sourceFile.referencedFiles; _b < _c.length; _b++) {
102581                     var referencedFile = _c[_b];
102582                     var referencedPath = getReferencedFileFromFileName(program, referencedFile.fileName, sourceFileDirectory, getCanonicalFileName);
102583                     addReferencedFile(referencedPath);
102584                 }
102585             }
102586             // Handle type reference directives
102587             if (sourceFile.resolvedTypeReferenceDirectiveNames) {
102588                 sourceFile.resolvedTypeReferenceDirectiveNames.forEach(function (resolvedTypeReferenceDirective) {
102589                     if (!resolvedTypeReferenceDirective) {
102590                         return;
102591                     }
102592                     var fileName = resolvedTypeReferenceDirective.resolvedFileName; // TODO: GH#18217
102593                     var typeFilePath = getReferencedFileFromFileName(program, fileName, sourceFileDirectory, getCanonicalFileName);
102594                     addReferencedFile(typeFilePath);
102595                 });
102596             }
102597             // Add module augmentation as references
102598             if (sourceFile.moduleAugmentations.length) {
102599                 var checker = program.getTypeChecker();
102600                 for (var _d = 0, _e = sourceFile.moduleAugmentations; _d < _e.length; _d++) {
102601                     var moduleName = _e[_d];
102602                     if (!ts.isStringLiteral(moduleName)) {
102603                         continue;
102604                     }
102605                     var symbol = checker.getSymbolAtLocation(moduleName);
102606                     if (!symbol) {
102607                         continue;
102608                     }
102609                     // Add any file other than our own as reference
102610                     addReferenceFromAmbientModule(symbol);
102611                 }
102612             }
102613             // From ambient modules
102614             for (var _f = 0, _g = program.getTypeChecker().getAmbientModules(); _f < _g.length; _f++) {
102615                 var ambientModule = _g[_f];
102616                 if (ambientModule.declarations.length > 1) {
102617                     addReferenceFromAmbientModule(ambientModule);
102618                 }
102619             }
102620             return referencedFiles;
102621             function addReferenceFromAmbientModule(symbol) {
102622                 // Add any file other than our own as reference
102623                 for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) {
102624                     var declaration = _a[_i];
102625                     var declarationSourceFile = ts.getSourceFileOfNode(declaration);
102626                     if (declarationSourceFile &&
102627                         declarationSourceFile !== sourceFile) {
102628                         addReferencedFile(declarationSourceFile.resolvedPath);
102629                     }
102630                 }
102631             }
102632             function addReferencedFile(referencedPath) {
102633                 if (!referencedFiles) {
102634                     referencedFiles = ts.createMap();
102635                 }
102636                 referencedFiles.set(referencedPath, true);
102637             }
102638         }
102639         /**
102640          * Returns true if oldState is reusable, that is the emitKind = module/non module has not changed
102641          */
102642         function canReuseOldState(newReferencedMap, oldState) {
102643             return oldState && !oldState.referencedMap === !newReferencedMap;
102644         }
102645         BuilderState.canReuseOldState = canReuseOldState;
102646         /**
102647          * Creates the state of file references and signature for the new program from oldState if it is safe
102648          */
102649         function create(newProgram, getCanonicalFileName, oldState) {
102650             var fileInfos = ts.createMap();
102651             var referencedMap = newProgram.getCompilerOptions().module !== ts.ModuleKind.None ? ts.createMap() : undefined;
102652             var exportedModulesMap = referencedMap ? ts.createMap() : undefined;
102653             var hasCalledUpdateShapeSignature = ts.createMap();
102654             var useOldState = canReuseOldState(referencedMap, oldState);
102655             // Create the reference map, and set the file infos
102656             for (var _i = 0, _a = newProgram.getSourceFiles(); _i < _a.length; _i++) {
102657                 var sourceFile = _a[_i];
102658                 var version_1 = ts.Debug.checkDefined(sourceFile.version, "Program intended to be used with Builder should have source files with versions set");
102659                 var oldInfo = useOldState ? oldState.fileInfos.get(sourceFile.resolvedPath) : undefined;
102660                 if (referencedMap) {
102661                     var newReferences = getReferencedFiles(newProgram, sourceFile, getCanonicalFileName);
102662                     if (newReferences) {
102663                         referencedMap.set(sourceFile.resolvedPath, newReferences);
102664                     }
102665                     // Copy old visible to outside files map
102666                     if (useOldState) {
102667                         var exportedModules = oldState.exportedModulesMap.get(sourceFile.resolvedPath);
102668                         if (exportedModules) {
102669                             exportedModulesMap.set(sourceFile.resolvedPath, exportedModules);
102670                         }
102671                     }
102672                 }
102673                 fileInfos.set(sourceFile.resolvedPath, { version: version_1, signature: oldInfo && oldInfo.signature, affectsGlobalScope: isFileAffectingGlobalScope(sourceFile) });
102674             }
102675             return {
102676                 fileInfos: fileInfos,
102677                 referencedMap: referencedMap,
102678                 exportedModulesMap: exportedModulesMap,
102679                 hasCalledUpdateShapeSignature: hasCalledUpdateShapeSignature
102680             };
102681         }
102682         BuilderState.create = create;
102683         /**
102684          * Releases needed properties
102685          */
102686         function releaseCache(state) {
102687             state.allFilesExcludingDefaultLibraryFile = undefined;
102688             state.allFileNames = undefined;
102689         }
102690         BuilderState.releaseCache = releaseCache;
102691         /**
102692          * Creates a clone of the state
102693          */
102694         function clone(state) {
102695             var fileInfos = ts.createMap();
102696             state.fileInfos.forEach(function (value, key) {
102697                 fileInfos.set(key, __assign({}, value));
102698             });
102699             // Dont need to backup allFiles info since its cache anyway
102700             return {
102701                 fileInfos: fileInfos,
102702                 referencedMap: cloneMapOrUndefined(state.referencedMap),
102703                 exportedModulesMap: cloneMapOrUndefined(state.exportedModulesMap),
102704                 hasCalledUpdateShapeSignature: ts.cloneMap(state.hasCalledUpdateShapeSignature),
102705             };
102706         }
102707         BuilderState.clone = clone;
102708         /**
102709          * Gets the files affected by the path from the program
102710          */
102711         function getFilesAffectedBy(state, programOfThisState, path, cancellationToken, computeHash, cacheToUpdateSignature, exportedModulesMapCache) {
102712             // Since the operation could be cancelled, the signatures are always stored in the cache
102713             // They will be committed once it is safe to use them
102714             // eg when calling this api from tsserver, if there is no cancellation of the operation
102715             // In the other cases the affected files signatures are committed only after the iteration through the result is complete
102716             var signatureCache = cacheToUpdateSignature || ts.createMap();
102717             var sourceFile = programOfThisState.getSourceFileByPath(path);
102718             if (!sourceFile) {
102719                 return ts.emptyArray;
102720             }
102721             if (!updateShapeSignature(state, programOfThisState, sourceFile, signatureCache, cancellationToken, computeHash, exportedModulesMapCache)) {
102722                 return [sourceFile];
102723             }
102724             var result = (state.referencedMap ? getFilesAffectedByUpdatedShapeWhenModuleEmit : getFilesAffectedByUpdatedShapeWhenNonModuleEmit)(state, programOfThisState, sourceFile, signatureCache, cancellationToken, computeHash, exportedModulesMapCache);
102725             if (!cacheToUpdateSignature) {
102726                 // Commit all the signatures in the signature cache
102727                 updateSignaturesFromCache(state, signatureCache);
102728             }
102729             return result;
102730         }
102731         BuilderState.getFilesAffectedBy = getFilesAffectedBy;
102732         /**
102733          * Updates the signatures from the cache into state's fileinfo signatures
102734          * This should be called whenever it is safe to commit the state of the builder
102735          */
102736         function updateSignaturesFromCache(state, signatureCache) {
102737             signatureCache.forEach(function (signature, path) { return updateSignatureOfFile(state, signature, path); });
102738         }
102739         BuilderState.updateSignaturesFromCache = updateSignaturesFromCache;
102740         function updateSignatureOfFile(state, signature, path) {
102741             state.fileInfos.get(path).signature = signature;
102742             state.hasCalledUpdateShapeSignature.set(path, true);
102743         }
102744         BuilderState.updateSignatureOfFile = updateSignatureOfFile;
102745         /**
102746          * Returns if the shape of the signature has changed since last emit
102747          */
102748         function updateShapeSignature(state, programOfThisState, sourceFile, cacheToUpdateSignature, cancellationToken, computeHash, exportedModulesMapCache) {
102749             ts.Debug.assert(!!sourceFile);
102750             ts.Debug.assert(!exportedModulesMapCache || !!state.exportedModulesMap, "Compute visible to outside map only if visibleToOutsideReferencedMap present in the state");
102751             // If we have cached the result for this file, that means hence forth we should assume file shape is uptodate
102752             if (state.hasCalledUpdateShapeSignature.has(sourceFile.resolvedPath) || cacheToUpdateSignature.has(sourceFile.resolvedPath)) {
102753                 return false;
102754             }
102755             var info = state.fileInfos.get(sourceFile.resolvedPath);
102756             if (!info)
102757                 return ts.Debug.fail();
102758             var prevSignature = info.signature;
102759             var latestSignature;
102760             if (sourceFile.isDeclarationFile) {
102761                 latestSignature = sourceFile.version;
102762                 if (exportedModulesMapCache && latestSignature !== prevSignature) {
102763                     // All the references in this file are exported
102764                     var references = state.referencedMap ? state.referencedMap.get(sourceFile.resolvedPath) : undefined;
102765                     exportedModulesMapCache.set(sourceFile.resolvedPath, references || false);
102766                 }
102767             }
102768             else {
102769                 var emitOutput_1 = getFileEmitOutput(programOfThisState, sourceFile, 
102770                 /*emitOnlyDtsFiles*/ true, cancellationToken, 
102771                 /*customTransformers*/ undefined, 
102772                 /*forceDtsEmit*/ true);
102773                 var firstDts_1 = emitOutput_1.outputFiles &&
102774                     programOfThisState.getCompilerOptions().declarationMap ?
102775                     emitOutput_1.outputFiles.length > 1 ? emitOutput_1.outputFiles[1] : undefined :
102776                     emitOutput_1.outputFiles.length > 0 ? emitOutput_1.outputFiles[0] : undefined;
102777                 if (firstDts_1) {
102778                     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; })); });
102779                     latestSignature = computeHash(firstDts_1.text);
102780                     if (exportedModulesMapCache && latestSignature !== prevSignature) {
102781                         updateExportedModules(sourceFile, emitOutput_1.exportedModulesFromDeclarationEmit, exportedModulesMapCache);
102782                     }
102783                 }
102784                 else {
102785                     latestSignature = prevSignature; // TODO: GH#18217
102786                 }
102787             }
102788             cacheToUpdateSignature.set(sourceFile.resolvedPath, latestSignature);
102789             return !prevSignature || latestSignature !== prevSignature;
102790         }
102791         BuilderState.updateShapeSignature = updateShapeSignature;
102792         /**
102793          * Coverts the declaration emit result into exported modules map
102794          */
102795         function updateExportedModules(sourceFile, exportedModulesFromDeclarationEmit, exportedModulesMapCache) {
102796             if (!exportedModulesFromDeclarationEmit) {
102797                 exportedModulesMapCache.set(sourceFile.resolvedPath, false);
102798                 return;
102799             }
102800             var exportedModules;
102801             exportedModulesFromDeclarationEmit.forEach(function (symbol) { return addExportedModule(getReferencedFileFromImportedModuleSymbol(symbol)); });
102802             exportedModulesMapCache.set(sourceFile.resolvedPath, exportedModules || false);
102803             function addExportedModule(exportedModulePath) {
102804                 if (exportedModulePath) {
102805                     if (!exportedModules) {
102806                         exportedModules = ts.createMap();
102807                     }
102808                     exportedModules.set(exportedModulePath, true);
102809                 }
102810             }
102811         }
102812         /**
102813          * Updates the exported modules from cache into state's exported modules map
102814          * This should be called whenever it is safe to commit the state of the builder
102815          */
102816         function updateExportedFilesMapFromCache(state, exportedModulesMapCache) {
102817             if (exportedModulesMapCache) {
102818                 ts.Debug.assert(!!state.exportedModulesMap);
102819                 exportedModulesMapCache.forEach(function (exportedModules, path) {
102820                     if (exportedModules) {
102821                         state.exportedModulesMap.set(path, exportedModules);
102822                     }
102823                     else {
102824                         state.exportedModulesMap.delete(path);
102825                     }
102826                 });
102827             }
102828         }
102829         BuilderState.updateExportedFilesMapFromCache = updateExportedFilesMapFromCache;
102830         /**
102831          * Get all the dependencies of the sourceFile
102832          */
102833         function getAllDependencies(state, programOfThisState, sourceFile) {
102834             var compilerOptions = programOfThisState.getCompilerOptions();
102835             // With --out or --outFile all outputs go into single file, all files depend on each other
102836             if (compilerOptions.outFile || compilerOptions.out) {
102837                 return getAllFileNames(state, programOfThisState);
102838             }
102839             // If this is non module emit, or its a global file, it depends on all the source files
102840             if (!state.referencedMap || isFileAffectingGlobalScope(sourceFile)) {
102841                 return getAllFileNames(state, programOfThisState);
102842             }
102843             // Get the references, traversing deep from the referenceMap
102844             var seenMap = ts.createMap();
102845             var queue = [sourceFile.resolvedPath];
102846             while (queue.length) {
102847                 var path = queue.pop();
102848                 if (!seenMap.has(path)) {
102849                     seenMap.set(path, true);
102850                     var references = state.referencedMap.get(path);
102851                     if (references) {
102852                         var iterator = references.keys();
102853                         for (var iterResult = iterator.next(); !iterResult.done; iterResult = iterator.next()) {
102854                             queue.push(iterResult.value);
102855                         }
102856                     }
102857                 }
102858             }
102859             return ts.arrayFrom(ts.mapDefinedIterator(seenMap.keys(), function (path) {
102860                 var file = programOfThisState.getSourceFileByPath(path);
102861                 return file ? file.fileName : path;
102862             }));
102863         }
102864         BuilderState.getAllDependencies = getAllDependencies;
102865         /**
102866          * Gets the names of all files from the program
102867          */
102868         function getAllFileNames(state, programOfThisState) {
102869             if (!state.allFileNames) {
102870                 var sourceFiles = programOfThisState.getSourceFiles();
102871                 state.allFileNames = sourceFiles === ts.emptyArray ? ts.emptyArray : sourceFiles.map(function (file) { return file.fileName; });
102872             }
102873             return state.allFileNames;
102874         }
102875         /**
102876          * Gets the files referenced by the the file path
102877          */
102878         function getReferencedByPaths(state, referencedFilePath) {
102879             return ts.arrayFrom(ts.mapDefinedIterator(state.referencedMap.entries(), function (_a) {
102880                 var filePath = _a[0], referencesInFile = _a[1];
102881                 return referencesInFile.has(referencedFilePath) ? filePath : undefined;
102882             }));
102883         }
102884         BuilderState.getReferencedByPaths = getReferencedByPaths;
102885         /**
102886          * For script files that contains only ambient external modules, although they are not actually external module files,
102887          * they can only be consumed via importing elements from them. Regular script files cannot consume them. Therefore,
102888          * there are no point to rebuild all script files if these special files have changed. However, if any statement
102889          * in the file is not ambient external module, we treat it as a regular script file.
102890          */
102891         function containsOnlyAmbientModules(sourceFile) {
102892             for (var _i = 0, _a = sourceFile.statements; _i < _a.length; _i++) {
102893                 var statement = _a[_i];
102894                 if (!ts.isModuleWithStringLiteralName(statement)) {
102895                     return false;
102896                 }
102897             }
102898             return true;
102899         }
102900         /**
102901          * Return true if file contains anything that augments to global scope we need to build them as if
102902          * they are global files as well as module
102903          */
102904         function containsGlobalScopeAugmentation(sourceFile) {
102905             return ts.some(sourceFile.moduleAugmentations, function (augmentation) { return ts.isGlobalScopeAugmentation(augmentation.parent); });
102906         }
102907         /**
102908          * Return true if the file will invalidate all files because it affectes global scope
102909          */
102910         function isFileAffectingGlobalScope(sourceFile) {
102911             return containsGlobalScopeAugmentation(sourceFile) ||
102912                 !ts.isExternalModule(sourceFile) && !containsOnlyAmbientModules(sourceFile);
102913         }
102914         /**
102915          * Gets all files of the program excluding the default library file
102916          */
102917         function getAllFilesExcludingDefaultLibraryFile(state, programOfThisState, firstSourceFile) {
102918             // Use cached result
102919             if (state.allFilesExcludingDefaultLibraryFile) {
102920                 return state.allFilesExcludingDefaultLibraryFile;
102921             }
102922             var result;
102923             if (firstSourceFile)
102924                 addSourceFile(firstSourceFile);
102925             for (var _i = 0, _a = programOfThisState.getSourceFiles(); _i < _a.length; _i++) {
102926                 var sourceFile = _a[_i];
102927                 if (sourceFile !== firstSourceFile) {
102928                     addSourceFile(sourceFile);
102929                 }
102930             }
102931             state.allFilesExcludingDefaultLibraryFile = result || ts.emptyArray;
102932             return state.allFilesExcludingDefaultLibraryFile;
102933             function addSourceFile(sourceFile) {
102934                 if (!programOfThisState.isSourceFileDefaultLibrary(sourceFile)) {
102935                     (result || (result = [])).push(sourceFile);
102936                 }
102937             }
102938         }
102939         BuilderState.getAllFilesExcludingDefaultLibraryFile = getAllFilesExcludingDefaultLibraryFile;
102940         /**
102941          * When program emits non modular code, gets the files affected by the sourceFile whose shape has changed
102942          */
102943         function getFilesAffectedByUpdatedShapeWhenNonModuleEmit(state, programOfThisState, sourceFileWithUpdatedShape) {
102944             var compilerOptions = programOfThisState.getCompilerOptions();
102945             // If `--out` or `--outFile` is specified, any new emit will result in re-emitting the entire project,
102946             // so returning the file itself is good enough.
102947             if (compilerOptions && (compilerOptions.out || compilerOptions.outFile)) {
102948                 return [sourceFileWithUpdatedShape];
102949             }
102950             return getAllFilesExcludingDefaultLibraryFile(state, programOfThisState, sourceFileWithUpdatedShape);
102951         }
102952         /**
102953          * When program emits modular code, gets the files affected by the sourceFile whose shape has changed
102954          */
102955         function getFilesAffectedByUpdatedShapeWhenModuleEmit(state, programOfThisState, sourceFileWithUpdatedShape, cacheToUpdateSignature, cancellationToken, computeHash, exportedModulesMapCache) {
102956             if (isFileAffectingGlobalScope(sourceFileWithUpdatedShape)) {
102957                 return getAllFilesExcludingDefaultLibraryFile(state, programOfThisState, sourceFileWithUpdatedShape);
102958             }
102959             var compilerOptions = programOfThisState.getCompilerOptions();
102960             if (compilerOptions && (compilerOptions.isolatedModules || compilerOptions.out || compilerOptions.outFile)) {
102961                 return [sourceFileWithUpdatedShape];
102962             }
102963             // Now we need to if each file in the referencedBy list has a shape change as well.
102964             // Because if so, its own referencedBy files need to be saved as well to make the
102965             // emitting result consistent with files on disk.
102966             var seenFileNamesMap = ts.createMap();
102967             // Start with the paths this file was referenced by
102968             seenFileNamesMap.set(sourceFileWithUpdatedShape.resolvedPath, sourceFileWithUpdatedShape);
102969             var queue = getReferencedByPaths(state, sourceFileWithUpdatedShape.resolvedPath);
102970             while (queue.length > 0) {
102971                 var currentPath = queue.pop();
102972                 if (!seenFileNamesMap.has(currentPath)) {
102973                     var currentSourceFile = programOfThisState.getSourceFileByPath(currentPath);
102974                     seenFileNamesMap.set(currentPath, currentSourceFile);
102975                     if (currentSourceFile && updateShapeSignature(state, programOfThisState, currentSourceFile, cacheToUpdateSignature, cancellationToken, computeHash, exportedModulesMapCache)) { // TODO: GH#18217
102976                         queue.push.apply(// TODO: GH#18217
102977                         queue, getReferencedByPaths(state, currentSourceFile.resolvedPath));
102978                     }
102979                 }
102980             }
102981             // Return array of values that needs emit
102982             // Return array of values that needs emit
102983             return ts.arrayFrom(ts.mapDefinedIterator(seenFileNamesMap.values(), function (value) { return value; }));
102984         }
102985     })(BuilderState = ts.BuilderState || (ts.BuilderState = {}));
102986     function cloneMapOrUndefined(map) {
102987         return map ? ts.cloneMap(map) : undefined;
102988     }
102989     ts.cloneMapOrUndefined = cloneMapOrUndefined;
102990 })(ts || (ts = {}));
102991 /*@internal*/
102992 var ts;
102993 (function (ts) {
102994     var BuilderFileEmit;
102995     (function (BuilderFileEmit) {
102996         BuilderFileEmit[BuilderFileEmit["DtsOnly"] = 0] = "DtsOnly";
102997         BuilderFileEmit[BuilderFileEmit["Full"] = 1] = "Full";
102998     })(BuilderFileEmit = ts.BuilderFileEmit || (ts.BuilderFileEmit = {}));
102999     function hasSameKeys(map1, map2) {
103000         // Has same size and every key is present in both maps
103001         return map1 === map2 || map1 !== undefined && map2 !== undefined && map1.size === map2.size && !ts.forEachKey(map1, function (key) { return !map2.has(key); });
103002     }
103003     /**
103004      * Create the state so that we can iterate on changedFiles/affected files
103005      */
103006     function createBuilderProgramState(newProgram, getCanonicalFileName, oldState) {
103007         var state = ts.BuilderState.create(newProgram, getCanonicalFileName, oldState);
103008         state.program = newProgram;
103009         var compilerOptions = newProgram.getCompilerOptions();
103010         state.compilerOptions = compilerOptions;
103011         // With --out or --outFile, any change affects all semantic diagnostics so no need to cache them
103012         if (!compilerOptions.outFile && !compilerOptions.out) {
103013             state.semanticDiagnosticsPerFile = ts.createMap();
103014         }
103015         state.changedFilesSet = ts.createMap();
103016         var useOldState = ts.BuilderState.canReuseOldState(state.referencedMap, oldState);
103017         var oldCompilerOptions = useOldState ? oldState.compilerOptions : undefined;
103018         var canCopySemanticDiagnostics = useOldState && oldState.semanticDiagnosticsPerFile && !!state.semanticDiagnosticsPerFile &&
103019             !ts.compilerOptionsAffectSemanticDiagnostics(compilerOptions, oldCompilerOptions);
103020         if (useOldState) {
103021             // Verify the sanity of old state
103022             if (!oldState.currentChangedFilePath) {
103023                 var affectedSignatures = oldState.currentAffectedFilesSignatures;
103024                 ts.Debug.assert(!oldState.affectedFiles && (!affectedSignatures || !affectedSignatures.size), "Cannot reuse if only few affected files of currentChangedFile were iterated");
103025             }
103026             var changedFilesSet = oldState.changedFilesSet;
103027             if (canCopySemanticDiagnostics) {
103028                 ts.Debug.assert(!changedFilesSet || !ts.forEachKey(changedFilesSet, function (path) { return oldState.semanticDiagnosticsPerFile.has(path); }), "Semantic diagnostics shouldnt be available for changed files");
103029             }
103030             // Copy old state's changed files set
103031             if (changedFilesSet) {
103032                 ts.copyEntries(changedFilesSet, state.changedFilesSet);
103033             }
103034             if (!compilerOptions.outFile && !compilerOptions.out && oldState.affectedFilesPendingEmit) {
103035                 state.affectedFilesPendingEmit = oldState.affectedFilesPendingEmit.slice();
103036                 state.affectedFilesPendingEmitKind = ts.cloneMapOrUndefined(oldState.affectedFilesPendingEmitKind);
103037                 state.affectedFilesPendingEmitIndex = oldState.affectedFilesPendingEmitIndex;
103038                 state.seenAffectedFiles = ts.createMap();
103039             }
103040         }
103041         // Update changed files and copy semantic diagnostics if we can
103042         var referencedMap = state.referencedMap;
103043         var oldReferencedMap = useOldState ? oldState.referencedMap : undefined;
103044         var copyDeclarationFileDiagnostics = canCopySemanticDiagnostics && !compilerOptions.skipLibCheck === !oldCompilerOptions.skipLibCheck;
103045         var copyLibFileDiagnostics = copyDeclarationFileDiagnostics && !compilerOptions.skipDefaultLibCheck === !oldCompilerOptions.skipDefaultLibCheck;
103046         state.fileInfos.forEach(function (info, sourceFilePath) {
103047             var oldInfo;
103048             var newReferences;
103049             // if not using old state, every file is changed
103050             if (!useOldState ||
103051                 // File wasnt present in old state
103052                 !(oldInfo = oldState.fileInfos.get(sourceFilePath)) ||
103053                 // versions dont match
103054                 oldInfo.version !== info.version ||
103055                 // Referenced files changed
103056                 !hasSameKeys(newReferences = referencedMap && referencedMap.get(sourceFilePath), oldReferencedMap && oldReferencedMap.get(sourceFilePath)) ||
103057                 // Referenced file was deleted in the new program
103058                 newReferences && ts.forEachKey(newReferences, function (path) { return !state.fileInfos.has(path) && oldState.fileInfos.has(path); })) {
103059                 // Register file as changed file and do not copy semantic diagnostics, since all changed files need to be re-evaluated
103060                 state.changedFilesSet.set(sourceFilePath, true);
103061             }
103062             else if (canCopySemanticDiagnostics) {
103063                 var sourceFile = newProgram.getSourceFileByPath(sourceFilePath);
103064                 if (sourceFile.isDeclarationFile && !copyDeclarationFileDiagnostics) {
103065                     return;
103066                 }
103067                 if (sourceFile.hasNoDefaultLib && !copyLibFileDiagnostics) {
103068                     return;
103069                 }
103070                 // Unchanged file copy diagnostics
103071                 var diagnostics = oldState.semanticDiagnosticsPerFile.get(sourceFilePath);
103072                 if (diagnostics) {
103073                     state.semanticDiagnosticsPerFile.set(sourceFilePath, oldState.hasReusableDiagnostic ? convertToDiagnostics(diagnostics, newProgram, getCanonicalFileName) : diagnostics);
103074                     if (!state.semanticDiagnosticsFromOldState) {
103075                         state.semanticDiagnosticsFromOldState = ts.createMap();
103076                     }
103077                     state.semanticDiagnosticsFromOldState.set(sourceFilePath, true);
103078                 }
103079             }
103080         });
103081         // If the global file is removed, add all files as changed
103082         if (useOldState && ts.forEachEntry(oldState.fileInfos, function (info, sourceFilePath) { return info.affectsGlobalScope && !state.fileInfos.has(sourceFilePath); })) {
103083             ts.BuilderState.getAllFilesExcludingDefaultLibraryFile(state, newProgram, /*firstSourceFile*/ undefined)
103084                 .forEach(function (file) { return state.changedFilesSet.set(file.resolvedPath, true); });
103085         }
103086         else if (oldCompilerOptions && ts.compilerOptionsAffectEmit(compilerOptions, oldCompilerOptions)) {
103087             // Add all files to affectedFilesPendingEmit since emit changed
103088             newProgram.getSourceFiles().forEach(function (f) { return addToAffectedFilesPendingEmit(state, f.resolvedPath, 1 /* Full */); });
103089             ts.Debug.assert(!state.seenAffectedFiles || !state.seenAffectedFiles.size);
103090             state.seenAffectedFiles = state.seenAffectedFiles || ts.createMap();
103091         }
103092         state.emittedBuildInfo = !state.changedFilesSet.size && !state.affectedFilesPendingEmit;
103093         return state;
103094     }
103095     function convertToDiagnostics(diagnostics, newProgram, getCanonicalFileName) {
103096         if (!diagnostics.length)
103097             return ts.emptyArray;
103098         var buildInfoDirectory = ts.getDirectoryPath(ts.getNormalizedAbsolutePath(ts.getTsBuildInfoEmitOutputFilePath(newProgram.getCompilerOptions()), newProgram.getCurrentDirectory()));
103099         return diagnostics.map(function (diagnostic) {
103100             var result = convertToDiagnosticRelatedInformation(diagnostic, newProgram, toPath);
103101             result.reportsUnnecessary = diagnostic.reportsUnnecessary;
103102             result.source = diagnostic.source;
103103             var relatedInformation = diagnostic.relatedInformation;
103104             result.relatedInformation = relatedInformation ?
103105                 relatedInformation.length ?
103106                     relatedInformation.map(function (r) { return convertToDiagnosticRelatedInformation(r, newProgram, toPath); }) :
103107                     ts.emptyArray :
103108                 undefined;
103109             return result;
103110         });
103111         function toPath(path) {
103112             return ts.toPath(path, buildInfoDirectory, getCanonicalFileName);
103113         }
103114     }
103115     function convertToDiagnosticRelatedInformation(diagnostic, newProgram, toPath) {
103116         var file = diagnostic.file;
103117         return __assign(__assign({}, diagnostic), { file: file ? newProgram.getSourceFileByPath(toPath(file)) : undefined });
103118     }
103119     /**
103120      * Releases program and other related not needed properties
103121      */
103122     function releaseCache(state) {
103123         ts.BuilderState.releaseCache(state);
103124         state.program = undefined;
103125     }
103126     /**
103127      * Creates a clone of the state
103128      */
103129     function cloneBuilderProgramState(state) {
103130         var newState = ts.BuilderState.clone(state);
103131         newState.semanticDiagnosticsPerFile = ts.cloneMapOrUndefined(state.semanticDiagnosticsPerFile);
103132         newState.changedFilesSet = ts.cloneMap(state.changedFilesSet);
103133         newState.affectedFiles = state.affectedFiles;
103134         newState.affectedFilesIndex = state.affectedFilesIndex;
103135         newState.currentChangedFilePath = state.currentChangedFilePath;
103136         newState.currentAffectedFilesSignatures = ts.cloneMapOrUndefined(state.currentAffectedFilesSignatures);
103137         newState.currentAffectedFilesExportedModulesMap = ts.cloneMapOrUndefined(state.currentAffectedFilesExportedModulesMap);
103138         newState.seenAffectedFiles = ts.cloneMapOrUndefined(state.seenAffectedFiles);
103139         newState.cleanedDiagnosticsOfLibFiles = state.cleanedDiagnosticsOfLibFiles;
103140         newState.semanticDiagnosticsFromOldState = ts.cloneMapOrUndefined(state.semanticDiagnosticsFromOldState);
103141         newState.program = state.program;
103142         newState.compilerOptions = state.compilerOptions;
103143         newState.affectedFilesPendingEmit = state.affectedFilesPendingEmit && state.affectedFilesPendingEmit.slice();
103144         newState.affectedFilesPendingEmitKind = ts.cloneMapOrUndefined(state.affectedFilesPendingEmitKind);
103145         newState.affectedFilesPendingEmitIndex = state.affectedFilesPendingEmitIndex;
103146         newState.seenEmittedFiles = ts.cloneMapOrUndefined(state.seenEmittedFiles);
103147         newState.programEmitComplete = state.programEmitComplete;
103148         return newState;
103149     }
103150     /**
103151      * Verifies that source file is ok to be used in calls that arent handled by next
103152      */
103153     function assertSourceFileOkWithoutNextAffectedCall(state, sourceFile) {
103154         ts.Debug.assert(!sourceFile || !state.affectedFiles || state.affectedFiles[state.affectedFilesIndex - 1] !== sourceFile || !state.semanticDiagnosticsPerFile.has(sourceFile.resolvedPath));
103155     }
103156     /**
103157      * This function returns the next affected file to be processed.
103158      * Note that until doneAffected is called it would keep reporting same result
103159      * This is to allow the callers to be able to actually remove affected file only when the operation is complete
103160      * eg. if during diagnostics check cancellation token ends up cancelling the request, the affected file should be retained
103161      */
103162     function getNextAffectedFile(state, cancellationToken, computeHash) {
103163         while (true) {
103164             var affectedFiles = state.affectedFiles;
103165             if (affectedFiles) {
103166                 var seenAffectedFiles = state.seenAffectedFiles;
103167                 var affectedFilesIndex = state.affectedFilesIndex; // TODO: GH#18217
103168                 while (affectedFilesIndex < affectedFiles.length) {
103169                     var affectedFile = affectedFiles[affectedFilesIndex];
103170                     if (!seenAffectedFiles.has(affectedFile.resolvedPath)) {
103171                         // Set the next affected file as seen and remove the cached semantic diagnostics
103172                         state.affectedFilesIndex = affectedFilesIndex;
103173                         handleDtsMayChangeOfAffectedFile(state, affectedFile, cancellationToken, computeHash);
103174                         return affectedFile;
103175                     }
103176                     affectedFilesIndex++;
103177                 }
103178                 // Remove the changed file from the change set
103179                 state.changedFilesSet.delete(state.currentChangedFilePath);
103180                 state.currentChangedFilePath = undefined;
103181                 // Commit the changes in file signature
103182                 ts.BuilderState.updateSignaturesFromCache(state, state.currentAffectedFilesSignatures);
103183                 state.currentAffectedFilesSignatures.clear();
103184                 ts.BuilderState.updateExportedFilesMapFromCache(state, state.currentAffectedFilesExportedModulesMap);
103185                 state.affectedFiles = undefined;
103186             }
103187             // Get next changed file
103188             var nextKey = state.changedFilesSet.keys().next();
103189             if (nextKey.done) {
103190                 // Done
103191                 return undefined;
103192             }
103193             // With --out or --outFile all outputs go into single file
103194             // so operations are performed directly on program, return program
103195             var program = ts.Debug.checkDefined(state.program);
103196             var compilerOptions = program.getCompilerOptions();
103197             if (compilerOptions.outFile || compilerOptions.out) {
103198                 ts.Debug.assert(!state.semanticDiagnosticsPerFile);
103199                 return program;
103200             }
103201             // Get next batch of affected files
103202             state.currentAffectedFilesSignatures = state.currentAffectedFilesSignatures || ts.createMap();
103203             if (state.exportedModulesMap) {
103204                 state.currentAffectedFilesExportedModulesMap = state.currentAffectedFilesExportedModulesMap || ts.createMap();
103205             }
103206             state.affectedFiles = ts.BuilderState.getFilesAffectedBy(state, program, nextKey.value, cancellationToken, computeHash, state.currentAffectedFilesSignatures, state.currentAffectedFilesExportedModulesMap);
103207             state.currentChangedFilePath = nextKey.value;
103208             state.affectedFilesIndex = 0;
103209             state.seenAffectedFiles = state.seenAffectedFiles || ts.createMap();
103210         }
103211     }
103212     /**
103213      * Returns next file to be emitted from files that retrieved semantic diagnostics but did not emit yet
103214      */
103215     function getNextAffectedFilePendingEmit(state) {
103216         var affectedFilesPendingEmit = state.affectedFilesPendingEmit;
103217         if (affectedFilesPendingEmit) {
103218             var seenEmittedFiles = state.seenEmittedFiles || (state.seenEmittedFiles = ts.createMap());
103219             for (var i = state.affectedFilesPendingEmitIndex; i < affectedFilesPendingEmit.length; i++) {
103220                 var affectedFile = ts.Debug.checkDefined(state.program).getSourceFileByPath(affectedFilesPendingEmit[i]);
103221                 if (affectedFile) {
103222                     var seenKind = seenEmittedFiles.get(affectedFile.resolvedPath);
103223                     var emitKind = ts.Debug.checkDefined(ts.Debug.checkDefined(state.affectedFilesPendingEmitKind).get(affectedFile.resolvedPath));
103224                     if (seenKind === undefined || seenKind < emitKind) {
103225                         // emit this file
103226                         state.affectedFilesPendingEmitIndex = i;
103227                         return { affectedFile: affectedFile, emitKind: emitKind };
103228                     }
103229                 }
103230             }
103231             state.affectedFilesPendingEmit = undefined;
103232             state.affectedFilesPendingEmitKind = undefined;
103233             state.affectedFilesPendingEmitIndex = undefined;
103234         }
103235         return undefined;
103236     }
103237     /**
103238      *  Handles semantic diagnostics and dts emit for affectedFile and files, that are referencing modules that export entities from affected file
103239      *  This is because even though js emit doesnt change, dts emit / type used can change resulting in need for dts emit and js change
103240      */
103241     function handleDtsMayChangeOfAffectedFile(state, affectedFile, cancellationToken, computeHash) {
103242         removeSemanticDiagnosticsOf(state, affectedFile.resolvedPath);
103243         // If affected files is everything except default library, then nothing more to do
103244         if (state.allFilesExcludingDefaultLibraryFile === state.affectedFiles) {
103245             if (!state.cleanedDiagnosticsOfLibFiles) {
103246                 state.cleanedDiagnosticsOfLibFiles = true;
103247                 var program_1 = ts.Debug.checkDefined(state.program);
103248                 var options_2 = program_1.getCompilerOptions();
103249                 ts.forEach(program_1.getSourceFiles(), function (f) {
103250                     return program_1.isSourceFileDefaultLibrary(f) &&
103251                         !ts.skipTypeChecking(f, options_2, program_1) &&
103252                         removeSemanticDiagnosticsOf(state, f.resolvedPath);
103253                 });
103254             }
103255             return;
103256         }
103257         if (!state.compilerOptions.assumeChangesOnlyAffectDirectDependencies) {
103258             forEachReferencingModulesOfExportOfAffectedFile(state, affectedFile, function (state, path) { return handleDtsMayChangeOf(state, path, cancellationToken, computeHash); });
103259         }
103260     }
103261     /**
103262      * Handle the dts may change, so they need to be added to pending emit if dts emit is enabled,
103263      * Also we need to make sure signature is updated for these files
103264      */
103265     function handleDtsMayChangeOf(state, path, cancellationToken, computeHash) {
103266         removeSemanticDiagnosticsOf(state, path);
103267         if (!state.changedFilesSet.has(path)) {
103268             var program = ts.Debug.checkDefined(state.program);
103269             var sourceFile = program.getSourceFileByPath(path);
103270             if (sourceFile) {
103271                 // Even though the js emit doesnt change and we are already handling dts emit and semantic diagnostics
103272                 // we need to update the signature to reflect correctness of the signature(which is output d.ts emit) of this file
103273                 // This ensures that we dont later during incremental builds considering wrong signature.
103274                 // Eg where this also is needed to ensure that .tsbuildinfo generated by incremental build should be same as if it was first fresh build
103275                 ts.BuilderState.updateShapeSignature(state, program, sourceFile, ts.Debug.checkDefined(state.currentAffectedFilesSignatures), cancellationToken, computeHash, state.currentAffectedFilesExportedModulesMap);
103276                 // If not dts emit, nothing more to do
103277                 if (ts.getEmitDeclarations(state.compilerOptions)) {
103278                     addToAffectedFilesPendingEmit(state, path, 0 /* DtsOnly */);
103279                 }
103280             }
103281         }
103282         return false;
103283     }
103284     /**
103285      * Removes semantic diagnostics for path and
103286      * returns true if there are no more semantic diagnostics from the old state
103287      */
103288     function removeSemanticDiagnosticsOf(state, path) {
103289         if (!state.semanticDiagnosticsFromOldState) {
103290             return true;
103291         }
103292         state.semanticDiagnosticsFromOldState.delete(path);
103293         state.semanticDiagnosticsPerFile.delete(path);
103294         return !state.semanticDiagnosticsFromOldState.size;
103295     }
103296     function isChangedSignagure(state, path) {
103297         var newSignature = ts.Debug.checkDefined(state.currentAffectedFilesSignatures).get(path);
103298         var oldSignagure = ts.Debug.checkDefined(state.fileInfos.get(path)).signature;
103299         return newSignature !== oldSignagure;
103300     }
103301     /**
103302      * Iterate on referencing modules that export entities from affected file
103303      */
103304     function forEachReferencingModulesOfExportOfAffectedFile(state, affectedFile, fn) {
103305         // If there was change in signature (dts output) for the changed file,
103306         // then only we need to handle pending file emit
103307         if (!state.exportedModulesMap || !state.changedFilesSet.has(affectedFile.resolvedPath)) {
103308             return;
103309         }
103310         if (!isChangedSignagure(state, affectedFile.resolvedPath))
103311             return;
103312         // Since isolated modules dont change js files, files affected by change in signature is itself
103313         // But we need to cleanup semantic diagnostics and queue dts emit for affected files
103314         if (state.compilerOptions.isolatedModules) {
103315             var seenFileNamesMap = ts.createMap();
103316             seenFileNamesMap.set(affectedFile.resolvedPath, true);
103317             var queue = ts.BuilderState.getReferencedByPaths(state, affectedFile.resolvedPath);
103318             while (queue.length > 0) {
103319                 var currentPath = queue.pop();
103320                 if (!seenFileNamesMap.has(currentPath)) {
103321                     seenFileNamesMap.set(currentPath, true);
103322                     var result = fn(state, currentPath);
103323                     if (result && isChangedSignagure(state, currentPath)) {
103324                         var currentSourceFile = ts.Debug.checkDefined(state.program).getSourceFileByPath(currentPath);
103325                         queue.push.apply(queue, ts.BuilderState.getReferencedByPaths(state, currentSourceFile.resolvedPath));
103326                     }
103327                 }
103328             }
103329         }
103330         ts.Debug.assert(!!state.currentAffectedFilesExportedModulesMap);
103331         var seenFileAndExportsOfFile = ts.createMap();
103332         // Go through exported modules from cache first
103333         // If exported modules has path, all files referencing file exported from are affected
103334         if (ts.forEachEntry(state.currentAffectedFilesExportedModulesMap, function (exportedModules, exportedFromPath) {
103335             return exportedModules &&
103336                 exportedModules.has(affectedFile.resolvedPath) &&
103337                 forEachFilesReferencingPath(state, exportedFromPath, seenFileAndExportsOfFile, fn);
103338         })) {
103339             return;
103340         }
103341         // If exported from path is not from cache and exported modules has path, all files referencing file exported from are affected
103342         ts.forEachEntry(state.exportedModulesMap, function (exportedModules, exportedFromPath) {
103343             return !state.currentAffectedFilesExportedModulesMap.has(exportedFromPath) && // If we already iterated this through cache, ignore it
103344                 exportedModules.has(affectedFile.resolvedPath) &&
103345                 forEachFilesReferencingPath(state, exportedFromPath, seenFileAndExportsOfFile, fn);
103346         });
103347     }
103348     /**
103349      * Iterate on files referencing referencedPath
103350      */
103351     function forEachFilesReferencingPath(state, referencedPath, seenFileAndExportsOfFile, fn) {
103352         return ts.forEachEntry(state.referencedMap, function (referencesInFile, filePath) {
103353             return referencesInFile.has(referencedPath) && forEachFileAndExportsOfFile(state, filePath, seenFileAndExportsOfFile, fn);
103354         });
103355     }
103356     /**
103357      * fn on file and iterate on anything that exports this file
103358      */
103359     function forEachFileAndExportsOfFile(state, filePath, seenFileAndExportsOfFile, fn) {
103360         if (!ts.addToSeen(seenFileAndExportsOfFile, filePath)) {
103361             return false;
103362         }
103363         if (fn(state, filePath)) {
103364             // If there are no more diagnostics from old cache, done
103365             return true;
103366         }
103367         ts.Debug.assert(!!state.currentAffectedFilesExportedModulesMap);
103368         // Go through exported modules from cache first
103369         // If exported modules has path, all files referencing file exported from are affected
103370         if (ts.forEachEntry(state.currentAffectedFilesExportedModulesMap, function (exportedModules, exportedFromPath) {
103371             return exportedModules &&
103372                 exportedModules.has(filePath) &&
103373                 forEachFileAndExportsOfFile(state, exportedFromPath, seenFileAndExportsOfFile, fn);
103374         })) {
103375             return true;
103376         }
103377         // If exported from path is not from cache and exported modules has path, all files referencing file exported from are affected
103378         if (ts.forEachEntry(state.exportedModulesMap, function (exportedModules, exportedFromPath) {
103379             return !state.currentAffectedFilesExportedModulesMap.has(exportedFromPath) && // If we already iterated this through cache, ignore it
103380                 exportedModules.has(filePath) &&
103381                 forEachFileAndExportsOfFile(state, exportedFromPath, seenFileAndExportsOfFile, fn);
103382         })) {
103383             return true;
103384         }
103385         // Remove diagnostics of files that import this file (without going to exports of referencing files)
103386         return !!ts.forEachEntry(state.referencedMap, function (referencesInFile, referencingFilePath) {
103387             return referencesInFile.has(filePath) &&
103388                 !seenFileAndExportsOfFile.has(referencingFilePath) && // Not already removed diagnostic file
103389                 fn(state, referencingFilePath);
103390         } // Dont add to seen since this is not yet done with the export removal
103391         );
103392     }
103393     /**
103394      * This is called after completing operation on the next affected file.
103395      * The operations here are postponed to ensure that cancellation during the iteration is handled correctly
103396      */
103397     function doneWithAffectedFile(state, affected, emitKind, isPendingEmit, isBuildInfoEmit) {
103398         if (isBuildInfoEmit) {
103399             state.emittedBuildInfo = true;
103400         }
103401         else if (affected === state.program) {
103402             state.changedFilesSet.clear();
103403             state.programEmitComplete = true;
103404         }
103405         else {
103406             state.seenAffectedFiles.set(affected.resolvedPath, true);
103407             if (emitKind !== undefined) {
103408                 (state.seenEmittedFiles || (state.seenEmittedFiles = ts.createMap())).set(affected.resolvedPath, emitKind);
103409             }
103410             if (isPendingEmit) {
103411                 state.affectedFilesPendingEmitIndex++;
103412             }
103413             else {
103414                 state.affectedFilesIndex++;
103415             }
103416         }
103417     }
103418     /**
103419      * Returns the result with affected file
103420      */
103421     function toAffectedFileResult(state, result, affected) {
103422         doneWithAffectedFile(state, affected);
103423         return { result: result, affected: affected };
103424     }
103425     /**
103426      * Returns the result with affected file
103427      */
103428     function toAffectedFileEmitResult(state, result, affected, emitKind, isPendingEmit, isBuildInfoEmit) {
103429         doneWithAffectedFile(state, affected, emitKind, isPendingEmit, isBuildInfoEmit);
103430         return { result: result, affected: affected };
103431     }
103432     /**
103433      * Gets semantic diagnostics for the file which are
103434      * bindAndCheckDiagnostics (from cache) and program diagnostics
103435      */
103436     function getSemanticDiagnosticsOfFile(state, sourceFile, cancellationToken) {
103437         return ts.concatenate(getBinderAndCheckerDiagnosticsOfFile(state, sourceFile, cancellationToken), ts.Debug.checkDefined(state.program).getProgramDiagnostics(sourceFile));
103438     }
103439     /**
103440      * Gets the binder and checker diagnostics either from cache if present, or otherwise from program and caches it
103441      * 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
103442      */
103443     function getBinderAndCheckerDiagnosticsOfFile(state, sourceFile, cancellationToken) {
103444         var path = sourceFile.resolvedPath;
103445         if (state.semanticDiagnosticsPerFile) {
103446             var cachedDiagnostics = state.semanticDiagnosticsPerFile.get(path);
103447             // Report the bind and check diagnostics from the cache if we already have those diagnostics present
103448             if (cachedDiagnostics) {
103449                 return cachedDiagnostics;
103450             }
103451         }
103452         // Diagnostics werent cached, get them from program, and cache the result
103453         var diagnostics = ts.Debug.checkDefined(state.program).getBindAndCheckDiagnostics(sourceFile, cancellationToken);
103454         if (state.semanticDiagnosticsPerFile) {
103455             state.semanticDiagnosticsPerFile.set(path, diagnostics);
103456         }
103457         return diagnostics;
103458     }
103459     /**
103460      * Gets the program information to be emitted in buildInfo so that we can use it to create new program
103461      */
103462     function getProgramBuildInfo(state, getCanonicalFileName) {
103463         if (state.compilerOptions.outFile || state.compilerOptions.out)
103464             return undefined;
103465         var currentDirectory = ts.Debug.checkDefined(state.program).getCurrentDirectory();
103466         var buildInfoDirectory = ts.getDirectoryPath(ts.getNormalizedAbsolutePath(ts.getTsBuildInfoEmitOutputFilePath(state.compilerOptions), currentDirectory));
103467         var fileInfos = {};
103468         state.fileInfos.forEach(function (value, key) {
103469             var signature = state.currentAffectedFilesSignatures && state.currentAffectedFilesSignatures.get(key);
103470             fileInfos[relativeToBuildInfo(key)] = signature === undefined ? value : { version: value.version, signature: signature, affectsGlobalScope: value.affectsGlobalScope };
103471         });
103472         var result = {
103473             fileInfos: fileInfos,
103474             options: convertToReusableCompilerOptions(state.compilerOptions, relativeToBuildInfoEnsuringAbsolutePath)
103475         };
103476         if (state.referencedMap) {
103477             var referencedMap = {};
103478             for (var _i = 0, _a = ts.arrayFrom(state.referencedMap.keys()).sort(ts.compareStringsCaseSensitive); _i < _a.length; _i++) {
103479                 var key = _a[_i];
103480                 referencedMap[relativeToBuildInfo(key)] = ts.arrayFrom(state.referencedMap.get(key).keys(), relativeToBuildInfo).sort(ts.compareStringsCaseSensitive);
103481             }
103482             result.referencedMap = referencedMap;
103483         }
103484         if (state.exportedModulesMap) {
103485             var exportedModulesMap = {};
103486             for (var _b = 0, _c = ts.arrayFrom(state.exportedModulesMap.keys()).sort(ts.compareStringsCaseSensitive); _b < _c.length; _b++) {
103487                 var key = _c[_b];
103488                 var newValue = state.currentAffectedFilesExportedModulesMap && state.currentAffectedFilesExportedModulesMap.get(key);
103489                 // Not in temporary cache, use existing value
103490                 if (newValue === undefined)
103491                     exportedModulesMap[relativeToBuildInfo(key)] = ts.arrayFrom(state.exportedModulesMap.get(key).keys(), relativeToBuildInfo).sort(ts.compareStringsCaseSensitive);
103492                 // Value in cache and has updated value map, use that
103493                 else if (newValue)
103494                     exportedModulesMap[relativeToBuildInfo(key)] = ts.arrayFrom(newValue.keys(), relativeToBuildInfo).sort(ts.compareStringsCaseSensitive);
103495             }
103496             result.exportedModulesMap = exportedModulesMap;
103497         }
103498         if (state.semanticDiagnosticsPerFile) {
103499             var semanticDiagnosticsPerFile = [];
103500             for (var _d = 0, _e = ts.arrayFrom(state.semanticDiagnosticsPerFile.keys()).sort(ts.compareStringsCaseSensitive); _d < _e.length; _d++) {
103501                 var key = _e[_d];
103502                 var value = state.semanticDiagnosticsPerFile.get(key);
103503                 semanticDiagnosticsPerFile.push(value.length ?
103504                     [
103505                         relativeToBuildInfo(key),
103506                         state.hasReusableDiagnostic ?
103507                             value :
103508                             convertToReusableDiagnostics(value, relativeToBuildInfo)
103509                     ] :
103510                     relativeToBuildInfo(key));
103511             }
103512             result.semanticDiagnosticsPerFile = semanticDiagnosticsPerFile;
103513         }
103514         return result;
103515         function relativeToBuildInfoEnsuringAbsolutePath(path) {
103516             return relativeToBuildInfo(ts.getNormalizedAbsolutePath(path, currentDirectory));
103517         }
103518         function relativeToBuildInfo(path) {
103519             return ts.ensurePathIsNonModuleName(ts.getRelativePathFromDirectory(buildInfoDirectory, path, getCanonicalFileName));
103520         }
103521     }
103522     function convertToReusableCompilerOptions(options, relativeToBuildInfo) {
103523         var result = {};
103524         var optionsNameMap = ts.getOptionsNameMap().optionsNameMap;
103525         for (var name in options) {
103526             if (ts.hasProperty(options, name)) {
103527                 result[name] = convertToReusableCompilerOptionValue(optionsNameMap.get(name.toLowerCase()), options[name], relativeToBuildInfo);
103528             }
103529         }
103530         if (result.configFilePath) {
103531             result.configFilePath = relativeToBuildInfo(result.configFilePath);
103532         }
103533         return result;
103534     }
103535     function convertToReusableCompilerOptionValue(option, value, relativeToBuildInfo) {
103536         if (option) {
103537             if (option.type === "list") {
103538                 var values = value;
103539                 if (option.element.isFilePath && values.length) {
103540                     return values.map(relativeToBuildInfo);
103541                 }
103542             }
103543             else if (option.isFilePath) {
103544                 return relativeToBuildInfo(value);
103545             }
103546         }
103547         return value;
103548     }
103549     function convertToReusableDiagnostics(diagnostics, relativeToBuildInfo) {
103550         ts.Debug.assert(!!diagnostics.length);
103551         return diagnostics.map(function (diagnostic) {
103552             var result = convertToReusableDiagnosticRelatedInformation(diagnostic, relativeToBuildInfo);
103553             result.reportsUnnecessary = diagnostic.reportsUnnecessary;
103554             result.source = diagnostic.source;
103555             var relatedInformation = diagnostic.relatedInformation;
103556             result.relatedInformation = relatedInformation ?
103557                 relatedInformation.length ?
103558                     relatedInformation.map(function (r) { return convertToReusableDiagnosticRelatedInformation(r, relativeToBuildInfo); }) :
103559                     ts.emptyArray :
103560                 undefined;
103561             return result;
103562         });
103563     }
103564     function convertToReusableDiagnosticRelatedInformation(diagnostic, relativeToBuildInfo) {
103565         var file = diagnostic.file;
103566         return __assign(__assign({}, diagnostic), { file: file ? relativeToBuildInfo(file.resolvedPath) : undefined });
103567     }
103568     var BuilderProgramKind;
103569     (function (BuilderProgramKind) {
103570         BuilderProgramKind[BuilderProgramKind["SemanticDiagnosticsBuilderProgram"] = 0] = "SemanticDiagnosticsBuilderProgram";
103571         BuilderProgramKind[BuilderProgramKind["EmitAndSemanticDiagnosticsBuilderProgram"] = 1] = "EmitAndSemanticDiagnosticsBuilderProgram";
103572     })(BuilderProgramKind = ts.BuilderProgramKind || (ts.BuilderProgramKind = {}));
103573     function getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences) {
103574         var host;
103575         var newProgram;
103576         var oldProgram;
103577         if (newProgramOrRootNames === undefined) {
103578             ts.Debug.assert(hostOrOptions === undefined);
103579             host = oldProgramOrHost;
103580             oldProgram = configFileParsingDiagnosticsOrOldProgram;
103581             ts.Debug.assert(!!oldProgram);
103582             newProgram = oldProgram.getProgram();
103583         }
103584         else if (ts.isArray(newProgramOrRootNames)) {
103585             oldProgram = configFileParsingDiagnosticsOrOldProgram;
103586             newProgram = ts.createProgram({
103587                 rootNames: newProgramOrRootNames,
103588                 options: hostOrOptions,
103589                 host: oldProgramOrHost,
103590                 oldProgram: oldProgram && oldProgram.getProgramOrUndefined(),
103591                 configFileParsingDiagnostics: configFileParsingDiagnostics,
103592                 projectReferences: projectReferences
103593             });
103594             host = oldProgramOrHost;
103595         }
103596         else {
103597             newProgram = newProgramOrRootNames;
103598             host = hostOrOptions;
103599             oldProgram = oldProgramOrHost;
103600             configFileParsingDiagnostics = configFileParsingDiagnosticsOrOldProgram;
103601         }
103602         return { host: host, newProgram: newProgram, oldProgram: oldProgram, configFileParsingDiagnostics: configFileParsingDiagnostics || ts.emptyArray };
103603     }
103604     ts.getBuilderCreationParameters = getBuilderCreationParameters;
103605     function createBuilderProgram(kind, _a) {
103606         var newProgram = _a.newProgram, host = _a.host, oldProgram = _a.oldProgram, configFileParsingDiagnostics = _a.configFileParsingDiagnostics;
103607         // Return same program if underlying program doesnt change
103608         var oldState = oldProgram && oldProgram.getState();
103609         if (oldState && newProgram === oldState.program && configFileParsingDiagnostics === newProgram.getConfigFileParsingDiagnostics()) {
103610             newProgram = undefined; // TODO: GH#18217
103611             oldState = undefined;
103612             return oldProgram;
103613         }
103614         /**
103615          * Create the canonical file name for identity
103616          */
103617         var getCanonicalFileName = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames());
103618         /**
103619          * Computing hash to for signature verification
103620          */
103621         var computeHash = host.createHash || ts.generateDjb2Hash;
103622         var state = createBuilderProgramState(newProgram, getCanonicalFileName, oldState);
103623         var backupState;
103624         newProgram.getProgramBuildInfo = function () { return getProgramBuildInfo(state, getCanonicalFileName); };
103625         // To ensure that we arent storing any references to old program or new program without state
103626         newProgram = undefined; // TODO: GH#18217
103627         oldProgram = undefined;
103628         oldState = undefined;
103629         var builderProgram = createRedirectedBuilderProgram(state, configFileParsingDiagnostics);
103630         builderProgram.getState = function () { return state; };
103631         builderProgram.backupState = function () {
103632             ts.Debug.assert(backupState === undefined);
103633             backupState = cloneBuilderProgramState(state);
103634         };
103635         builderProgram.restoreState = function () {
103636             state = ts.Debug.checkDefined(backupState);
103637             backupState = undefined;
103638         };
103639         builderProgram.getAllDependencies = function (sourceFile) { return ts.BuilderState.getAllDependencies(state, ts.Debug.checkDefined(state.program), sourceFile); };
103640         builderProgram.getSemanticDiagnostics = getSemanticDiagnostics;
103641         builderProgram.emit = emit;
103642         builderProgram.releaseProgram = function () {
103643             releaseCache(state);
103644             backupState = undefined;
103645         };
103646         if (kind === BuilderProgramKind.SemanticDiagnosticsBuilderProgram) {
103647             builderProgram.getSemanticDiagnosticsOfNextAffectedFile = getSemanticDiagnosticsOfNextAffectedFile;
103648         }
103649         else if (kind === BuilderProgramKind.EmitAndSemanticDiagnosticsBuilderProgram) {
103650             builderProgram.getSemanticDiagnosticsOfNextAffectedFile = getSemanticDiagnosticsOfNextAffectedFile;
103651             builderProgram.emitNextAffectedFile = emitNextAffectedFile;
103652         }
103653         else {
103654             ts.notImplemented();
103655         }
103656         return builderProgram;
103657         /**
103658          * Emits the next affected file's emit result (EmitResult and sourceFiles emitted) or returns undefined if iteration is complete
103659          * The first of writeFile if provided, writeFile of BuilderProgramHost if provided, writeFile of compiler host
103660          * in that order would be used to write the files
103661          */
103662         function emitNextAffectedFile(writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers) {
103663             var affected = getNextAffectedFile(state, cancellationToken, computeHash);
103664             var emitKind = 1 /* Full */;
103665             var isPendingEmitFile = false;
103666             if (!affected) {
103667                 if (!state.compilerOptions.out && !state.compilerOptions.outFile) {
103668                     var pendingAffectedFile = getNextAffectedFilePendingEmit(state);
103669                     if (!pendingAffectedFile) {
103670                         if (state.emittedBuildInfo) {
103671                             return undefined;
103672                         }
103673                         var affected_1 = ts.Debug.checkDefined(state.program);
103674                         return toAffectedFileEmitResult(state, 
103675                         // When whole program is affected, do emit only once (eg when --out or --outFile is specified)
103676                         // Otherwise just affected file
103677                         affected_1.emitBuildInfo(writeFile || ts.maybeBind(host, host.writeFile), cancellationToken), affected_1, 1 /* Full */, 
103678                         /*isPendingEmitFile*/ false, 
103679                         /*isBuildInfoEmit*/ true);
103680                     }
103681                     (affected = pendingAffectedFile.affectedFile, emitKind = pendingAffectedFile.emitKind);
103682                     isPendingEmitFile = true;
103683                 }
103684                 else {
103685                     var program = ts.Debug.checkDefined(state.program);
103686                     if (state.programEmitComplete)
103687                         return undefined;
103688                     affected = program;
103689                 }
103690             }
103691             return toAffectedFileEmitResult(state, 
103692             // When whole program is affected, do emit only once (eg when --out or --outFile is specified)
103693             // Otherwise just affected file
103694             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);
103695         }
103696         /**
103697          * Emits the JavaScript and declaration files.
103698          * When targetSource file is specified, emits the files corresponding to that source file,
103699          * otherwise for the whole program.
103700          * In case of EmitAndSemanticDiagnosticsBuilderProgram, when targetSourceFile is specified,
103701          * it is assumed that that file is handled from affected file list. If targetSourceFile is not specified,
103702          * it will only emit all the affected files instead of whole program
103703          *
103704          * The first of writeFile if provided, writeFile of BuilderProgramHost if provided, writeFile of compiler host
103705          * in that order would be used to write the files
103706          */
103707         function emit(targetSourceFile, writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers) {
103708             if (kind === BuilderProgramKind.EmitAndSemanticDiagnosticsBuilderProgram) {
103709                 assertSourceFileOkWithoutNextAffectedCall(state, targetSourceFile);
103710                 var result = ts.handleNoEmitOptions(builderProgram, targetSourceFile, cancellationToken);
103711                 if (result)
103712                     return result;
103713                 if (!targetSourceFile) {
103714                     // Emit and report any errors we ran into.
103715                     var sourceMaps = [];
103716                     var emitSkipped = false;
103717                     var diagnostics = void 0;
103718                     var emittedFiles = [];
103719                     var affectedEmitResult = void 0;
103720                     while (affectedEmitResult = emitNextAffectedFile(writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers)) {
103721                         emitSkipped = emitSkipped || affectedEmitResult.result.emitSkipped;
103722                         diagnostics = ts.addRange(diagnostics, affectedEmitResult.result.diagnostics);
103723                         emittedFiles = ts.addRange(emittedFiles, affectedEmitResult.result.emittedFiles);
103724                         sourceMaps = ts.addRange(sourceMaps, affectedEmitResult.result.sourceMaps);
103725                     }
103726                     return {
103727                         emitSkipped: emitSkipped,
103728                         diagnostics: diagnostics || ts.emptyArray,
103729                         emittedFiles: emittedFiles,
103730                         sourceMaps: sourceMaps
103731                     };
103732                 }
103733             }
103734             return ts.Debug.checkDefined(state.program).emit(targetSourceFile, writeFile || ts.maybeBind(host, host.writeFile), cancellationToken, emitOnlyDtsFiles, customTransformers);
103735         }
103736         /**
103737          * Return the semantic diagnostics for the next affected file or undefined if iteration is complete
103738          * If provided ignoreSourceFile would be called before getting the diagnostics and would ignore the sourceFile if the returned value was true
103739          */
103740         function getSemanticDiagnosticsOfNextAffectedFile(cancellationToken, ignoreSourceFile) {
103741             while (true) {
103742                 var affected = getNextAffectedFile(state, cancellationToken, computeHash);
103743                 if (!affected) {
103744                     // Done
103745                     return undefined;
103746                 }
103747                 else if (affected === state.program) {
103748                     // When whole program is affected, get all semantic diagnostics (eg when --out or --outFile is specified)
103749                     return toAffectedFileResult(state, state.program.getSemanticDiagnostics(/*targetSourceFile*/ undefined, cancellationToken), affected);
103750                 }
103751                 // Add file to affected file pending emit to handle for later emit time
103752                 if (kind === BuilderProgramKind.EmitAndSemanticDiagnosticsBuilderProgram) {
103753                     addToAffectedFilesPendingEmit(state, affected.resolvedPath, 1 /* Full */);
103754                 }
103755                 // Get diagnostics for the affected file if its not ignored
103756                 if (ignoreSourceFile && ignoreSourceFile(affected)) {
103757                     // Get next affected file
103758                     doneWithAffectedFile(state, affected);
103759                     continue;
103760                 }
103761                 return toAffectedFileResult(state, getSemanticDiagnosticsOfFile(state, affected, cancellationToken), affected);
103762             }
103763         }
103764         /**
103765          * Gets the semantic diagnostics from the program corresponding to this state of file (if provided) or whole program
103766          * The semantic diagnostics are cached and managed here
103767          * Note that it is assumed that when asked about semantic diagnostics through this API,
103768          * the file has been taken out of affected files so it is safe to use cache or get from program and cache the diagnostics
103769          * In case of SemanticDiagnosticsBuilderProgram if the source file is not provided,
103770          * it will iterate through all the affected files, to ensure that cache stays valid and yet provide a way to get all semantic diagnostics
103771          */
103772         function getSemanticDiagnostics(sourceFile, cancellationToken) {
103773             assertSourceFileOkWithoutNextAffectedCall(state, sourceFile);
103774             var compilerOptions = ts.Debug.checkDefined(state.program).getCompilerOptions();
103775             if (compilerOptions.outFile || compilerOptions.out) {
103776                 ts.Debug.assert(!state.semanticDiagnosticsPerFile);
103777                 // We dont need to cache the diagnostics just return them from program
103778                 return ts.Debug.checkDefined(state.program).getSemanticDiagnostics(sourceFile, cancellationToken);
103779             }
103780             if (sourceFile) {
103781                 return getSemanticDiagnosticsOfFile(state, sourceFile, cancellationToken);
103782             }
103783             // When semantic builder asks for diagnostics of the whole program,
103784             // ensure that all the affected files are handled
103785             // eslint-disable-next-line no-empty
103786             while (getSemanticDiagnosticsOfNextAffectedFile(cancellationToken)) {
103787             }
103788             var diagnostics;
103789             for (var _i = 0, _a = ts.Debug.checkDefined(state.program).getSourceFiles(); _i < _a.length; _i++) {
103790                 var sourceFile_1 = _a[_i];
103791                 diagnostics = ts.addRange(diagnostics, getSemanticDiagnosticsOfFile(state, sourceFile_1, cancellationToken));
103792             }
103793             return diagnostics || ts.emptyArray;
103794         }
103795     }
103796     ts.createBuilderProgram = createBuilderProgram;
103797     function addToAffectedFilesPendingEmit(state, affectedFilePendingEmit, kind) {
103798         if (!state.affectedFilesPendingEmit)
103799             state.affectedFilesPendingEmit = [];
103800         if (!state.affectedFilesPendingEmitKind)
103801             state.affectedFilesPendingEmitKind = ts.createMap();
103802         var existingKind = state.affectedFilesPendingEmitKind.get(affectedFilePendingEmit);
103803         state.affectedFilesPendingEmit.push(affectedFilePendingEmit);
103804         state.affectedFilesPendingEmitKind.set(affectedFilePendingEmit, existingKind || kind);
103805         // affectedFilesPendingEmitIndex === undefined
103806         // - means the emit state.affectedFilesPendingEmit was undefined before adding current affected files
103807         //   so start from 0 as array would be affectedFilesPendingEmit
103808         // else, continue to iterate from existing index, the current set is appended to existing files
103809         if (state.affectedFilesPendingEmitIndex === undefined) {
103810             state.affectedFilesPendingEmitIndex = 0;
103811         }
103812     }
103813     function getMapOfReferencedSet(mapLike, toPath) {
103814         if (!mapLike)
103815             return undefined;
103816         var map = ts.createMap();
103817         // Copies keys/values from template. Note that for..in will not throw if
103818         // template is undefined, and instead will just exit the loop.
103819         for (var key in mapLike) {
103820             if (ts.hasProperty(mapLike, key)) {
103821                 map.set(toPath(key), ts.arrayToSet(mapLike[key], toPath));
103822             }
103823         }
103824         return map;
103825     }
103826     function createBuildProgramUsingProgramBuildInfo(program, buildInfoPath, host) {
103827         var buildInfoDirectory = ts.getDirectoryPath(ts.getNormalizedAbsolutePath(buildInfoPath, host.getCurrentDirectory()));
103828         var getCanonicalFileName = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames());
103829         var fileInfos = ts.createMap();
103830         for (var key in program.fileInfos) {
103831             if (ts.hasProperty(program.fileInfos, key)) {
103832                 fileInfos.set(toPath(key), program.fileInfos[key]);
103833             }
103834         }
103835         var state = {
103836             fileInfos: fileInfos,
103837             compilerOptions: ts.convertToOptionsWithAbsolutePaths(program.options, toAbsolutePath),
103838             referencedMap: getMapOfReferencedSet(program.referencedMap, toPath),
103839             exportedModulesMap: getMapOfReferencedSet(program.exportedModulesMap, toPath),
103840             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]; }),
103841             hasReusableDiagnostic: true
103842         };
103843         return {
103844             getState: function () { return state; },
103845             backupState: ts.noop,
103846             restoreState: ts.noop,
103847             getProgram: ts.notImplemented,
103848             getProgramOrUndefined: ts.returnUndefined,
103849             releaseProgram: ts.noop,
103850             getCompilerOptions: function () { return state.compilerOptions; },
103851             getSourceFile: ts.notImplemented,
103852             getSourceFiles: ts.notImplemented,
103853             getOptionsDiagnostics: ts.notImplemented,
103854             getGlobalDiagnostics: ts.notImplemented,
103855             getConfigFileParsingDiagnostics: ts.notImplemented,
103856             getSyntacticDiagnostics: ts.notImplemented,
103857             getDeclarationDiagnostics: ts.notImplemented,
103858             getSemanticDiagnostics: ts.notImplemented,
103859             emit: ts.notImplemented,
103860             getAllDependencies: ts.notImplemented,
103861             getCurrentDirectory: ts.notImplemented,
103862             emitNextAffectedFile: ts.notImplemented,
103863             getSemanticDiagnosticsOfNextAffectedFile: ts.notImplemented,
103864             close: ts.noop,
103865         };
103866         function toPath(path) {
103867             return ts.toPath(path, buildInfoDirectory, getCanonicalFileName);
103868         }
103869         function toAbsolutePath(path) {
103870             return ts.getNormalizedAbsolutePath(path, buildInfoDirectory);
103871         }
103872     }
103873     ts.createBuildProgramUsingProgramBuildInfo = createBuildProgramUsingProgramBuildInfo;
103874     function createRedirectedBuilderProgram(state, configFileParsingDiagnostics) {
103875         return {
103876             getState: ts.notImplemented,
103877             backupState: ts.noop,
103878             restoreState: ts.noop,
103879             getProgram: getProgram,
103880             getProgramOrUndefined: function () { return state.program; },
103881             releaseProgram: function () { return state.program = undefined; },
103882             getCompilerOptions: function () { return state.compilerOptions; },
103883             getSourceFile: function (fileName) { return getProgram().getSourceFile(fileName); },
103884             getSourceFiles: function () { return getProgram().getSourceFiles(); },
103885             getOptionsDiagnostics: function (cancellationToken) { return getProgram().getOptionsDiagnostics(cancellationToken); },
103886             getGlobalDiagnostics: function (cancellationToken) { return getProgram().getGlobalDiagnostics(cancellationToken); },
103887             getConfigFileParsingDiagnostics: function () { return configFileParsingDiagnostics; },
103888             getSyntacticDiagnostics: function (sourceFile, cancellationToken) { return getProgram().getSyntacticDiagnostics(sourceFile, cancellationToken); },
103889             getDeclarationDiagnostics: function (sourceFile, cancellationToken) { return getProgram().getDeclarationDiagnostics(sourceFile, cancellationToken); },
103890             getSemanticDiagnostics: function (sourceFile, cancellationToken) { return getProgram().getSemanticDiagnostics(sourceFile, cancellationToken); },
103891             emit: function (sourceFile, writeFile, cancellationToken, emitOnlyDts, customTransformers) { return getProgram().emit(sourceFile, writeFile, cancellationToken, emitOnlyDts, customTransformers); },
103892             getAllDependencies: ts.notImplemented,
103893             getCurrentDirectory: function () { return getProgram().getCurrentDirectory(); },
103894             close: ts.noop,
103895         };
103896         function getProgram() {
103897             return ts.Debug.checkDefined(state.program);
103898         }
103899     }
103900     ts.createRedirectedBuilderProgram = createRedirectedBuilderProgram;
103901 })(ts || (ts = {}));
103902 var ts;
103903 (function (ts) {
103904     function createSemanticDiagnosticsBuilderProgram(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences) {
103905         return ts.createBuilderProgram(ts.BuilderProgramKind.SemanticDiagnosticsBuilderProgram, ts.getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences));
103906     }
103907     ts.createSemanticDiagnosticsBuilderProgram = createSemanticDiagnosticsBuilderProgram;
103908     function createEmitAndSemanticDiagnosticsBuilderProgram(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences) {
103909         return ts.createBuilderProgram(ts.BuilderProgramKind.EmitAndSemanticDiagnosticsBuilderProgram, ts.getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences));
103910     }
103911     ts.createEmitAndSemanticDiagnosticsBuilderProgram = createEmitAndSemanticDiagnosticsBuilderProgram;
103912     function createAbstractBuilder(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences) {
103913         var _a = ts.getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences), newProgram = _a.newProgram, newConfigFileParsingDiagnostics = _a.configFileParsingDiagnostics;
103914         return ts.createRedirectedBuilderProgram({ program: newProgram, compilerOptions: newProgram.getCompilerOptions() }, newConfigFileParsingDiagnostics);
103915     }
103916     ts.createAbstractBuilder = createAbstractBuilder;
103917 })(ts || (ts = {}));
103918 /*@internal*/
103919 var ts;
103920 (function (ts) {
103921     function removeIgnoredPath(path) {
103922         // Consider whole staging folder as if node_modules changed.
103923         if (ts.endsWith(path, "/node_modules/.staging")) {
103924             return ts.removeSuffix(path, "/.staging");
103925         }
103926         return ts.some(ts.ignoredPaths, function (searchPath) { return ts.stringContains(path, searchPath); }) ?
103927             undefined :
103928             path;
103929     }
103930     ts.removeIgnoredPath = removeIgnoredPath;
103931     /**
103932      * Filter out paths like
103933      * "/", "/user", "/user/username", "/user/username/folderAtRoot",
103934      * "c:/", "c:/users", "c:/users/username", "c:/users/username/folderAtRoot", "c:/folderAtRoot"
103935      * @param dirPath
103936      */
103937     function canWatchDirectory(dirPath) {
103938         var rootLength = ts.getRootLength(dirPath);
103939         if (dirPath.length === rootLength) {
103940             // Ignore "/", "c:/"
103941             return false;
103942         }
103943         var nextDirectorySeparator = dirPath.indexOf(ts.directorySeparator, rootLength);
103944         if (nextDirectorySeparator === -1) {
103945             // ignore "/user", "c:/users" or "c:/folderAtRoot"
103946             return false;
103947         }
103948         var pathPartForUserCheck = dirPath.substring(rootLength, nextDirectorySeparator + 1);
103949         var isNonDirectorySeparatorRoot = rootLength > 1 || dirPath.charCodeAt(0) !== 47 /* slash */;
103950         if (isNonDirectorySeparatorRoot &&
103951             dirPath.search(/[a-zA-Z]:/) !== 0 && // Non dos style paths
103952             pathPartForUserCheck.search(/[a-zA-z]\$\//) === 0) { // Dos style nextPart
103953             nextDirectorySeparator = dirPath.indexOf(ts.directorySeparator, nextDirectorySeparator + 1);
103954             if (nextDirectorySeparator === -1) {
103955                 // ignore "//vda1cs4850/c$/folderAtRoot"
103956                 return false;
103957             }
103958             pathPartForUserCheck = dirPath.substring(rootLength + pathPartForUserCheck.length, nextDirectorySeparator + 1);
103959         }
103960         if (isNonDirectorySeparatorRoot &&
103961             pathPartForUserCheck.search(/users\//i) !== 0) {
103962             // Paths like c:/folderAtRoot/subFolder are allowed
103963             return true;
103964         }
103965         for (var searchIndex = nextDirectorySeparator + 1, searchLevels = 2; searchLevels > 0; searchLevels--) {
103966             searchIndex = dirPath.indexOf(ts.directorySeparator, searchIndex) + 1;
103967             if (searchIndex === 0) {
103968                 // Folder isnt at expected minimum levels
103969                 return false;
103970             }
103971         }
103972         return true;
103973     }
103974     ts.canWatchDirectory = canWatchDirectory;
103975     function createResolutionCache(resolutionHost, rootDirForResolution, logChangesWhenResolvingModule) {
103976         var filesWithChangedSetOfUnresolvedImports;
103977         var filesWithInvalidatedResolutions;
103978         var filesWithInvalidatedNonRelativeUnresolvedImports;
103979         var nonRelativeExternalModuleResolutions = ts.createMultiMap();
103980         var resolutionsWithFailedLookups = [];
103981         var resolvedFileToResolution = ts.createMultiMap();
103982         var getCurrentDirectory = ts.memoize(function () { return resolutionHost.getCurrentDirectory(); }); // TODO: GH#18217
103983         var cachedDirectoryStructureHost = resolutionHost.getCachedDirectoryStructureHost();
103984         // The resolvedModuleNames and resolvedTypeReferenceDirectives are the cache of resolutions per file.
103985         // The key in the map is source file's path.
103986         // The values are Map of resolutions with key being name lookedup.
103987         var resolvedModuleNames = ts.createMap();
103988         var perDirectoryResolvedModuleNames = ts.createCacheWithRedirects();
103989         var nonRelativeModuleNameCache = ts.createCacheWithRedirects();
103990         var moduleResolutionCache = ts.createModuleResolutionCacheWithMaps(perDirectoryResolvedModuleNames, nonRelativeModuleNameCache, getCurrentDirectory(), resolutionHost.getCanonicalFileName);
103991         var resolvedTypeReferenceDirectives = ts.createMap();
103992         var perDirectoryResolvedTypeReferenceDirectives = ts.createCacheWithRedirects();
103993         /**
103994          * These are the extensions that failed lookup files will have by default,
103995          * any other extension of failed lookup will be store that path in custom failed lookup path
103996          * This helps in not having to comb through all resolutions when files are added/removed
103997          * Note that .d.ts file also has .d.ts extension hence will be part of default extensions
103998          */
103999         var failedLookupDefaultExtensions = [".ts" /* Ts */, ".tsx" /* Tsx */, ".js" /* Js */, ".jsx" /* Jsx */, ".json" /* Json */];
104000         var customFailedLookupPaths = ts.createMap();
104001         var directoryWatchesOfFailedLookups = ts.createMap();
104002         var rootDir = rootDirForResolution && ts.removeTrailingDirectorySeparator(ts.getNormalizedAbsolutePath(rootDirForResolution, getCurrentDirectory()));
104003         var rootPath = (rootDir && resolutionHost.toPath(rootDir)); // TODO: GH#18217
104004         var rootSplitLength = rootPath !== undefined ? rootPath.split(ts.directorySeparator).length : 0;
104005         // TypeRoot watches for the types that get added as part of getAutomaticTypeDirectiveNames
104006         var typeRootsWatches = ts.createMap();
104007         return {
104008             startRecordingFilesWithChangedResolutions: startRecordingFilesWithChangedResolutions,
104009             finishRecordingFilesWithChangedResolutions: finishRecordingFilesWithChangedResolutions,
104010             // perDirectoryResolvedModuleNames and perDirectoryResolvedTypeReferenceDirectives could be non empty if there was exception during program update
104011             // (between startCachingPerDirectoryResolution and finishCachingPerDirectoryResolution)
104012             startCachingPerDirectoryResolution: clearPerDirectoryResolutions,
104013             finishCachingPerDirectoryResolution: finishCachingPerDirectoryResolution,
104014             resolveModuleNames: resolveModuleNames,
104015             getResolvedModuleWithFailedLookupLocationsFromCache: getResolvedModuleWithFailedLookupLocationsFromCache,
104016             resolveTypeReferenceDirectives: resolveTypeReferenceDirectives,
104017             removeResolutionsFromProjectReferenceRedirects: removeResolutionsFromProjectReferenceRedirects,
104018             removeResolutionsOfFile: removeResolutionsOfFile,
104019             invalidateResolutionOfFile: invalidateResolutionOfFile,
104020             setFilesWithInvalidatedNonRelativeUnresolvedImports: setFilesWithInvalidatedNonRelativeUnresolvedImports,
104021             createHasInvalidatedResolution: createHasInvalidatedResolution,
104022             updateTypeRootsWatch: updateTypeRootsWatch,
104023             closeTypeRootsWatch: closeTypeRootsWatch,
104024             clear: clear
104025         };
104026         function getResolvedModule(resolution) {
104027             return resolution.resolvedModule;
104028         }
104029         function getResolvedTypeReferenceDirective(resolution) {
104030             return resolution.resolvedTypeReferenceDirective;
104031         }
104032         function isInDirectoryPath(dir, file) {
104033             if (dir === undefined || file.length <= dir.length) {
104034                 return false;
104035             }
104036             return ts.startsWith(file, dir) && file[dir.length] === ts.directorySeparator;
104037         }
104038         function clear() {
104039             ts.clearMap(directoryWatchesOfFailedLookups, ts.closeFileWatcherOf);
104040             customFailedLookupPaths.clear();
104041             nonRelativeExternalModuleResolutions.clear();
104042             closeTypeRootsWatch();
104043             resolvedModuleNames.clear();
104044             resolvedTypeReferenceDirectives.clear();
104045             resolvedFileToResolution.clear();
104046             resolutionsWithFailedLookups.length = 0;
104047             // perDirectoryResolvedModuleNames and perDirectoryResolvedTypeReferenceDirectives could be non empty if there was exception during program update
104048             // (between startCachingPerDirectoryResolution and finishCachingPerDirectoryResolution)
104049             clearPerDirectoryResolutions();
104050         }
104051         function startRecordingFilesWithChangedResolutions() {
104052             filesWithChangedSetOfUnresolvedImports = [];
104053         }
104054         function finishRecordingFilesWithChangedResolutions() {
104055             var collected = filesWithChangedSetOfUnresolvedImports;
104056             filesWithChangedSetOfUnresolvedImports = undefined;
104057             return collected;
104058         }
104059         function isFileWithInvalidatedNonRelativeUnresolvedImports(path) {
104060             if (!filesWithInvalidatedNonRelativeUnresolvedImports) {
104061                 return false;
104062             }
104063             // Invalidated if file has unresolved imports
104064             var value = filesWithInvalidatedNonRelativeUnresolvedImports.get(path);
104065             return !!value && !!value.length;
104066         }
104067         function createHasInvalidatedResolution(forceAllFilesAsInvalidated) {
104068             if (forceAllFilesAsInvalidated) {
104069                 // Any file asked would have invalidated resolution
104070                 filesWithInvalidatedResolutions = undefined;
104071                 return ts.returnTrue;
104072             }
104073             var collected = filesWithInvalidatedResolutions;
104074             filesWithInvalidatedResolutions = undefined;
104075             return function (path) { return (!!collected && collected.has(path)) ||
104076                 isFileWithInvalidatedNonRelativeUnresolvedImports(path); };
104077         }
104078         function clearPerDirectoryResolutions() {
104079             perDirectoryResolvedModuleNames.clear();
104080             nonRelativeModuleNameCache.clear();
104081             perDirectoryResolvedTypeReferenceDirectives.clear();
104082             nonRelativeExternalModuleResolutions.forEach(watchFailedLookupLocationOfNonRelativeModuleResolutions);
104083             nonRelativeExternalModuleResolutions.clear();
104084         }
104085         function finishCachingPerDirectoryResolution() {
104086             filesWithInvalidatedNonRelativeUnresolvedImports = undefined;
104087             clearPerDirectoryResolutions();
104088             directoryWatchesOfFailedLookups.forEach(function (watcher, path) {
104089                 if (watcher.refCount === 0) {
104090                     directoryWatchesOfFailedLookups.delete(path);
104091                     watcher.watcher.close();
104092                 }
104093             });
104094         }
104095         function resolveModuleName(moduleName, containingFile, compilerOptions, host, redirectedReference) {
104096             var _a;
104097             var primaryResult = ts.resolveModuleName(moduleName, containingFile, compilerOptions, host, moduleResolutionCache, redirectedReference);
104098             // return result immediately only if global cache support is not enabled or if it is .ts, .tsx or .d.ts
104099             if (!resolutionHost.getGlobalCache) {
104100                 return primaryResult;
104101             }
104102             // otherwise try to load typings from @types
104103             var globalCache = resolutionHost.getGlobalCache();
104104             if (globalCache !== undefined && !ts.isExternalModuleNameRelative(moduleName) && !(primaryResult.resolvedModule && ts.extensionIsTS(primaryResult.resolvedModule.extension))) {
104105                 // create different collection of failed lookup locations for second pass
104106                 // if it will fail and we've already found something during the first pass - we don't want to pollute its results
104107                 var _b = ts.loadModuleFromGlobalCache(ts.Debug.checkDefined(resolutionHost.globalCacheResolutionModuleName)(moduleName), resolutionHost.projectName, compilerOptions, host, globalCache), resolvedModule = _b.resolvedModule, failedLookupLocations = _b.failedLookupLocations;
104108                 if (resolvedModule) {
104109                     // Modify existing resolution so its saved in the directory cache as well
104110                     primaryResult.resolvedModule = resolvedModule;
104111                     (_a = primaryResult.failedLookupLocations).push.apply(_a, failedLookupLocations);
104112                     return primaryResult;
104113                 }
104114             }
104115             // Default return the result from the first pass
104116             return primaryResult;
104117         }
104118         function resolveNamesWithLocalCache(_a) {
104119             var _b;
104120             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;
104121             var path = resolutionHost.toPath(containingFile);
104122             var resolutionsInFile = cache.get(path) || cache.set(path, ts.createMap()).get(path);
104123             var dirPath = ts.getDirectoryPath(path);
104124             var perDirectoryCache = perDirectoryCacheWithRedirects.getOrCreateMapOfCacheRedirects(redirectedReference);
104125             var perDirectoryResolution = perDirectoryCache.get(dirPath);
104126             if (!perDirectoryResolution) {
104127                 perDirectoryResolution = ts.createMap();
104128                 perDirectoryCache.set(dirPath, perDirectoryResolution);
104129             }
104130             var resolvedModules = [];
104131             var compilerOptions = resolutionHost.getCompilationSettings();
104132             var hasInvalidatedNonRelativeUnresolvedImport = logChanges && isFileWithInvalidatedNonRelativeUnresolvedImports(path);
104133             // All the resolutions in this file are invalidated if this file wasnt resolved using same redirect
104134             var program = resolutionHost.getCurrentProgram();
104135             var oldRedirect = program && program.getResolvedProjectReferenceToRedirect(containingFile);
104136             var unmatchedRedirects = oldRedirect ?
104137                 !redirectedReference || redirectedReference.sourceFile.path !== oldRedirect.sourceFile.path :
104138                 !!redirectedReference;
104139             var seenNamesInFile = ts.createMap();
104140             for (var _i = 0, names_3 = names; _i < names_3.length; _i++) {
104141                 var name = names_3[_i];
104142                 var resolution = resolutionsInFile.get(name);
104143                 // Resolution is valid if it is present and not invalidated
104144                 if (!seenNamesInFile.has(name) &&
104145                     unmatchedRedirects || !resolution || resolution.isInvalidated ||
104146                     // If the name is unresolved import that was invalidated, recalculate
104147                     (hasInvalidatedNonRelativeUnresolvedImport && !ts.isExternalModuleNameRelative(name) && shouldRetryResolution(resolution))) {
104148                     var existingResolution = resolution;
104149                     var resolutionInDirectory = perDirectoryResolution.get(name);
104150                     if (resolutionInDirectory) {
104151                         resolution = resolutionInDirectory;
104152                     }
104153                     else {
104154                         resolution = loader(name, containingFile, compilerOptions, ((_b = resolutionHost.getCompilerHost) === null || _b === void 0 ? void 0 : _b.call(resolutionHost)) || resolutionHost, redirectedReference);
104155                         perDirectoryResolution.set(name, resolution);
104156                     }
104157                     resolutionsInFile.set(name, resolution);
104158                     watchFailedLookupLocationsOfExternalModuleResolutions(name, resolution, path, getResolutionWithResolvedFileName);
104159                     if (existingResolution) {
104160                         stopWatchFailedLookupLocationOfResolution(existingResolution, path, getResolutionWithResolvedFileName);
104161                     }
104162                     if (logChanges && filesWithChangedSetOfUnresolvedImports && !resolutionIsEqualTo(existingResolution, resolution)) {
104163                         filesWithChangedSetOfUnresolvedImports.push(path);
104164                         // reset log changes to avoid recording the same file multiple times
104165                         logChanges = false;
104166                     }
104167                 }
104168                 ts.Debug.assert(resolution !== undefined && !resolution.isInvalidated);
104169                 seenNamesInFile.set(name, true);
104170                 resolvedModules.push(getResolutionWithResolvedFileName(resolution));
104171             }
104172             // Stop watching and remove the unused name
104173             resolutionsInFile.forEach(function (resolution, name) {
104174                 if (!seenNamesInFile.has(name) && !ts.contains(reusedNames, name)) {
104175                     stopWatchFailedLookupLocationOfResolution(resolution, path, getResolutionWithResolvedFileName);
104176                     resolutionsInFile.delete(name);
104177                 }
104178             });
104179             return resolvedModules;
104180             function resolutionIsEqualTo(oldResolution, newResolution) {
104181                 if (oldResolution === newResolution) {
104182                     return true;
104183                 }
104184                 if (!oldResolution || !newResolution) {
104185                     return false;
104186                 }
104187                 var oldResult = getResolutionWithResolvedFileName(oldResolution);
104188                 var newResult = getResolutionWithResolvedFileName(newResolution);
104189                 if (oldResult === newResult) {
104190                     return true;
104191                 }
104192                 if (!oldResult || !newResult) {
104193                     return false;
104194                 }
104195                 return oldResult.resolvedFileName === newResult.resolvedFileName;
104196             }
104197         }
104198         function resolveTypeReferenceDirectives(typeDirectiveNames, containingFile, redirectedReference) {
104199             return resolveNamesWithLocalCache({
104200                 names: typeDirectiveNames,
104201                 containingFile: containingFile,
104202                 redirectedReference: redirectedReference,
104203                 cache: resolvedTypeReferenceDirectives,
104204                 perDirectoryCacheWithRedirects: perDirectoryResolvedTypeReferenceDirectives,
104205                 loader: ts.resolveTypeReferenceDirective,
104206                 getResolutionWithResolvedFileName: getResolvedTypeReferenceDirective,
104207                 shouldRetryResolution: function (resolution) { return resolution.resolvedTypeReferenceDirective === undefined; },
104208             });
104209         }
104210         function resolveModuleNames(moduleNames, containingFile, reusedNames, redirectedReference) {
104211             return resolveNamesWithLocalCache({
104212                 names: moduleNames,
104213                 containingFile: containingFile,
104214                 redirectedReference: redirectedReference,
104215                 cache: resolvedModuleNames,
104216                 perDirectoryCacheWithRedirects: perDirectoryResolvedModuleNames,
104217                 loader: resolveModuleName,
104218                 getResolutionWithResolvedFileName: getResolvedModule,
104219                 shouldRetryResolution: function (resolution) { return !resolution.resolvedModule || !ts.resolutionExtensionIsTSOrJson(resolution.resolvedModule.extension); },
104220                 reusedNames: reusedNames,
104221                 logChanges: logChangesWhenResolvingModule
104222             });
104223         }
104224         function getResolvedModuleWithFailedLookupLocationsFromCache(moduleName, containingFile) {
104225             var cache = resolvedModuleNames.get(resolutionHost.toPath(containingFile));
104226             return cache && cache.get(moduleName);
104227         }
104228         function isNodeModulesAtTypesDirectory(dirPath) {
104229             return ts.endsWith(dirPath, "/node_modules/@types");
104230         }
104231         function getDirectoryToWatchFailedLookupLocation(failedLookupLocation, failedLookupLocationPath) {
104232             if (isInDirectoryPath(rootPath, failedLookupLocationPath)) {
104233                 // Ensure failed look up is normalized path
104234                 failedLookupLocation = ts.isRootedDiskPath(failedLookupLocation) ? ts.normalizePath(failedLookupLocation) : ts.getNormalizedAbsolutePath(failedLookupLocation, getCurrentDirectory());
104235                 var failedLookupPathSplit = failedLookupLocationPath.split(ts.directorySeparator);
104236                 var failedLookupSplit = failedLookupLocation.split(ts.directorySeparator);
104237                 ts.Debug.assert(failedLookupSplit.length === failedLookupPathSplit.length, "FailedLookup: " + failedLookupLocation + " failedLookupLocationPath: " + failedLookupLocationPath);
104238                 if (failedLookupPathSplit.length > rootSplitLength + 1) {
104239                     // Instead of watching root, watch directory in root to avoid watching excluded directories not needed for module resolution
104240                     return {
104241                         dir: failedLookupSplit.slice(0, rootSplitLength + 1).join(ts.directorySeparator),
104242                         dirPath: failedLookupPathSplit.slice(0, rootSplitLength + 1).join(ts.directorySeparator)
104243                     };
104244                 }
104245                 else {
104246                     // Always watch root directory non recursively
104247                     return {
104248                         dir: rootDir,
104249                         dirPath: rootPath,
104250                         nonRecursive: false
104251                     };
104252                 }
104253             }
104254             return getDirectoryToWatchFromFailedLookupLocationDirectory(ts.getDirectoryPath(ts.getNormalizedAbsolutePath(failedLookupLocation, getCurrentDirectory())), ts.getDirectoryPath(failedLookupLocationPath));
104255         }
104256         function getDirectoryToWatchFromFailedLookupLocationDirectory(dir, dirPath) {
104257             // If directory path contains node module, get the most parent node_modules directory for watching
104258             while (ts.pathContainsNodeModules(dirPath)) {
104259                 dir = ts.getDirectoryPath(dir);
104260                 dirPath = ts.getDirectoryPath(dirPath);
104261             }
104262             // If the directory is node_modules use it to watch, always watch it recursively
104263             if (ts.isNodeModulesDirectory(dirPath)) {
104264                 return canWatchDirectory(ts.getDirectoryPath(dirPath)) ? { dir: dir, dirPath: dirPath } : undefined;
104265             }
104266             var nonRecursive = true;
104267             // Use some ancestor of the root directory
104268             var subDirectoryPath, subDirectory;
104269             if (rootPath !== undefined) {
104270                 while (!isInDirectoryPath(dirPath, rootPath)) {
104271                     var parentPath = ts.getDirectoryPath(dirPath);
104272                     if (parentPath === dirPath) {
104273                         break;
104274                     }
104275                     nonRecursive = false;
104276                     subDirectoryPath = dirPath;
104277                     subDirectory = dir;
104278                     dirPath = parentPath;
104279                     dir = ts.getDirectoryPath(dir);
104280                 }
104281             }
104282             return canWatchDirectory(dirPath) ? { dir: subDirectory || dir, dirPath: subDirectoryPath || dirPath, nonRecursive: nonRecursive } : undefined;
104283         }
104284         function isPathWithDefaultFailedLookupExtension(path) {
104285             return ts.fileExtensionIsOneOf(path, failedLookupDefaultExtensions);
104286         }
104287         function watchFailedLookupLocationsOfExternalModuleResolutions(name, resolution, filePath, getResolutionWithResolvedFileName) {
104288             if (resolution.refCount) {
104289                 resolution.refCount++;
104290                 ts.Debug.assertDefined(resolution.files);
104291             }
104292             else {
104293                 resolution.refCount = 1;
104294                 ts.Debug.assert(resolution.files === undefined);
104295                 if (ts.isExternalModuleNameRelative(name)) {
104296                     watchFailedLookupLocationOfResolution(resolution);
104297                 }
104298                 else {
104299                     nonRelativeExternalModuleResolutions.add(name, resolution);
104300                 }
104301                 var resolved = getResolutionWithResolvedFileName(resolution);
104302                 if (resolved && resolved.resolvedFileName) {
104303                     resolvedFileToResolution.add(resolutionHost.toPath(resolved.resolvedFileName), resolution);
104304                 }
104305             }
104306             (resolution.files || (resolution.files = [])).push(filePath);
104307         }
104308         function watchFailedLookupLocationOfResolution(resolution) {
104309             ts.Debug.assert(!!resolution.refCount);
104310             var failedLookupLocations = resolution.failedLookupLocations;
104311             if (!failedLookupLocations.length)
104312                 return;
104313             resolutionsWithFailedLookups.push(resolution);
104314             var setAtRoot = false;
104315             for (var _i = 0, failedLookupLocations_1 = failedLookupLocations; _i < failedLookupLocations_1.length; _i++) {
104316                 var failedLookupLocation = failedLookupLocations_1[_i];
104317                 var failedLookupLocationPath = resolutionHost.toPath(failedLookupLocation);
104318                 var toWatch = getDirectoryToWatchFailedLookupLocation(failedLookupLocation, failedLookupLocationPath);
104319                 if (toWatch) {
104320                     var dir = toWatch.dir, dirPath = toWatch.dirPath, nonRecursive = toWatch.nonRecursive;
104321                     // If the failed lookup location path is not one of the supported extensions,
104322                     // store it in the custom path
104323                     if (!isPathWithDefaultFailedLookupExtension(failedLookupLocationPath)) {
104324                         var refCount = customFailedLookupPaths.get(failedLookupLocationPath) || 0;
104325                         customFailedLookupPaths.set(failedLookupLocationPath, refCount + 1);
104326                     }
104327                     if (dirPath === rootPath) {
104328                         ts.Debug.assert(!nonRecursive);
104329                         setAtRoot = true;
104330                     }
104331                     else {
104332                         setDirectoryWatcher(dir, dirPath, nonRecursive);
104333                     }
104334                 }
104335             }
104336             if (setAtRoot) {
104337                 // This is always non recursive
104338                 setDirectoryWatcher(rootDir, rootPath, /*nonRecursive*/ true); // TODO: GH#18217
104339             }
104340         }
104341         function watchFailedLookupLocationOfNonRelativeModuleResolutions(resolutions, name) {
104342             var program = resolutionHost.getCurrentProgram();
104343             if (!program || !program.getTypeChecker().tryFindAmbientModuleWithoutAugmentations(name)) {
104344                 resolutions.forEach(watchFailedLookupLocationOfResolution);
104345             }
104346         }
104347         function setDirectoryWatcher(dir, dirPath, nonRecursive) {
104348             var dirWatcher = directoryWatchesOfFailedLookups.get(dirPath);
104349             if (dirWatcher) {
104350                 ts.Debug.assert(!!nonRecursive === !!dirWatcher.nonRecursive);
104351                 dirWatcher.refCount++;
104352             }
104353             else {
104354                 directoryWatchesOfFailedLookups.set(dirPath, { watcher: createDirectoryWatcher(dir, dirPath, nonRecursive), refCount: 1, nonRecursive: nonRecursive });
104355             }
104356         }
104357         function stopWatchFailedLookupLocationOfResolution(resolution, filePath, getResolutionWithResolvedFileName) {
104358             ts.unorderedRemoveItem(ts.Debug.assertDefined(resolution.files), filePath);
104359             resolution.refCount--;
104360             if (resolution.refCount) {
104361                 return;
104362             }
104363             var resolved = getResolutionWithResolvedFileName(resolution);
104364             if (resolved && resolved.resolvedFileName) {
104365                 resolvedFileToResolution.remove(resolutionHost.toPath(resolved.resolvedFileName), resolution);
104366             }
104367             if (!ts.unorderedRemoveItem(resolutionsWithFailedLookups, resolution)) {
104368                 // If not watching failed lookups, it wont be there in resolutionsWithFailedLookups
104369                 return;
104370             }
104371             var failedLookupLocations = resolution.failedLookupLocations;
104372             var removeAtRoot = false;
104373             for (var _i = 0, failedLookupLocations_2 = failedLookupLocations; _i < failedLookupLocations_2.length; _i++) {
104374                 var failedLookupLocation = failedLookupLocations_2[_i];
104375                 var failedLookupLocationPath = resolutionHost.toPath(failedLookupLocation);
104376                 var toWatch = getDirectoryToWatchFailedLookupLocation(failedLookupLocation, failedLookupLocationPath);
104377                 if (toWatch) {
104378                     var dirPath = toWatch.dirPath;
104379                     var refCount = customFailedLookupPaths.get(failedLookupLocationPath);
104380                     if (refCount) {
104381                         if (refCount === 1) {
104382                             customFailedLookupPaths.delete(failedLookupLocationPath);
104383                         }
104384                         else {
104385                             ts.Debug.assert(refCount > 1);
104386                             customFailedLookupPaths.set(failedLookupLocationPath, refCount - 1);
104387                         }
104388                     }
104389                     if (dirPath === rootPath) {
104390                         removeAtRoot = true;
104391                     }
104392                     else {
104393                         removeDirectoryWatcher(dirPath);
104394                     }
104395                 }
104396             }
104397             if (removeAtRoot) {
104398                 removeDirectoryWatcher(rootPath);
104399             }
104400         }
104401         function removeDirectoryWatcher(dirPath) {
104402             var dirWatcher = directoryWatchesOfFailedLookups.get(dirPath);
104403             // Do not close the watcher yet since it might be needed by other failed lookup locations.
104404             dirWatcher.refCount--;
104405         }
104406         function createDirectoryWatcher(directory, dirPath, nonRecursive) {
104407             return resolutionHost.watchDirectoryOfFailedLookupLocation(directory, function (fileOrDirectory) {
104408                 var fileOrDirectoryPath = resolutionHost.toPath(fileOrDirectory);
104409                 if (cachedDirectoryStructureHost) {
104410                     // Since the file existence changed, update the sourceFiles cache
104411                     cachedDirectoryStructureHost.addOrDeleteFileOrDirectory(fileOrDirectory, fileOrDirectoryPath);
104412                 }
104413                 if (invalidateResolutionOfFailedLookupLocation(fileOrDirectoryPath, dirPath === fileOrDirectoryPath)) {
104414                     resolutionHost.onInvalidatedResolution();
104415                 }
104416             }, nonRecursive ? 0 /* None */ : 1 /* Recursive */);
104417         }
104418         function removeResolutionsOfFileFromCache(cache, filePath, getResolutionWithResolvedFileName) {
104419             // Deleted file, stop watching failed lookups for all the resolutions in the file
104420             var resolutions = cache.get(filePath);
104421             if (resolutions) {
104422                 resolutions.forEach(function (resolution) { return stopWatchFailedLookupLocationOfResolution(resolution, filePath, getResolutionWithResolvedFileName); });
104423                 cache.delete(filePath);
104424             }
104425         }
104426         function removeResolutionsFromProjectReferenceRedirects(filePath) {
104427             if (!ts.fileExtensionIs(filePath, ".json" /* Json */)) {
104428                 return;
104429             }
104430             var program = resolutionHost.getCurrentProgram();
104431             if (!program) {
104432                 return;
104433             }
104434             // If this file is input file for the referenced project, get it
104435             var resolvedProjectReference = program.getResolvedProjectReferenceByPath(filePath);
104436             if (!resolvedProjectReference) {
104437                 return;
104438             }
104439             // filePath is for the projectReference and the containing file is from this project reference, invalidate the resolution
104440             resolvedProjectReference.commandLine.fileNames.forEach(function (f) { return removeResolutionsOfFile(resolutionHost.toPath(f)); });
104441         }
104442         function removeResolutionsOfFile(filePath) {
104443             removeResolutionsOfFileFromCache(resolvedModuleNames, filePath, getResolvedModule);
104444             removeResolutionsOfFileFromCache(resolvedTypeReferenceDirectives, filePath, getResolvedTypeReferenceDirective);
104445         }
104446         function invalidateResolution(resolution) {
104447             resolution.isInvalidated = true;
104448             var changedInAutoTypeReferenced = false;
104449             for (var _i = 0, _a = ts.Debug.assertDefined(resolution.files); _i < _a.length; _i++) {
104450                 var containingFilePath = _a[_i];
104451                 (filesWithInvalidatedResolutions || (filesWithInvalidatedResolutions = ts.createMap())).set(containingFilePath, true);
104452                 // When its a file with inferred types resolution, invalidate type reference directive resolution
104453                 changedInAutoTypeReferenced = changedInAutoTypeReferenced || containingFilePath.endsWith(ts.inferredTypesContainingFile);
104454             }
104455             if (changedInAutoTypeReferenced) {
104456                 resolutionHost.onChangedAutomaticTypeDirectiveNames();
104457             }
104458         }
104459         function invalidateResolutionOfFile(filePath) {
104460             removeResolutionsOfFile(filePath);
104461             // Resolution is invalidated if the resulting file name is same as the deleted file path
104462             ts.forEach(resolvedFileToResolution.get(filePath), invalidateResolution);
104463         }
104464         function setFilesWithInvalidatedNonRelativeUnresolvedImports(filesMap) {
104465             ts.Debug.assert(filesWithInvalidatedNonRelativeUnresolvedImports === filesMap || filesWithInvalidatedNonRelativeUnresolvedImports === undefined);
104466             filesWithInvalidatedNonRelativeUnresolvedImports = filesMap;
104467         }
104468         function invalidateResolutionOfFailedLookupLocation(fileOrDirectoryPath, isCreatingWatchedDirectory) {
104469             var isChangedFailedLookupLocation;
104470             if (isCreatingWatchedDirectory) {
104471                 // Watching directory is created
104472                 // Invalidate any resolution has failed lookup in this directory
104473                 isChangedFailedLookupLocation = function (location) { return isInDirectoryPath(fileOrDirectoryPath, resolutionHost.toPath(location)); };
104474             }
104475             else {
104476                 // If something to do with folder/file starting with "." in node_modules folder, skip it
104477                 var updatedPath = removeIgnoredPath(fileOrDirectoryPath);
104478                 if (!updatedPath)
104479                     return false;
104480                 fileOrDirectoryPath = updatedPath;
104481                 // prevent saving an open file from over-eagerly triggering invalidation
104482                 if (resolutionHost.fileIsOpen(fileOrDirectoryPath)) {
104483                     return false;
104484                 }
104485                 // Some file or directory in the watching directory is created
104486                 // Return early if it does not have any of the watching extension or not the custom failed lookup path
104487                 var dirOfFileOrDirectory = ts.getDirectoryPath(fileOrDirectoryPath);
104488                 if (isNodeModulesAtTypesDirectory(fileOrDirectoryPath) || ts.isNodeModulesDirectory(fileOrDirectoryPath) ||
104489                     isNodeModulesAtTypesDirectory(dirOfFileOrDirectory) || ts.isNodeModulesDirectory(dirOfFileOrDirectory)) {
104490                     // Invalidate any resolution from this directory
104491                     isChangedFailedLookupLocation = function (location) {
104492                         var locationPath = resolutionHost.toPath(location);
104493                         return locationPath === fileOrDirectoryPath || ts.startsWith(resolutionHost.toPath(location), fileOrDirectoryPath);
104494                     };
104495                 }
104496                 else {
104497                     if (!isPathWithDefaultFailedLookupExtension(fileOrDirectoryPath) && !customFailedLookupPaths.has(fileOrDirectoryPath)) {
104498                         return false;
104499                     }
104500                     // Ignore emits from the program
104501                     if (ts.isEmittedFileOfProgram(resolutionHost.getCurrentProgram(), fileOrDirectoryPath)) {
104502                         return false;
104503                     }
104504                     // Resolution need to be invalidated if failed lookup location is same as the file or directory getting created
104505                     isChangedFailedLookupLocation = function (location) { return resolutionHost.toPath(location) === fileOrDirectoryPath; };
104506                 }
104507             }
104508             var invalidated = false;
104509             // Resolution is invalidated if the resulting file name is same as the deleted file path
104510             for (var _i = 0, resolutionsWithFailedLookups_1 = resolutionsWithFailedLookups; _i < resolutionsWithFailedLookups_1.length; _i++) {
104511                 var resolution = resolutionsWithFailedLookups_1[_i];
104512                 if (resolution.failedLookupLocations.some(isChangedFailedLookupLocation)) {
104513                     invalidateResolution(resolution);
104514                     invalidated = true;
104515                 }
104516             }
104517             return invalidated;
104518         }
104519         function closeTypeRootsWatch() {
104520             ts.clearMap(typeRootsWatches, ts.closeFileWatcher);
104521         }
104522         function getDirectoryToWatchFailedLookupLocationFromTypeRoot(typeRoot, typeRootPath) {
104523             if (isInDirectoryPath(rootPath, typeRootPath)) {
104524                 return rootPath;
104525             }
104526             var toWatch = getDirectoryToWatchFromFailedLookupLocationDirectory(typeRoot, typeRootPath);
104527             return toWatch && directoryWatchesOfFailedLookups.has(toWatch.dirPath) ? toWatch.dirPath : undefined;
104528         }
104529         function createTypeRootsWatch(typeRootPath, typeRoot) {
104530             // Create new watch and recursive info
104531             return resolutionHost.watchTypeRootsDirectory(typeRoot, function (fileOrDirectory) {
104532                 var fileOrDirectoryPath = resolutionHost.toPath(fileOrDirectory);
104533                 if (cachedDirectoryStructureHost) {
104534                     // Since the file existence changed, update the sourceFiles cache
104535                     cachedDirectoryStructureHost.addOrDeleteFileOrDirectory(fileOrDirectory, fileOrDirectoryPath);
104536                 }
104537                 // For now just recompile
104538                 // We could potentially store more data here about whether it was/would be really be used or not
104539                 // and with that determine to trigger compilation but for now this is enough
104540                 resolutionHost.onChangedAutomaticTypeDirectiveNames();
104541                 // Since directory watchers invoked are flaky, the failed lookup location events might not be triggered
104542                 // So handle to failed lookup locations here as well to ensure we are invalidating resolutions
104543                 var dirPath = getDirectoryToWatchFailedLookupLocationFromTypeRoot(typeRoot, typeRootPath);
104544                 if (dirPath && invalidateResolutionOfFailedLookupLocation(fileOrDirectoryPath, dirPath === fileOrDirectoryPath)) {
104545                     resolutionHost.onInvalidatedResolution();
104546                 }
104547             }, 1 /* Recursive */);
104548         }
104549         /**
104550          * Watches the types that would get added as part of getAutomaticTypeDirectiveNames
104551          * To be called when compiler options change
104552          */
104553         function updateTypeRootsWatch() {
104554             var options = resolutionHost.getCompilationSettings();
104555             if (options.types) {
104556                 // No need to do any watch since resolution cache is going to handle the failed lookups
104557                 // for the types added by this
104558                 closeTypeRootsWatch();
104559                 return;
104560             }
104561             // we need to assume the directories exist to ensure that we can get all the type root directories that get included
104562             // But filter directories that are at root level to say directory doesnt exist, so that we arent watching them
104563             var typeRoots = ts.getEffectiveTypeRoots(options, { directoryExists: directoryExistsForTypeRootWatch, getCurrentDirectory: getCurrentDirectory });
104564             if (typeRoots) {
104565                 ts.mutateMap(typeRootsWatches, ts.arrayToMap(typeRoots, function (tr) { return resolutionHost.toPath(tr); }), {
104566                     createNewValue: createTypeRootsWatch,
104567                     onDeleteValue: ts.closeFileWatcher
104568                 });
104569             }
104570             else {
104571                 closeTypeRootsWatch();
104572             }
104573         }
104574         /**
104575          * Use this function to return if directory exists to get type roots to watch
104576          * If we return directory exists then only the paths will be added to type roots
104577          * Hence return true for all directories except root directories which are filtered from watching
104578          */
104579         function directoryExistsForTypeRootWatch(nodeTypesDirectory) {
104580             var dir = ts.getDirectoryPath(ts.getDirectoryPath(nodeTypesDirectory));
104581             var dirPath = resolutionHost.toPath(dir);
104582             return dirPath === rootPath || canWatchDirectory(dirPath);
104583         }
104584     }
104585     ts.createResolutionCache = createResolutionCache;
104586 })(ts || (ts = {}));
104587 // Used by importFixes, getEditsForFileRename, and declaration emit to synthesize import module specifiers.
104588 /* @internal */
104589 var ts;
104590 (function (ts) {
104591     var moduleSpecifiers;
104592     (function (moduleSpecifiers) {
104593         var RelativePreference;
104594         (function (RelativePreference) {
104595             RelativePreference[RelativePreference["Relative"] = 0] = "Relative";
104596             RelativePreference[RelativePreference["NonRelative"] = 1] = "NonRelative";
104597             RelativePreference[RelativePreference["Auto"] = 2] = "Auto";
104598         })(RelativePreference || (RelativePreference = {}));
104599         // See UserPreferences#importPathEnding
104600         var Ending;
104601         (function (Ending) {
104602             Ending[Ending["Minimal"] = 0] = "Minimal";
104603             Ending[Ending["Index"] = 1] = "Index";
104604             Ending[Ending["JsExtension"] = 2] = "JsExtension";
104605         })(Ending || (Ending = {}));
104606         function getPreferences(_a, compilerOptions, importingSourceFile) {
104607             var importModuleSpecifierPreference = _a.importModuleSpecifierPreference, importModuleSpecifierEnding = _a.importModuleSpecifierEnding;
104608             return {
104609                 relativePreference: importModuleSpecifierPreference === "relative" ? 0 /* Relative */ : importModuleSpecifierPreference === "non-relative" ? 1 /* NonRelative */ : 2 /* Auto */,
104610                 ending: getEnding(),
104611             };
104612             function getEnding() {
104613                 switch (importModuleSpecifierEnding) {
104614                     case "minimal": return 0 /* Minimal */;
104615                     case "index": return 1 /* Index */;
104616                     case "js": return 2 /* JsExtension */;
104617                     default: return usesJsExtensionOnImports(importingSourceFile) ? 2 /* JsExtension */
104618                         : ts.getEmitModuleResolutionKind(compilerOptions) !== ts.ModuleResolutionKind.NodeJs ? 1 /* Index */ : 0 /* Minimal */;
104619                 }
104620             }
104621         }
104622         function getPreferencesForUpdate(compilerOptions, oldImportSpecifier) {
104623             return {
104624                 relativePreference: ts.isExternalModuleNameRelative(oldImportSpecifier) ? 0 /* Relative */ : 1 /* NonRelative */,
104625                 ending: ts.hasJSFileExtension(oldImportSpecifier) ?
104626                     2 /* JsExtension */ :
104627                     ts.getEmitModuleResolutionKind(compilerOptions) !== ts.ModuleResolutionKind.NodeJs || ts.endsWith(oldImportSpecifier, "index") ? 1 /* Index */ : 0 /* Minimal */,
104628             };
104629         }
104630         function updateModuleSpecifier(compilerOptions, importingSourceFileName, toFileName, host, oldImportSpecifier) {
104631             var res = getModuleSpecifierWorker(compilerOptions, importingSourceFileName, toFileName, host, getPreferencesForUpdate(compilerOptions, oldImportSpecifier));
104632             if (res === oldImportSpecifier)
104633                 return undefined;
104634             return res;
104635         }
104636         moduleSpecifiers.updateModuleSpecifier = updateModuleSpecifier;
104637         // Note: importingSourceFile is just for usesJsExtensionOnImports
104638         function getModuleSpecifier(compilerOptions, importingSourceFile, importingSourceFileName, toFileName, host, preferences) {
104639             if (preferences === void 0) { preferences = {}; }
104640             return getModuleSpecifierWorker(compilerOptions, importingSourceFileName, toFileName, host, getPreferences(preferences, compilerOptions, importingSourceFile));
104641         }
104642         moduleSpecifiers.getModuleSpecifier = getModuleSpecifier;
104643         function getNodeModulesPackageName(compilerOptions, importingSourceFileName, nodeModulesFileName, host) {
104644             var info = getInfo(importingSourceFileName, host);
104645             var modulePaths = getAllModulePaths(importingSourceFileName, nodeModulesFileName, host);
104646             return ts.firstDefined(modulePaths, function (moduleFileName) { return tryGetModuleNameAsNodeModule(moduleFileName, info, host, compilerOptions, /*packageNameOnly*/ true); });
104647         }
104648         moduleSpecifiers.getNodeModulesPackageName = getNodeModulesPackageName;
104649         function getModuleSpecifierWorker(compilerOptions, importingSourceFileName, toFileName, host, preferences) {
104650             var info = getInfo(importingSourceFileName, host);
104651             var modulePaths = getAllModulePaths(importingSourceFileName, toFileName, host);
104652             return ts.firstDefined(modulePaths, function (moduleFileName) { return tryGetModuleNameAsNodeModule(moduleFileName, info, host, compilerOptions); }) ||
104653                 getLocalModuleSpecifier(toFileName, info, compilerOptions, preferences);
104654         }
104655         /** Returns an import for each symlink and for the realpath. */
104656         function getModuleSpecifiers(moduleSymbol, compilerOptions, importingSourceFile, host, userPreferences) {
104657             var ambient = tryGetModuleNameFromAmbientModule(moduleSymbol);
104658             if (ambient)
104659                 return [ambient];
104660             var info = getInfo(importingSourceFile.path, host);
104661             var moduleSourceFile = ts.getSourceFileOfNode(moduleSymbol.valueDeclaration || ts.getNonAugmentationDeclaration(moduleSymbol));
104662             var modulePaths = getAllModulePaths(importingSourceFile.path, moduleSourceFile.originalFileName, host);
104663             var preferences = getPreferences(userPreferences, compilerOptions, importingSourceFile);
104664             var global = ts.mapDefined(modulePaths, function (moduleFileName) { return tryGetModuleNameAsNodeModule(moduleFileName, info, host, compilerOptions); });
104665             return global.length ? global : modulePaths.map(function (moduleFileName) { return getLocalModuleSpecifier(moduleFileName, info, compilerOptions, preferences); });
104666         }
104667         moduleSpecifiers.getModuleSpecifiers = getModuleSpecifiers;
104668         // importingSourceFileName is separate because getEditsForFileRename may need to specify an updated path
104669         function getInfo(importingSourceFileName, host) {
104670             var getCanonicalFileName = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames ? host.useCaseSensitiveFileNames() : true);
104671             var sourceDirectory = ts.getDirectoryPath(importingSourceFileName);
104672             return { getCanonicalFileName: getCanonicalFileName, sourceDirectory: sourceDirectory };
104673         }
104674         function getLocalModuleSpecifier(moduleFileName, _a, compilerOptions, _b) {
104675             var getCanonicalFileName = _a.getCanonicalFileName, sourceDirectory = _a.sourceDirectory;
104676             var ending = _b.ending, relativePreference = _b.relativePreference;
104677             var baseUrl = compilerOptions.baseUrl, paths = compilerOptions.paths, rootDirs = compilerOptions.rootDirs;
104678             var relativePath = rootDirs && tryGetModuleNameFromRootDirs(rootDirs, moduleFileName, sourceDirectory, getCanonicalFileName, ending, compilerOptions) ||
104679                 removeExtensionAndIndexPostFix(ts.ensurePathIsNonModuleName(ts.getRelativePathFromDirectory(sourceDirectory, moduleFileName, getCanonicalFileName)), ending, compilerOptions);
104680             if (!baseUrl || relativePreference === 0 /* Relative */) {
104681                 return relativePath;
104682             }
104683             var relativeToBaseUrl = getRelativePathIfInDirectory(moduleFileName, baseUrl, getCanonicalFileName);
104684             if (!relativeToBaseUrl) {
104685                 return relativePath;
104686             }
104687             var importRelativeToBaseUrl = removeExtensionAndIndexPostFix(relativeToBaseUrl, ending, compilerOptions);
104688             var fromPaths = paths && tryGetModuleNameFromPaths(ts.removeFileExtension(relativeToBaseUrl), importRelativeToBaseUrl, paths);
104689             var nonRelative = fromPaths === undefined ? importRelativeToBaseUrl : fromPaths;
104690             if (relativePreference === 1 /* NonRelative */) {
104691                 return nonRelative;
104692             }
104693             if (relativePreference !== 2 /* Auto */)
104694                 ts.Debug.assertNever(relativePreference);
104695             // Prefer a relative import over a baseUrl import if it has fewer components.
104696             return isPathRelativeToParent(nonRelative) || countPathComponents(relativePath) < countPathComponents(nonRelative) ? relativePath : nonRelative;
104697         }
104698         function countPathComponents(path) {
104699             var count = 0;
104700             for (var i = ts.startsWith(path, "./") ? 2 : 0; i < path.length; i++) {
104701                 if (path.charCodeAt(i) === 47 /* slash */)
104702                     count++;
104703             }
104704             return count;
104705         }
104706         moduleSpecifiers.countPathComponents = countPathComponents;
104707         function usesJsExtensionOnImports(_a) {
104708             var imports = _a.imports;
104709             return ts.firstDefined(imports, function (_a) {
104710                 var text = _a.text;
104711                 return ts.pathIsRelative(text) ? ts.hasJSFileExtension(text) : undefined;
104712             }) || false;
104713         }
104714         function numberOfDirectorySeparators(str) {
104715             var match = str.match(/\//g);
104716             return match ? match.length : 0;
104717         }
104718         function comparePathsByNumberOfDirectorySeparators(a, b) {
104719             return ts.compareValues(numberOfDirectorySeparators(a), numberOfDirectorySeparators(b));
104720         }
104721         function forEachFileNameOfModule(importingFileName, importedFileName, host, preferSymlinks, cb) {
104722             var getCanonicalFileName = ts.hostGetCanonicalFileName(host);
104723             var cwd = host.getCurrentDirectory();
104724             var referenceRedirect = host.isSourceOfProjectReferenceRedirect(importedFileName) ? host.getProjectReferenceRedirect(importedFileName) : undefined;
104725             var redirects = host.redirectTargetsMap.get(ts.toPath(importedFileName, cwd, getCanonicalFileName)) || ts.emptyArray;
104726             var importedFileNames = __spreadArrays((referenceRedirect ? [referenceRedirect] : ts.emptyArray), [importedFileName], redirects);
104727             var targets = importedFileNames.map(function (f) { return ts.getNormalizedAbsolutePath(f, cwd); });
104728             if (!preferSymlinks) {
104729                 var result_12 = ts.forEach(targets, cb);
104730                 if (result_12)
104731                     return result_12;
104732             }
104733             var links = host.getProbableSymlinks
104734                 ? host.getProbableSymlinks(host.getSourceFiles())
104735                 : ts.discoverProbableSymlinks(host.getSourceFiles(), getCanonicalFileName, cwd);
104736             var compareStrings = (!host.useCaseSensitiveFileNames || host.useCaseSensitiveFileNames()) ? ts.compareStringsCaseSensitive : ts.compareStringsCaseInsensitive;
104737             var result = ts.forEachEntry(links, function (resolved, path) {
104738                 if (ts.startsWithDirectory(importingFileName, resolved, getCanonicalFileName)) {
104739                     return undefined; // Don't want to a package to globally import from itself
104740                 }
104741                 var target = ts.find(targets, function (t) { return compareStrings(t.slice(0, resolved.length + 1), resolved + "/") === 0 /* EqualTo */; });
104742                 if (target === undefined)
104743                     return undefined;
104744                 var relative = ts.getRelativePathFromDirectory(resolved, target, getCanonicalFileName);
104745                 var option = ts.resolvePath(path, relative);
104746                 if (!host.fileExists || host.fileExists(option)) {
104747                     var result_13 = cb(option);
104748                     if (result_13)
104749                         return result_13;
104750                 }
104751             });
104752             return result ||
104753                 (preferSymlinks ? ts.forEach(targets, cb) : undefined);
104754         }
104755         moduleSpecifiers.forEachFileNameOfModule = forEachFileNameOfModule;
104756         /**
104757          * Looks for existing imports that use symlinks to this module.
104758          * Symlinks will be returned first so they are preferred over the real path.
104759          */
104760         function getAllModulePaths(importingFileName, importedFileName, host) {
104761             var cwd = host.getCurrentDirectory();
104762             var getCanonicalFileName = ts.hostGetCanonicalFileName(host);
104763             var allFileNames = ts.createMap();
104764             var importedFileFromNodeModules = false;
104765             forEachFileNameOfModule(importingFileName, importedFileName, host, 
104766             /*preferSymlinks*/ true, function (path) {
104767                 // dont return value, so we collect everything
104768                 allFileNames.set(path, getCanonicalFileName(path));
104769                 importedFileFromNodeModules = importedFileFromNodeModules || ts.pathContainsNodeModules(path);
104770             });
104771             // Sort by paths closest to importing file Name directory
104772             var sortedPaths = [];
104773             var _loop_20 = function (directory) {
104774                 var directoryStart = ts.ensureTrailingDirectorySeparator(directory);
104775                 var pathsInDirectory;
104776                 allFileNames.forEach(function (canonicalFileName, fileName) {
104777                     if (ts.startsWith(canonicalFileName, directoryStart)) {
104778                         // If the importedFile is from node modules, use only paths in node_modules folder as option
104779                         if (!importedFileFromNodeModules || ts.pathContainsNodeModules(fileName)) {
104780                             (pathsInDirectory || (pathsInDirectory = [])).push(fileName);
104781                         }
104782                         allFileNames.delete(fileName);
104783                     }
104784                 });
104785                 if (pathsInDirectory) {
104786                     if (pathsInDirectory.length > 1) {
104787                         pathsInDirectory.sort(comparePathsByNumberOfDirectorySeparators);
104788                     }
104789                     sortedPaths.push.apply(sortedPaths, pathsInDirectory);
104790                 }
104791                 var newDirectory = ts.getDirectoryPath(directory);
104792                 if (newDirectory === directory)
104793                     return out_directory_1 = directory, "break";
104794                 directory = newDirectory;
104795                 out_directory_1 = directory;
104796             };
104797             var out_directory_1;
104798             for (var directory = ts.getDirectoryPath(ts.toPath(importingFileName, cwd, getCanonicalFileName)); allFileNames.size !== 0;) {
104799                 var state_8 = _loop_20(directory);
104800                 directory = out_directory_1;
104801                 if (state_8 === "break")
104802                     break;
104803             }
104804             if (allFileNames.size) {
104805                 var remainingPaths = ts.arrayFrom(allFileNames.values());
104806                 if (remainingPaths.length > 1)
104807                     remainingPaths.sort(comparePathsByNumberOfDirectorySeparators);
104808                 sortedPaths.push.apply(sortedPaths, remainingPaths);
104809             }
104810             return sortedPaths;
104811         }
104812         function tryGetModuleNameFromAmbientModule(moduleSymbol) {
104813             var decl = ts.find(moduleSymbol.declarations, function (d) { return ts.isNonGlobalAmbientModule(d) && (!ts.isExternalModuleAugmentation(d) || !ts.isExternalModuleNameRelative(ts.getTextOfIdentifierOrLiteral(d.name))); });
104814             if (decl) {
104815                 return decl.name.text;
104816             }
104817         }
104818         function tryGetModuleNameFromPaths(relativeToBaseUrlWithIndex, relativeToBaseUrl, paths) {
104819             for (var key in paths) {
104820                 for (var _i = 0, _a = paths[key]; _i < _a.length; _i++) {
104821                     var patternText_1 = _a[_i];
104822                     var pattern = ts.removeFileExtension(ts.normalizePath(patternText_1));
104823                     var indexOfStar = pattern.indexOf("*");
104824                     if (indexOfStar !== -1) {
104825                         var prefix = pattern.substr(0, indexOfStar);
104826                         var suffix = pattern.substr(indexOfStar + 1);
104827                         if (relativeToBaseUrl.length >= prefix.length + suffix.length &&
104828                             ts.startsWith(relativeToBaseUrl, prefix) &&
104829                             ts.endsWith(relativeToBaseUrl, suffix) ||
104830                             !suffix && relativeToBaseUrl === ts.removeTrailingDirectorySeparator(prefix)) {
104831                             var matchedStar = relativeToBaseUrl.substr(prefix.length, relativeToBaseUrl.length - suffix.length);
104832                             return key.replace("*", matchedStar);
104833                         }
104834                     }
104835                     else if (pattern === relativeToBaseUrl || pattern === relativeToBaseUrlWithIndex) {
104836                         return key;
104837                     }
104838                 }
104839             }
104840         }
104841         function tryGetModuleNameFromRootDirs(rootDirs, moduleFileName, sourceDirectory, getCanonicalFileName, ending, compilerOptions) {
104842             var normalizedTargetPath = getPathRelativeToRootDirs(moduleFileName, rootDirs, getCanonicalFileName);
104843             if (normalizedTargetPath === undefined) {
104844                 return undefined;
104845             }
104846             var normalizedSourcePath = getPathRelativeToRootDirs(sourceDirectory, rootDirs, getCanonicalFileName);
104847             var relativePath = normalizedSourcePath !== undefined ? ts.ensurePathIsNonModuleName(ts.getRelativePathFromDirectory(normalizedSourcePath, normalizedTargetPath, getCanonicalFileName)) : normalizedTargetPath;
104848             return ts.getEmitModuleResolutionKind(compilerOptions) === ts.ModuleResolutionKind.NodeJs
104849                 ? removeExtensionAndIndexPostFix(relativePath, ending, compilerOptions)
104850                 : ts.removeFileExtension(relativePath);
104851         }
104852         function tryGetModuleNameAsNodeModule(moduleFileName, _a, host, options, packageNameOnly) {
104853             var getCanonicalFileName = _a.getCanonicalFileName, sourceDirectory = _a.sourceDirectory;
104854             if (!host.fileExists || !host.readFile) {
104855                 return undefined;
104856             }
104857             var parts = getNodeModulePathParts(moduleFileName);
104858             if (!parts) {
104859                 return undefined;
104860             }
104861             // Simplify the full file path to something that can be resolved by Node.
104862             var moduleSpecifier = moduleFileName;
104863             if (!packageNameOnly) {
104864                 var packageRootIndex = parts.packageRootIndex;
104865                 var moduleFileNameForExtensionless = void 0;
104866                 while (true) {
104867                     // If the module could be imported by a directory name, use that directory's name
104868                     var _b = tryDirectoryWithPackageJson(packageRootIndex), moduleFileToTry = _b.moduleFileToTry, packageRootPath = _b.packageRootPath;
104869                     if (packageRootPath) {
104870                         moduleSpecifier = packageRootPath;
104871                         break;
104872                     }
104873                     if (!moduleFileNameForExtensionless)
104874                         moduleFileNameForExtensionless = moduleFileToTry;
104875                     // try with next level of directory
104876                     packageRootIndex = moduleFileName.indexOf(ts.directorySeparator, packageRootIndex + 1);
104877                     if (packageRootIndex === -1) {
104878                         moduleSpecifier = getExtensionlessFileName(moduleFileNameForExtensionless);
104879                         break;
104880                     }
104881                 }
104882             }
104883             var globalTypingsCacheLocation = host.getGlobalTypingsCacheLocation && host.getGlobalTypingsCacheLocation();
104884             // Get a path that's relative to node_modules or the importing file's path
104885             // if node_modules folder is in this folder or any of its parent folders, no need to keep it.
104886             var pathToTopLevelNodeModules = getCanonicalFileName(moduleSpecifier.substring(0, parts.topLevelNodeModulesIndex));
104887             if (!(ts.startsWith(sourceDirectory, pathToTopLevelNodeModules) || globalTypingsCacheLocation && ts.startsWith(getCanonicalFileName(globalTypingsCacheLocation), pathToTopLevelNodeModules))) {
104888                 return undefined;
104889             }
104890             // If the module was found in @types, get the actual Node package name
104891             var nodeModulesDirectoryName = moduleSpecifier.substring(parts.topLevelPackageNameIndex + 1);
104892             var packageName = ts.getPackageNameFromTypesPackageName(nodeModulesDirectoryName);
104893             // For classic resolution, only allow importing from node_modules/@types, not other node_modules
104894             return ts.getEmitModuleResolutionKind(options) !== ts.ModuleResolutionKind.NodeJs && packageName === nodeModulesDirectoryName ? undefined : packageName;
104895             function tryDirectoryWithPackageJson(packageRootIndex) {
104896                 var packageRootPath = moduleFileName.substring(0, packageRootIndex);
104897                 var packageJsonPath = ts.combinePaths(packageRootPath, "package.json");
104898                 var moduleFileToTry = moduleFileName;
104899                 if (host.fileExists(packageJsonPath)) {
104900                     var packageJsonContent = JSON.parse(host.readFile(packageJsonPath));
104901                     var versionPaths = packageJsonContent.typesVersions
104902                         ? ts.getPackageJsonTypesVersionsPaths(packageJsonContent.typesVersions)
104903                         : undefined;
104904                     if (versionPaths) {
104905                         var subModuleName = moduleFileName.slice(packageRootPath.length + 1);
104906                         var fromPaths = tryGetModuleNameFromPaths(ts.removeFileExtension(subModuleName), removeExtensionAndIndexPostFix(subModuleName, 0 /* Minimal */, options), versionPaths.paths);
104907                         if (fromPaths !== undefined) {
104908                             moduleFileToTry = ts.combinePaths(packageRootPath, fromPaths);
104909                         }
104910                     }
104911                     // If the file is the main module, it can be imported by the package name
104912                     var mainFileRelative = packageJsonContent.typings || packageJsonContent.types || packageJsonContent.main;
104913                     if (ts.isString(mainFileRelative)) {
104914                         var mainExportFile = ts.toPath(mainFileRelative, packageRootPath, getCanonicalFileName);
104915                         if (ts.removeFileExtension(mainExportFile) === ts.removeFileExtension(getCanonicalFileName(moduleFileToTry))) {
104916                             return { packageRootPath: packageRootPath, moduleFileToTry: moduleFileToTry };
104917                         }
104918                     }
104919                 }
104920                 return { moduleFileToTry: moduleFileToTry };
104921             }
104922             function getExtensionlessFileName(path) {
104923                 // We still have a file name - remove the extension
104924                 var fullModulePathWithoutExtension = ts.removeFileExtension(path);
104925                 // If the file is /index, it can be imported by its directory name
104926                 // IFF there is not _also_ a file by the same name
104927                 if (getCanonicalFileName(fullModulePathWithoutExtension.substring(parts.fileNameIndex)) === "/index" && !tryGetAnyFileFromPath(host, fullModulePathWithoutExtension.substring(0, parts.fileNameIndex))) {
104928                     return fullModulePathWithoutExtension.substring(0, parts.fileNameIndex);
104929                 }
104930                 return fullModulePathWithoutExtension;
104931             }
104932         }
104933         function tryGetAnyFileFromPath(host, path) {
104934             if (!host.fileExists)
104935                 return;
104936             // We check all js, `node` and `json` extensions in addition to TS, since node module resolution would also choose those over the directory
104937             var extensions = ts.getSupportedExtensions({ allowJs: true }, [{ extension: "node", isMixedContent: false }, { extension: "json", isMixedContent: false, scriptKind: 6 /* JSON */ }]);
104938             for (var _i = 0, extensions_3 = extensions; _i < extensions_3.length; _i++) {
104939                 var e = extensions_3[_i];
104940                 var fullPath = path + e;
104941                 if (host.fileExists(fullPath)) {
104942                     return fullPath;
104943                 }
104944             }
104945         }
104946         function getNodeModulePathParts(fullPath) {
104947             // If fullPath can't be valid module file within node_modules, returns undefined.
104948             // Example of expected pattern: /base/path/node_modules/[@scope/otherpackage/@otherscope/node_modules/]package/[subdirectory/]file.js
104949             // Returns indices:                       ^            ^                                                      ^             ^
104950             var topLevelNodeModulesIndex = 0;
104951             var topLevelPackageNameIndex = 0;
104952             var packageRootIndex = 0;
104953             var fileNameIndex = 0;
104954             var States;
104955             (function (States) {
104956                 States[States["BeforeNodeModules"] = 0] = "BeforeNodeModules";
104957                 States[States["NodeModules"] = 1] = "NodeModules";
104958                 States[States["Scope"] = 2] = "Scope";
104959                 States[States["PackageContent"] = 3] = "PackageContent";
104960             })(States || (States = {}));
104961             var partStart = 0;
104962             var partEnd = 0;
104963             var state = 0 /* BeforeNodeModules */;
104964             while (partEnd >= 0) {
104965                 partStart = partEnd;
104966                 partEnd = fullPath.indexOf("/", partStart + 1);
104967                 switch (state) {
104968                     case 0 /* BeforeNodeModules */:
104969                         if (fullPath.indexOf(ts.nodeModulesPathPart, partStart) === partStart) {
104970                             topLevelNodeModulesIndex = partStart;
104971                             topLevelPackageNameIndex = partEnd;
104972                             state = 1 /* NodeModules */;
104973                         }
104974                         break;
104975                     case 1 /* NodeModules */:
104976                     case 2 /* Scope */:
104977                         if (state === 1 /* NodeModules */ && fullPath.charAt(partStart + 1) === "@") {
104978                             state = 2 /* Scope */;
104979                         }
104980                         else {
104981                             packageRootIndex = partEnd;
104982                             state = 3 /* PackageContent */;
104983                         }
104984                         break;
104985                     case 3 /* PackageContent */:
104986                         if (fullPath.indexOf(ts.nodeModulesPathPart, partStart) === partStart) {
104987                             state = 1 /* NodeModules */;
104988                         }
104989                         else {
104990                             state = 3 /* PackageContent */;
104991                         }
104992                         break;
104993                 }
104994             }
104995             fileNameIndex = partStart;
104996             return state > 1 /* NodeModules */ ? { topLevelNodeModulesIndex: topLevelNodeModulesIndex, topLevelPackageNameIndex: topLevelPackageNameIndex, packageRootIndex: packageRootIndex, fileNameIndex: fileNameIndex } : undefined;
104997         }
104998         function getPathRelativeToRootDirs(path, rootDirs, getCanonicalFileName) {
104999             return ts.firstDefined(rootDirs, function (rootDir) {
105000                 var relativePath = getRelativePathIfInDirectory(path, rootDir, getCanonicalFileName); // TODO: GH#18217
105001                 return isPathRelativeToParent(relativePath) ? undefined : relativePath;
105002             });
105003         }
105004         function removeExtensionAndIndexPostFix(fileName, ending, options) {
105005             if (ts.fileExtensionIs(fileName, ".json" /* Json */))
105006                 return fileName;
105007             var noExtension = ts.removeFileExtension(fileName);
105008             switch (ending) {
105009                 case 0 /* Minimal */:
105010                     return ts.removeSuffix(noExtension, "/index");
105011                 case 1 /* Index */:
105012                     return noExtension;
105013                 case 2 /* JsExtension */:
105014                     return noExtension + getJSExtensionForFile(fileName, options);
105015                 default:
105016                     return ts.Debug.assertNever(ending);
105017             }
105018         }
105019         function getJSExtensionForFile(fileName, options) {
105020             var ext = ts.extensionFromPath(fileName);
105021             switch (ext) {
105022                 case ".ts" /* Ts */:
105023                 case ".d.ts" /* Dts */:
105024                     return ".js" /* Js */;
105025                 case ".tsx" /* Tsx */:
105026                     return options.jsx === 1 /* Preserve */ ? ".jsx" /* Jsx */ : ".js" /* Js */;
105027                 case ".js" /* Js */:
105028                 case ".jsx" /* Jsx */:
105029                 case ".json" /* Json */:
105030                     return ext;
105031                 case ".tsbuildinfo" /* TsBuildInfo */:
105032                     return ts.Debug.fail("Extension " + ".tsbuildinfo" /* TsBuildInfo */ + " is unsupported:: FileName:: " + fileName);
105033                 default:
105034                     return ts.Debug.assertNever(ext);
105035             }
105036         }
105037         function getRelativePathIfInDirectory(path, directoryPath, getCanonicalFileName) {
105038             var relativePath = ts.getRelativePathToDirectoryOrUrl(directoryPath, path, directoryPath, getCanonicalFileName, /*isAbsolutePathAnUrl*/ false);
105039             return ts.isRootedDiskPath(relativePath) ? undefined : relativePath;
105040         }
105041         function isPathRelativeToParent(path) {
105042             return ts.startsWith(path, "..");
105043         }
105044     })(moduleSpecifiers = ts.moduleSpecifiers || (ts.moduleSpecifiers = {}));
105045 })(ts || (ts = {}));
105046 /*@internal*/
105047 var ts;
105048 (function (ts) {
105049     var sysFormatDiagnosticsHost = ts.sys ? {
105050         getCurrentDirectory: function () { return ts.sys.getCurrentDirectory(); },
105051         getNewLine: function () { return ts.sys.newLine; },
105052         getCanonicalFileName: ts.createGetCanonicalFileName(ts.sys.useCaseSensitiveFileNames)
105053     } : undefined; // TODO: GH#18217
105054     /**
105055      * Create a function that reports error by writing to the system and handles the formating of the diagnostic
105056      */
105057     function createDiagnosticReporter(system, pretty) {
105058         var host = system === ts.sys ? sysFormatDiagnosticsHost : {
105059             getCurrentDirectory: function () { return system.getCurrentDirectory(); },
105060             getNewLine: function () { return system.newLine; },
105061             getCanonicalFileName: ts.createGetCanonicalFileName(system.useCaseSensitiveFileNames),
105062         };
105063         if (!pretty) {
105064             return function (diagnostic) { return system.write(ts.formatDiagnostic(diagnostic, host)); };
105065         }
105066         var diagnostics = new Array(1);
105067         return function (diagnostic) {
105068             diagnostics[0] = diagnostic;
105069             system.write(ts.formatDiagnosticsWithColorAndContext(diagnostics, host) + host.getNewLine());
105070             diagnostics[0] = undefined; // TODO: GH#18217
105071         };
105072     }
105073     ts.createDiagnosticReporter = createDiagnosticReporter;
105074     /**
105075      * @returns Whether the screen was cleared.
105076      */
105077     function clearScreenIfNotWatchingForFileChanges(system, diagnostic, options) {
105078         if (system.clearScreen &&
105079             !options.preserveWatchOutput &&
105080             !options.extendedDiagnostics &&
105081             !options.diagnostics &&
105082             ts.contains(ts.screenStartingMessageCodes, diagnostic.code)) {
105083             system.clearScreen();
105084             return true;
105085         }
105086         return false;
105087     }
105088     ts.screenStartingMessageCodes = [
105089         ts.Diagnostics.Starting_compilation_in_watch_mode.code,
105090         ts.Diagnostics.File_change_detected_Starting_incremental_compilation.code,
105091     ];
105092     function getPlainDiagnosticFollowingNewLines(diagnostic, newLine) {
105093         return ts.contains(ts.screenStartingMessageCodes, diagnostic.code)
105094             ? newLine + newLine
105095             : newLine;
105096     }
105097     /**
105098      * Get locale specific time based on whether we are in test mode
105099      */
105100     function getLocaleTimeString(system) {
105101         return !system.now ?
105102             new Date().toLocaleTimeString() :
105103             system.now().toLocaleTimeString("en-US", { timeZone: "UTC" });
105104     }
105105     ts.getLocaleTimeString = getLocaleTimeString;
105106     /**
105107      * Create a function that reports watch status by writing to the system and handles the formating of the diagnostic
105108      */
105109     function createWatchStatusReporter(system, pretty) {
105110         return pretty ?
105111             function (diagnostic, newLine, options) {
105112                 clearScreenIfNotWatchingForFileChanges(system, diagnostic, options);
105113                 var output = "[" + ts.formatColorAndReset(getLocaleTimeString(system), ts.ForegroundColorEscapeSequences.Grey) + "] ";
105114                 output += "" + ts.flattenDiagnosticMessageText(diagnostic.messageText, system.newLine) + (newLine + newLine);
105115                 system.write(output);
105116             } :
105117             function (diagnostic, newLine, options) {
105118                 var output = "";
105119                 if (!clearScreenIfNotWatchingForFileChanges(system, diagnostic, options)) {
105120                     output += newLine;
105121                 }
105122                 output += getLocaleTimeString(system) + " - ";
105123                 output += "" + ts.flattenDiagnosticMessageText(diagnostic.messageText, system.newLine) + getPlainDiagnosticFollowingNewLines(diagnostic, newLine);
105124                 system.write(output);
105125             };
105126     }
105127     ts.createWatchStatusReporter = createWatchStatusReporter;
105128     /** Parses config file using System interface */
105129     function parseConfigFileWithSystem(configFileName, optionsToExtend, watchOptionsToExtend, system, reportDiagnostic) {
105130         var host = system;
105131         host.onUnRecoverableConfigFileDiagnostic = function (diagnostic) { return reportUnrecoverableDiagnostic(system, reportDiagnostic, diagnostic); };
105132         var result = ts.getParsedCommandLineOfConfigFile(configFileName, optionsToExtend, host, /*extendedConfigCache*/ undefined, watchOptionsToExtend);
105133         host.onUnRecoverableConfigFileDiagnostic = undefined; // TODO: GH#18217
105134         return result;
105135     }
105136     ts.parseConfigFileWithSystem = parseConfigFileWithSystem;
105137     function getErrorCountForSummary(diagnostics) {
105138         return ts.countWhere(diagnostics, function (diagnostic) { return diagnostic.category === ts.DiagnosticCategory.Error; });
105139     }
105140     ts.getErrorCountForSummary = getErrorCountForSummary;
105141     function getWatchErrorSummaryDiagnosticMessage(errorCount) {
105142         return errorCount === 1 ?
105143             ts.Diagnostics.Found_1_error_Watching_for_file_changes :
105144             ts.Diagnostics.Found_0_errors_Watching_for_file_changes;
105145     }
105146     ts.getWatchErrorSummaryDiagnosticMessage = getWatchErrorSummaryDiagnosticMessage;
105147     function getErrorSummaryText(errorCount, newLine) {
105148         if (errorCount === 0)
105149             return "";
105150         var d = ts.createCompilerDiagnostic(errorCount === 1 ? ts.Diagnostics.Found_1_error : ts.Diagnostics.Found_0_errors, errorCount);
105151         return "" + newLine + ts.flattenDiagnosticMessageText(d.messageText, newLine) + newLine + newLine;
105152     }
105153     ts.getErrorSummaryText = getErrorSummaryText;
105154     function listFiles(program, writeFileName) {
105155         if (program.getCompilerOptions().listFiles || program.getCompilerOptions().listFilesOnly) {
105156             ts.forEach(program.getSourceFiles(), function (file) {
105157                 writeFileName(file.fileName);
105158             });
105159         }
105160     }
105161     ts.listFiles = listFiles;
105162     /**
105163      * Helper that emit files, report diagnostics and lists emitted and/or source files depending on compiler options
105164      */
105165     function emitFilesAndReportErrors(program, reportDiagnostic, writeFileName, reportSummary, writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers) {
105166         var isListFilesOnly = !!program.getCompilerOptions().listFilesOnly;
105167         // First get and report any syntactic errors.
105168         var allDiagnostics = program.getConfigFileParsingDiagnostics().slice();
105169         var configFileParsingDiagnosticsLength = allDiagnostics.length;
105170         ts.addRange(allDiagnostics, program.getSyntacticDiagnostics(/*sourceFile*/ undefined, cancellationToken));
105171         // If we didn't have any syntactic errors, then also try getting the global and
105172         // semantic errors.
105173         if (allDiagnostics.length === configFileParsingDiagnosticsLength) {
105174             ts.addRange(allDiagnostics, program.getOptionsDiagnostics(cancellationToken));
105175             if (!isListFilesOnly) {
105176                 ts.addRange(allDiagnostics, program.getGlobalDiagnostics(cancellationToken));
105177                 if (allDiagnostics.length === configFileParsingDiagnosticsLength) {
105178                     ts.addRange(allDiagnostics, program.getSemanticDiagnostics(/*sourceFile*/ undefined, cancellationToken));
105179                 }
105180             }
105181         }
105182         // Emit and report any errors we ran into.
105183         var emitResult = isListFilesOnly
105184             ? { emitSkipped: true, diagnostics: ts.emptyArray }
105185             : program.emit(/*targetSourceFile*/ undefined, writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers);
105186         var emittedFiles = emitResult.emittedFiles, emitDiagnostics = emitResult.diagnostics;
105187         ts.addRange(allDiagnostics, emitDiagnostics);
105188         var diagnostics = ts.sortAndDeduplicateDiagnostics(allDiagnostics);
105189         diagnostics.forEach(reportDiagnostic);
105190         if (writeFileName) {
105191             var currentDir_1 = program.getCurrentDirectory();
105192             ts.forEach(emittedFiles, function (file) {
105193                 var filepath = ts.getNormalizedAbsolutePath(file, currentDir_1);
105194                 writeFileName("TSFILE: " + filepath);
105195             });
105196             listFiles(program, writeFileName);
105197         }
105198         if (reportSummary) {
105199             reportSummary(getErrorCountForSummary(diagnostics));
105200         }
105201         return {
105202             emitResult: emitResult,
105203             diagnostics: diagnostics,
105204         };
105205     }
105206     ts.emitFilesAndReportErrors = emitFilesAndReportErrors;
105207     function emitFilesAndReportErrorsAndGetExitStatus(program, reportDiagnostic, writeFileName, reportSummary, writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers) {
105208         var _a = emitFilesAndReportErrors(program, reportDiagnostic, writeFileName, reportSummary, writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers), emitResult = _a.emitResult, diagnostics = _a.diagnostics;
105209         if (emitResult.emitSkipped && diagnostics.length > 0) {
105210             // If the emitter didn't emit anything, then pass that value along.
105211             return ts.ExitStatus.DiagnosticsPresent_OutputsSkipped;
105212         }
105213         else if (diagnostics.length > 0) {
105214             // The emitter emitted something, inform the caller if that happened in the presence
105215             // of diagnostics or not.
105216             return ts.ExitStatus.DiagnosticsPresent_OutputsGenerated;
105217         }
105218         return ts.ExitStatus.Success;
105219     }
105220     ts.emitFilesAndReportErrorsAndGetExitStatus = emitFilesAndReportErrorsAndGetExitStatus;
105221     ts.noopFileWatcher = { close: ts.noop };
105222     function createWatchHost(system, reportWatchStatus) {
105223         if (system === void 0) { system = ts.sys; }
105224         var onWatchStatusChange = reportWatchStatus || createWatchStatusReporter(system);
105225         return {
105226             onWatchStatusChange: onWatchStatusChange,
105227             watchFile: ts.maybeBind(system, system.watchFile) || (function () { return ts.noopFileWatcher; }),
105228             watchDirectory: ts.maybeBind(system, system.watchDirectory) || (function () { return ts.noopFileWatcher; }),
105229             setTimeout: ts.maybeBind(system, system.setTimeout) || ts.noop,
105230             clearTimeout: ts.maybeBind(system, system.clearTimeout) || ts.noop
105231         };
105232     }
105233     ts.createWatchHost = createWatchHost;
105234     ts.WatchType = {
105235         ConfigFile: "Config file",
105236         SourceFile: "Source file",
105237         MissingFile: "Missing file",
105238         WildcardDirectory: "Wild card directory",
105239         FailedLookupLocations: "Failed Lookup Locations",
105240         TypeRoots: "Type roots"
105241     };
105242     function createWatchFactory(host, options) {
105243         var watchLogLevel = host.trace ? options.extendedDiagnostics ? ts.WatchLogLevel.Verbose : options.diagnostics ? ts.WatchLogLevel.TriggerOnly : ts.WatchLogLevel.None : ts.WatchLogLevel.None;
105244         var writeLog = watchLogLevel !== ts.WatchLogLevel.None ? (function (s) { return host.trace(s); }) : ts.noop;
105245         var result = ts.getWatchFactory(watchLogLevel, writeLog);
105246         result.writeLog = writeLog;
105247         return result;
105248     }
105249     ts.createWatchFactory = createWatchFactory;
105250     function createCompilerHostFromProgramHost(host, getCompilerOptions, directoryStructureHost) {
105251         if (directoryStructureHost === void 0) { directoryStructureHost = host; }
105252         var useCaseSensitiveFileNames = host.useCaseSensitiveFileNames();
105253         var hostGetNewLine = ts.memoize(function () { return host.getNewLine(); });
105254         return {
105255             getSourceFile: function (fileName, languageVersion, onError) {
105256                 var text;
105257                 try {
105258                     ts.performance.mark("beforeIORead");
105259                     text = host.readFile(fileName, getCompilerOptions().charset);
105260                     ts.performance.mark("afterIORead");
105261                     ts.performance.measure("I/O Read", "beforeIORead", "afterIORead");
105262                 }
105263                 catch (e) {
105264                     if (onError) {
105265                         onError(e.message);
105266                     }
105267                     text = "";
105268                 }
105269                 return text !== undefined ? ts.createSourceFile(fileName, text, languageVersion) : undefined;
105270             },
105271             getDefaultLibLocation: ts.maybeBind(host, host.getDefaultLibLocation),
105272             getDefaultLibFileName: function (options) { return host.getDefaultLibFileName(options); },
105273             writeFile: writeFile,
105274             getCurrentDirectory: ts.memoize(function () { return host.getCurrentDirectory(); }),
105275             useCaseSensitiveFileNames: function () { return useCaseSensitiveFileNames; },
105276             getCanonicalFileName: ts.createGetCanonicalFileName(useCaseSensitiveFileNames),
105277             getNewLine: function () { return ts.getNewLineCharacter(getCompilerOptions(), hostGetNewLine); },
105278             fileExists: function (f) { return host.fileExists(f); },
105279             readFile: function (f) { return host.readFile(f); },
105280             trace: ts.maybeBind(host, host.trace),
105281             directoryExists: ts.maybeBind(directoryStructureHost, directoryStructureHost.directoryExists),
105282             getDirectories: ts.maybeBind(directoryStructureHost, directoryStructureHost.getDirectories),
105283             realpath: ts.maybeBind(host, host.realpath),
105284             getEnvironmentVariable: ts.maybeBind(host, host.getEnvironmentVariable) || (function () { return ""; }),
105285             createHash: ts.maybeBind(host, host.createHash),
105286             readDirectory: ts.maybeBind(host, host.readDirectory),
105287         };
105288         function writeFile(fileName, text, writeByteOrderMark, onError) {
105289             try {
105290                 ts.performance.mark("beforeIOWrite");
105291                 // NOTE: If patchWriteFileEnsuringDirectory has been called,
105292                 // the host.writeFile will do its own directory creation and
105293                 // the ensureDirectoriesExist call will always be redundant.
105294                 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); });
105295                 ts.performance.mark("afterIOWrite");
105296                 ts.performance.measure("I/O Write", "beforeIOWrite", "afterIOWrite");
105297             }
105298             catch (e) {
105299                 if (onError) {
105300                     onError(e.message);
105301                 }
105302             }
105303         }
105304     }
105305     ts.createCompilerHostFromProgramHost = createCompilerHostFromProgramHost;
105306     function setGetSourceFileAsHashVersioned(compilerHost, host) {
105307         var originalGetSourceFile = compilerHost.getSourceFile;
105308         var computeHash = host.createHash || ts.generateDjb2Hash;
105309         compilerHost.getSourceFile = function () {
105310             var args = [];
105311             for (var _i = 0; _i < arguments.length; _i++) {
105312                 args[_i] = arguments[_i];
105313             }
105314             var result = originalGetSourceFile.call.apply(originalGetSourceFile, __spreadArrays([compilerHost], args));
105315             if (result) {
105316                 result.version = computeHash.call(host, result.text);
105317             }
105318             return result;
105319         };
105320     }
105321     ts.setGetSourceFileAsHashVersioned = setGetSourceFileAsHashVersioned;
105322     /**
105323      * Creates the watch compiler host that can be extended with config file or root file names and options host
105324      */
105325     function createProgramHost(system, createProgram) {
105326         var getDefaultLibLocation = ts.memoize(function () { return ts.getDirectoryPath(ts.normalizePath(system.getExecutingFilePath())); });
105327         return {
105328             useCaseSensitiveFileNames: function () { return system.useCaseSensitiveFileNames; },
105329             getNewLine: function () { return system.newLine; },
105330             getCurrentDirectory: ts.memoize(function () { return system.getCurrentDirectory(); }),
105331             getDefaultLibLocation: getDefaultLibLocation,
105332             getDefaultLibFileName: function (options) { return ts.combinePaths(getDefaultLibLocation(), ts.getDefaultLibFileName(options)); },
105333             fileExists: function (path) { return system.fileExists(path); },
105334             readFile: function (path, encoding) { return system.readFile(path, encoding); },
105335             directoryExists: function (path) { return system.directoryExists(path); },
105336             getDirectories: function (path) { return system.getDirectories(path); },
105337             readDirectory: function (path, extensions, exclude, include, depth) { return system.readDirectory(path, extensions, exclude, include, depth); },
105338             realpath: ts.maybeBind(system, system.realpath),
105339             getEnvironmentVariable: ts.maybeBind(system, system.getEnvironmentVariable),
105340             trace: function (s) { return system.write(s + system.newLine); },
105341             createDirectory: function (path) { return system.createDirectory(path); },
105342             writeFile: function (path, data, writeByteOrderMark) { return system.writeFile(path, data, writeByteOrderMark); },
105343             createHash: ts.maybeBind(system, system.createHash),
105344             createProgram: createProgram || ts.createEmitAndSemanticDiagnosticsBuilderProgram
105345         };
105346     }
105347     ts.createProgramHost = createProgramHost;
105348     /**
105349      * Creates the watch compiler host that can be extended with config file or root file names and options host
105350      */
105351     function createWatchCompilerHost(system, createProgram, reportDiagnostic, reportWatchStatus) {
105352         if (system === void 0) { system = ts.sys; }
105353         var writeFileName = function (s) { return system.write(s + system.newLine); };
105354         var result = createProgramHost(system, createProgram);
105355         ts.copyProperties(result, createWatchHost(system, reportWatchStatus));
105356         result.afterProgramCreate = function (builderProgram) {
105357             var compilerOptions = builderProgram.getCompilerOptions();
105358             var newLine = ts.getNewLineCharacter(compilerOptions, function () { return system.newLine; });
105359             emitFilesAndReportErrors(builderProgram, reportDiagnostic, writeFileName, function (errorCount) { return result.onWatchStatusChange(ts.createCompilerDiagnostic(getWatchErrorSummaryDiagnosticMessage(errorCount), errorCount), newLine, compilerOptions, errorCount); });
105360         };
105361         return result;
105362     }
105363     /**
105364      * Report error and exit
105365      */
105366     function reportUnrecoverableDiagnostic(system, reportDiagnostic, diagnostic) {
105367         reportDiagnostic(diagnostic);
105368         system.exit(ts.ExitStatus.DiagnosticsPresent_OutputsSkipped);
105369     }
105370     /**
105371      * Creates the watch compiler host from system for config file in watch mode
105372      */
105373     function createWatchCompilerHostOfConfigFile(_a) {
105374         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;
105375         var diagnosticReporter = reportDiagnostic || createDiagnosticReporter(system);
105376         var host = createWatchCompilerHost(system, createProgram, diagnosticReporter, reportWatchStatus);
105377         host.onUnRecoverableConfigFileDiagnostic = function (diagnostic) { return reportUnrecoverableDiagnostic(system, diagnosticReporter, diagnostic); };
105378         host.configFileName = configFileName;
105379         host.optionsToExtend = optionsToExtend;
105380         host.watchOptionsToExtend = watchOptionsToExtend;
105381         host.extraFileExtensions = extraFileExtensions;
105382         return host;
105383     }
105384     ts.createWatchCompilerHostOfConfigFile = createWatchCompilerHostOfConfigFile;
105385     /**
105386      * Creates the watch compiler host from system for compiling root files and options in watch mode
105387      */
105388     function createWatchCompilerHostOfFilesAndCompilerOptions(_a) {
105389         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;
105390         var host = createWatchCompilerHost(system, createProgram, reportDiagnostic || createDiagnosticReporter(system), reportWatchStatus);
105391         host.rootFiles = rootFiles;
105392         host.options = options;
105393         host.watchOptions = watchOptions;
105394         host.projectReferences = projectReferences;
105395         return host;
105396     }
105397     ts.createWatchCompilerHostOfFilesAndCompilerOptions = createWatchCompilerHostOfFilesAndCompilerOptions;
105398     function performIncrementalCompilation(input) {
105399         var system = input.system || ts.sys;
105400         var host = input.host || (input.host = ts.createIncrementalCompilerHost(input.options, system));
105401         var builderProgram = ts.createIncrementalProgram(input);
105402         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);
105403         if (input.afterProgramEmitAndDiagnostics)
105404             input.afterProgramEmitAndDiagnostics(builderProgram);
105405         return exitStatus;
105406     }
105407     ts.performIncrementalCompilation = performIncrementalCompilation;
105408 })(ts || (ts = {}));
105409 var ts;
105410 (function (ts) {
105411     function readBuilderProgram(compilerOptions, host) {
105412         if (compilerOptions.out || compilerOptions.outFile)
105413             return undefined;
105414         var buildInfoPath = ts.getTsBuildInfoEmitOutputFilePath(compilerOptions);
105415         if (!buildInfoPath)
105416             return undefined;
105417         var content = host.readFile(buildInfoPath);
105418         if (!content)
105419             return undefined;
105420         var buildInfo = ts.getBuildInfo(content);
105421         if (buildInfo.version !== ts.version)
105422             return undefined;
105423         if (!buildInfo.program)
105424             return undefined;
105425         return ts.createBuildProgramUsingProgramBuildInfo(buildInfo.program, buildInfoPath, host);
105426     }
105427     ts.readBuilderProgram = readBuilderProgram;
105428     function createIncrementalCompilerHost(options, system) {
105429         if (system === void 0) { system = ts.sys; }
105430         var host = ts.createCompilerHostWorker(options, /*setParentNodes*/ undefined, system);
105431         host.createHash = ts.maybeBind(system, system.createHash);
105432         ts.setGetSourceFileAsHashVersioned(host, system);
105433         ts.changeCompilerHostLikeToUseCache(host, function (fileName) { return ts.toPath(fileName, host.getCurrentDirectory(), host.getCanonicalFileName); });
105434         return host;
105435     }
105436     ts.createIncrementalCompilerHost = createIncrementalCompilerHost;
105437     function createIncrementalProgram(_a) {
105438         var rootNames = _a.rootNames, options = _a.options, configFileParsingDiagnostics = _a.configFileParsingDiagnostics, projectReferences = _a.projectReferences, host = _a.host, createProgram = _a.createProgram;
105439         host = host || createIncrementalCompilerHost(options);
105440         createProgram = createProgram || ts.createEmitAndSemanticDiagnosticsBuilderProgram;
105441         var oldProgram = readBuilderProgram(options, host);
105442         return createProgram(rootNames, options, host, oldProgram, configFileParsingDiagnostics, projectReferences);
105443     }
105444     ts.createIncrementalProgram = createIncrementalProgram;
105445     function createWatchCompilerHost(rootFilesOrConfigFileName, options, system, createProgram, reportDiagnostic, reportWatchStatus, projectReferencesOrWatchOptionsToExtend, watchOptionsOrExtraFileExtensions) {
105446         if (ts.isArray(rootFilesOrConfigFileName)) {
105447             return ts.createWatchCompilerHostOfFilesAndCompilerOptions({
105448                 rootFiles: rootFilesOrConfigFileName,
105449                 options: options,
105450                 watchOptions: watchOptionsOrExtraFileExtensions,
105451                 projectReferences: projectReferencesOrWatchOptionsToExtend,
105452                 system: system,
105453                 createProgram: createProgram,
105454                 reportDiagnostic: reportDiagnostic,
105455                 reportWatchStatus: reportWatchStatus,
105456             });
105457         }
105458         else {
105459             return ts.createWatchCompilerHostOfConfigFile({
105460                 configFileName: rootFilesOrConfigFileName,
105461                 optionsToExtend: options,
105462                 watchOptionsToExtend: projectReferencesOrWatchOptionsToExtend,
105463                 extraFileExtensions: watchOptionsOrExtraFileExtensions,
105464                 system: system,
105465                 createProgram: createProgram,
105466                 reportDiagnostic: reportDiagnostic,
105467                 reportWatchStatus: reportWatchStatus,
105468             });
105469         }
105470     }
105471     ts.createWatchCompilerHost = createWatchCompilerHost;
105472     function createWatchProgram(host) {
105473         var builderProgram;
105474         var reloadLevel; // level to indicate if the program needs to be reloaded from config file/just filenames etc
105475         var missingFilesMap; // Map of file watchers for the missing files
105476         var watchedWildcardDirectories; // map of watchers for the wild card directories in the config file
105477         var timerToUpdateProgram; // timer callback to recompile the program
105478         var sourceFilesCache = ts.createMap(); // Cache that stores the source file and version info
105479         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
105480         var hasChangedCompilerOptions = false; // True if the compiler options have changed between compilations
105481         var hasChangedAutomaticTypeDirectiveNames = false; // True if the automatic type directives have changed
105482         var useCaseSensitiveFileNames = host.useCaseSensitiveFileNames();
105483         var currentDirectory = host.getCurrentDirectory();
105484         var configFileName = host.configFileName, _a = host.optionsToExtend, optionsToExtendForConfigFile = _a === void 0 ? {} : _a, watchOptionsToExtend = host.watchOptionsToExtend, extraFileExtensions = host.extraFileExtensions, createProgram = host.createProgram;
105485         var rootFileNames = host.rootFiles, compilerOptions = host.options, watchOptions = host.watchOptions, projectReferences = host.projectReferences;
105486         var configFileSpecs;
105487         var configFileParsingDiagnostics;
105488         var canConfigFileJsonReportNoInputFiles = false;
105489         var hasChangedConfigFileParsingErrors = false;
105490         var cachedDirectoryStructureHost = configFileName === undefined ? undefined : ts.createCachedDirectoryStructureHost(host, currentDirectory, useCaseSensitiveFileNames);
105491         var directoryStructureHost = cachedDirectoryStructureHost || host;
105492         var parseConfigFileHost = ts.parseConfigHostFromCompilerHostLike(host, directoryStructureHost);
105493         // From tsc we want to get already parsed result and hence check for rootFileNames
105494         var newLine = updateNewLine();
105495         if (configFileName && host.configFileParsingResult) {
105496             setConfigFileParsingResult(host.configFileParsingResult);
105497             newLine = updateNewLine();
105498         }
105499         reportWatchDiagnostic(ts.Diagnostics.Starting_compilation_in_watch_mode);
105500         if (configFileName && !host.configFileParsingResult) {
105501             newLine = ts.getNewLineCharacter(optionsToExtendForConfigFile, function () { return host.getNewLine(); });
105502             ts.Debug.assert(!rootFileNames);
105503             parseConfigFile();
105504             newLine = updateNewLine();
105505         }
105506         var _b = ts.createWatchFactory(host, compilerOptions), watchFile = _b.watchFile, watchFilePath = _b.watchFilePath, watchDirectory = _b.watchDirectory, writeLog = _b.writeLog;
105507         var getCanonicalFileName = ts.createGetCanonicalFileName(useCaseSensitiveFileNames);
105508         writeLog("Current directory: " + currentDirectory + " CaseSensitiveFileNames: " + useCaseSensitiveFileNames);
105509         var configFileWatcher;
105510         if (configFileName) {
105511             configFileWatcher = watchFile(host, configFileName, scheduleProgramReload, ts.PollingInterval.High, watchOptions, ts.WatchType.ConfigFile);
105512         }
105513         var compilerHost = ts.createCompilerHostFromProgramHost(host, function () { return compilerOptions; }, directoryStructureHost);
105514         ts.setGetSourceFileAsHashVersioned(compilerHost, host);
105515         // Members for CompilerHost
105516         var getNewSourceFile = compilerHost.getSourceFile;
105517         compilerHost.getSourceFile = function (fileName) {
105518             var args = [];
105519             for (var _i = 1; _i < arguments.length; _i++) {
105520                 args[_i - 1] = arguments[_i];
105521             }
105522             return getVersionedSourceFileByPath.apply(void 0, __spreadArrays([fileName, toPath(fileName)], args));
105523         };
105524         compilerHost.getSourceFileByPath = getVersionedSourceFileByPath;
105525         compilerHost.getNewLine = function () { return newLine; };
105526         compilerHost.fileExists = fileExists;
105527         compilerHost.onReleaseOldSourceFile = onReleaseOldSourceFile;
105528         // Members for ResolutionCacheHost
105529         compilerHost.toPath = toPath;
105530         compilerHost.getCompilationSettings = function () { return compilerOptions; };
105531         compilerHost.useSourceOfProjectReferenceRedirect = ts.maybeBind(host, host.useSourceOfProjectReferenceRedirect);
105532         compilerHost.watchDirectoryOfFailedLookupLocation = function (dir, cb, flags) { return watchDirectory(host, dir, cb, flags, watchOptions, ts.WatchType.FailedLookupLocations); };
105533         compilerHost.watchTypeRootsDirectory = function (dir, cb, flags) { return watchDirectory(host, dir, cb, flags, watchOptions, ts.WatchType.TypeRoots); };
105534         compilerHost.getCachedDirectoryStructureHost = function () { return cachedDirectoryStructureHost; };
105535         compilerHost.onInvalidatedResolution = scheduleProgramUpdate;
105536         compilerHost.onChangedAutomaticTypeDirectiveNames = function () {
105537             hasChangedAutomaticTypeDirectiveNames = true;
105538             scheduleProgramUpdate();
105539         };
105540         compilerHost.fileIsOpen = ts.returnFalse;
105541         compilerHost.getCurrentProgram = getCurrentProgram;
105542         compilerHost.writeLog = writeLog;
105543         // Cache for the module resolution
105544         var resolutionCache = ts.createResolutionCache(compilerHost, configFileName ?
105545             ts.getDirectoryPath(ts.getNormalizedAbsolutePath(configFileName, currentDirectory)) :
105546             currentDirectory, 
105547         /*logChangesWhenResolvingModule*/ false);
105548         // Resolve module using host module resolution strategy if provided otherwise use resolution cache to resolve module names
105549         compilerHost.resolveModuleNames = host.resolveModuleNames ?
105550             (function () {
105551                 var args = [];
105552                 for (var _i = 0; _i < arguments.length; _i++) {
105553                     args[_i] = arguments[_i];
105554                 }
105555                 return host.resolveModuleNames.apply(host, args);
105556             }) :
105557             (function (moduleNames, containingFile, reusedNames, redirectedReference) { return resolutionCache.resolveModuleNames(moduleNames, containingFile, reusedNames, redirectedReference); });
105558         compilerHost.resolveTypeReferenceDirectives = host.resolveTypeReferenceDirectives ?
105559             (function () {
105560                 var args = [];
105561                 for (var _i = 0; _i < arguments.length; _i++) {
105562                     args[_i] = arguments[_i];
105563                 }
105564                 return host.resolveTypeReferenceDirectives.apply(host, args);
105565             }) :
105566             (function (typeDirectiveNames, containingFile, redirectedReference) { return resolutionCache.resolveTypeReferenceDirectives(typeDirectiveNames, containingFile, redirectedReference); });
105567         var userProvidedResolution = !!host.resolveModuleNames || !!host.resolveTypeReferenceDirectives;
105568         builderProgram = readBuilderProgram(compilerOptions, compilerHost);
105569         synchronizeProgram();
105570         // Update the wild card directory watch
105571         watchConfigFileWildCardDirectories();
105572         return configFileName ?
105573             { getCurrentProgram: getCurrentBuilderProgram, getProgram: updateProgram, close: close } :
105574             { getCurrentProgram: getCurrentBuilderProgram, getProgram: updateProgram, updateRootFileNames: updateRootFileNames, close: close };
105575         function close() {
105576             resolutionCache.clear();
105577             ts.clearMap(sourceFilesCache, function (value) {
105578                 if (value && value.fileWatcher) {
105579                     value.fileWatcher.close();
105580                     value.fileWatcher = undefined;
105581                 }
105582             });
105583             if (configFileWatcher) {
105584                 configFileWatcher.close();
105585                 configFileWatcher = undefined;
105586             }
105587             if (watchedWildcardDirectories) {
105588                 ts.clearMap(watchedWildcardDirectories, ts.closeFileWatcherOf);
105589                 watchedWildcardDirectories = undefined;
105590             }
105591             if (missingFilesMap) {
105592                 ts.clearMap(missingFilesMap, ts.closeFileWatcher);
105593                 missingFilesMap = undefined;
105594             }
105595         }
105596         function getCurrentBuilderProgram() {
105597             return builderProgram;
105598         }
105599         function getCurrentProgram() {
105600             return builderProgram && builderProgram.getProgramOrUndefined();
105601         }
105602         function synchronizeProgram() {
105603             writeLog("Synchronizing program");
105604             var program = getCurrentBuilderProgram();
105605             if (hasChangedCompilerOptions) {
105606                 newLine = updateNewLine();
105607                 if (program && ts.changesAffectModuleResolution(program.getCompilerOptions(), compilerOptions)) {
105608                     resolutionCache.clear();
105609                 }
105610             }
105611             // All resolutions are invalid if user provided resolutions
105612             var hasInvalidatedResolution = resolutionCache.createHasInvalidatedResolution(userProvidedResolution);
105613             if (ts.isProgramUptoDate(getCurrentProgram(), rootFileNames, compilerOptions, getSourceVersion, fileExists, hasInvalidatedResolution, hasChangedAutomaticTypeDirectiveNames, projectReferences)) {
105614                 if (hasChangedConfigFileParsingErrors) {
105615                     builderProgram = createProgram(/*rootNames*/ undefined, /*options*/ undefined, compilerHost, builderProgram, configFileParsingDiagnostics, projectReferences);
105616                     hasChangedConfigFileParsingErrors = false;
105617                 }
105618             }
105619             else {
105620                 createNewProgram(hasInvalidatedResolution);
105621             }
105622             if (host.afterProgramCreate && program !== builderProgram) {
105623                 host.afterProgramCreate(builderProgram);
105624             }
105625             return builderProgram;
105626         }
105627         function createNewProgram(hasInvalidatedResolution) {
105628             // Compile the program
105629             writeLog("CreatingProgramWith::");
105630             writeLog("  roots: " + JSON.stringify(rootFileNames));
105631             writeLog("  options: " + JSON.stringify(compilerOptions));
105632             var needsUpdateInTypeRootWatch = hasChangedCompilerOptions || !getCurrentProgram();
105633             hasChangedCompilerOptions = false;
105634             hasChangedConfigFileParsingErrors = false;
105635             resolutionCache.startCachingPerDirectoryResolution();
105636             compilerHost.hasInvalidatedResolution = hasInvalidatedResolution;
105637             compilerHost.hasChangedAutomaticTypeDirectiveNames = hasChangedAutomaticTypeDirectiveNames;
105638             hasChangedAutomaticTypeDirectiveNames = false;
105639             builderProgram = createProgram(rootFileNames, compilerOptions, compilerHost, builderProgram, configFileParsingDiagnostics, projectReferences);
105640             resolutionCache.finishCachingPerDirectoryResolution();
105641             // Update watches
105642             ts.updateMissingFilePathsWatch(builderProgram.getProgram(), missingFilesMap || (missingFilesMap = ts.createMap()), watchMissingFilePath);
105643             if (needsUpdateInTypeRootWatch) {
105644                 resolutionCache.updateTypeRootsWatch();
105645             }
105646             if (missingFilePathsRequestedForRelease) {
105647                 // These are the paths that program creater told us as not in use any more but were missing on the disk.
105648                 // We didnt remove the entry for them from sourceFiles cache so that we dont have to do File IO,
105649                 // if there is already watcher for it (for missing files)
105650                 // At this point our watches were updated, hence now we know that these paths are not tracked and need to be removed
105651                 // so that at later time we have correct result of their presence
105652                 for (var _i = 0, missingFilePathsRequestedForRelease_1 = missingFilePathsRequestedForRelease; _i < missingFilePathsRequestedForRelease_1.length; _i++) {
105653                     var missingFilePath = missingFilePathsRequestedForRelease_1[_i];
105654                     if (!missingFilesMap.has(missingFilePath)) {
105655                         sourceFilesCache.delete(missingFilePath);
105656                     }
105657                 }
105658                 missingFilePathsRequestedForRelease = undefined;
105659             }
105660         }
105661         function updateRootFileNames(files) {
105662             ts.Debug.assert(!configFileName, "Cannot update root file names with config file watch mode");
105663             rootFileNames = files;
105664             scheduleProgramUpdate();
105665         }
105666         function updateNewLine() {
105667             return ts.getNewLineCharacter(compilerOptions || optionsToExtendForConfigFile, function () { return host.getNewLine(); });
105668         }
105669         function toPath(fileName) {
105670             return ts.toPath(fileName, currentDirectory, getCanonicalFileName);
105671         }
105672         function isFileMissingOnHost(hostSourceFile) {
105673             return typeof hostSourceFile === "boolean";
105674         }
105675         function isFilePresenceUnknownOnHost(hostSourceFile) {
105676             return typeof hostSourceFile.version === "boolean";
105677         }
105678         function fileExists(fileName) {
105679             var path = toPath(fileName);
105680             // If file is missing on host from cache, we can definitely say file doesnt exist
105681             // otherwise we need to ensure from the disk
105682             if (isFileMissingOnHost(sourceFilesCache.get(path))) {
105683                 return false;
105684             }
105685             return directoryStructureHost.fileExists(fileName);
105686         }
105687         function getVersionedSourceFileByPath(fileName, path, languageVersion, onError, shouldCreateNewSourceFile) {
105688             var hostSourceFile = sourceFilesCache.get(path);
105689             // No source file on the host
105690             if (isFileMissingOnHost(hostSourceFile)) {
105691                 return undefined;
105692             }
105693             // Create new source file if requested or the versions dont match
105694             if (hostSourceFile === undefined || shouldCreateNewSourceFile || isFilePresenceUnknownOnHost(hostSourceFile)) {
105695                 var sourceFile = getNewSourceFile(fileName, languageVersion, onError);
105696                 if (hostSourceFile) {
105697                     if (sourceFile) {
105698                         // Set the source file and create file watcher now that file was present on the disk
105699                         hostSourceFile.sourceFile = sourceFile;
105700                         hostSourceFile.version = sourceFile.version;
105701                         if (!hostSourceFile.fileWatcher) {
105702                             hostSourceFile.fileWatcher = watchFilePath(host, fileName, onSourceFileChange, ts.PollingInterval.Low, watchOptions, path, ts.WatchType.SourceFile);
105703                         }
105704                     }
105705                     else {
105706                         // There is no source file on host any more, close the watch, missing file paths will track it
105707                         if (hostSourceFile.fileWatcher) {
105708                             hostSourceFile.fileWatcher.close();
105709                         }
105710                         sourceFilesCache.set(path, false);
105711                     }
105712                 }
105713                 else {
105714                     if (sourceFile) {
105715                         var fileWatcher = watchFilePath(host, fileName, onSourceFileChange, ts.PollingInterval.Low, watchOptions, path, ts.WatchType.SourceFile);
105716                         sourceFilesCache.set(path, { sourceFile: sourceFile, version: sourceFile.version, fileWatcher: fileWatcher });
105717                     }
105718                     else {
105719                         sourceFilesCache.set(path, false);
105720                     }
105721                 }
105722                 return sourceFile;
105723             }
105724             return hostSourceFile.sourceFile;
105725         }
105726         function nextSourceFileVersion(path) {
105727             var hostSourceFile = sourceFilesCache.get(path);
105728             if (hostSourceFile !== undefined) {
105729                 if (isFileMissingOnHost(hostSourceFile)) {
105730                     // The next version, lets set it as presence unknown file
105731                     sourceFilesCache.set(path, { version: false });
105732                 }
105733                 else {
105734                     hostSourceFile.version = false;
105735                 }
105736             }
105737         }
105738         function getSourceVersion(path) {
105739             var hostSourceFile = sourceFilesCache.get(path);
105740             return !hostSourceFile || !hostSourceFile.version ? undefined : hostSourceFile.version;
105741         }
105742         function onReleaseOldSourceFile(oldSourceFile, _oldOptions, hasSourceFileByPath) {
105743             var hostSourceFileInfo = sourceFilesCache.get(oldSourceFile.resolvedPath);
105744             // If this is the source file thats in the cache and new program doesnt need it,
105745             // remove the cached entry.
105746             // Note we arent deleting entry if file became missing in new program or
105747             // there was version update and new source file was created.
105748             if (hostSourceFileInfo !== undefined) {
105749                 // record the missing file paths so they can be removed later if watchers arent tracking them
105750                 if (isFileMissingOnHost(hostSourceFileInfo)) {
105751                     (missingFilePathsRequestedForRelease || (missingFilePathsRequestedForRelease = [])).push(oldSourceFile.path);
105752                 }
105753                 else if (hostSourceFileInfo.sourceFile === oldSourceFile) {
105754                     if (hostSourceFileInfo.fileWatcher) {
105755                         hostSourceFileInfo.fileWatcher.close();
105756                     }
105757                     sourceFilesCache.delete(oldSourceFile.resolvedPath);
105758                     if (!hasSourceFileByPath) {
105759                         resolutionCache.removeResolutionsOfFile(oldSourceFile.path);
105760                     }
105761                 }
105762             }
105763         }
105764         function reportWatchDiagnostic(message) {
105765             if (host.onWatchStatusChange) {
105766                 host.onWatchStatusChange(ts.createCompilerDiagnostic(message), newLine, compilerOptions || optionsToExtendForConfigFile);
105767             }
105768         }
105769         // Upon detecting a file change, wait for 250ms and then perform a recompilation. This gives batch
105770         // operations (such as saving all modified files in an editor) a chance to complete before we kick
105771         // off a new compilation.
105772         function scheduleProgramUpdate() {
105773             if (!host.setTimeout || !host.clearTimeout) {
105774                 return;
105775             }
105776             if (timerToUpdateProgram) {
105777                 host.clearTimeout(timerToUpdateProgram);
105778             }
105779             writeLog("Scheduling update");
105780             timerToUpdateProgram = host.setTimeout(updateProgramWithWatchStatus, 250);
105781         }
105782         function scheduleProgramReload() {
105783             ts.Debug.assert(!!configFileName);
105784             reloadLevel = ts.ConfigFileProgramReloadLevel.Full;
105785             scheduleProgramUpdate();
105786         }
105787         function updateProgramWithWatchStatus() {
105788             timerToUpdateProgram = undefined;
105789             reportWatchDiagnostic(ts.Diagnostics.File_change_detected_Starting_incremental_compilation);
105790             updateProgram();
105791         }
105792         function updateProgram() {
105793             switch (reloadLevel) {
105794                 case ts.ConfigFileProgramReloadLevel.Partial:
105795                     ts.perfLogger.logStartUpdateProgram("PartialConfigReload");
105796                     reloadFileNamesFromConfigFile();
105797                     break;
105798                 case ts.ConfigFileProgramReloadLevel.Full:
105799                     ts.perfLogger.logStartUpdateProgram("FullConfigReload");
105800                     reloadConfigFile();
105801                     break;
105802                 default:
105803                     ts.perfLogger.logStartUpdateProgram("SynchronizeProgram");
105804                     synchronizeProgram();
105805                     break;
105806             }
105807             ts.perfLogger.logStopUpdateProgram("Done");
105808             return getCurrentBuilderProgram();
105809         }
105810         function reloadFileNamesFromConfigFile() {
105811             writeLog("Reloading new file names and options");
105812             var result = ts.getFileNamesFromConfigSpecs(configFileSpecs, ts.getNormalizedAbsolutePath(ts.getDirectoryPath(configFileName), currentDirectory), compilerOptions, parseConfigFileHost);
105813             if (ts.updateErrorForNoInputFiles(result, ts.getNormalizedAbsolutePath(configFileName, currentDirectory), configFileSpecs, configFileParsingDiagnostics, canConfigFileJsonReportNoInputFiles)) {
105814                 hasChangedConfigFileParsingErrors = true;
105815             }
105816             rootFileNames = result.fileNames;
105817             // Update the program
105818             synchronizeProgram();
105819         }
105820         function reloadConfigFile() {
105821             writeLog("Reloading config file: " + configFileName);
105822             reloadLevel = ts.ConfigFileProgramReloadLevel.None;
105823             if (cachedDirectoryStructureHost) {
105824                 cachedDirectoryStructureHost.clearCache();
105825             }
105826             parseConfigFile();
105827             hasChangedCompilerOptions = true;
105828             synchronizeProgram();
105829             // Update the wild card directory watch
105830             watchConfigFileWildCardDirectories();
105831         }
105832         function parseConfigFile() {
105833             setConfigFileParsingResult(ts.getParsedCommandLineOfConfigFile(configFileName, optionsToExtendForConfigFile, parseConfigFileHost, /*extendedConfigCache*/ undefined, watchOptionsToExtend, extraFileExtensions)); // TODO: GH#18217
105834         }
105835         function setConfigFileParsingResult(configFileParseResult) {
105836             rootFileNames = configFileParseResult.fileNames;
105837             compilerOptions = configFileParseResult.options;
105838             watchOptions = configFileParseResult.watchOptions;
105839             configFileSpecs = configFileParseResult.configFileSpecs; // TODO: GH#18217
105840             projectReferences = configFileParseResult.projectReferences;
105841             configFileParsingDiagnostics = ts.getConfigFileParsingDiagnostics(configFileParseResult).slice();
105842             canConfigFileJsonReportNoInputFiles = ts.canJsonReportNoInutFiles(configFileParseResult.raw);
105843             hasChangedConfigFileParsingErrors = true;
105844         }
105845         function onSourceFileChange(fileName, eventKind, path) {
105846             updateCachedSystemWithFile(fileName, path, eventKind);
105847             // Update the source file cache
105848             if (eventKind === ts.FileWatcherEventKind.Deleted && sourceFilesCache.has(path)) {
105849                 resolutionCache.invalidateResolutionOfFile(path);
105850             }
105851             resolutionCache.removeResolutionsFromProjectReferenceRedirects(path);
105852             nextSourceFileVersion(path);
105853             // Update the program
105854             scheduleProgramUpdate();
105855         }
105856         function updateCachedSystemWithFile(fileName, path, eventKind) {
105857             if (cachedDirectoryStructureHost) {
105858                 cachedDirectoryStructureHost.addOrDeleteFile(fileName, path, eventKind);
105859             }
105860         }
105861         function watchMissingFilePath(missingFilePath) {
105862             return watchFilePath(host, missingFilePath, onMissingFileChange, ts.PollingInterval.Medium, watchOptions, missingFilePath, ts.WatchType.MissingFile);
105863         }
105864         function onMissingFileChange(fileName, eventKind, missingFilePath) {
105865             updateCachedSystemWithFile(fileName, missingFilePath, eventKind);
105866             if (eventKind === ts.FileWatcherEventKind.Created && missingFilesMap.has(missingFilePath)) {
105867                 missingFilesMap.get(missingFilePath).close();
105868                 missingFilesMap.delete(missingFilePath);
105869                 // Delete the entry in the source files cache so that new source file is created
105870                 nextSourceFileVersion(missingFilePath);
105871                 // When a missing file is created, we should update the graph.
105872                 scheduleProgramUpdate();
105873             }
105874         }
105875         function watchConfigFileWildCardDirectories() {
105876             if (configFileSpecs) {
105877                 ts.updateWatchingWildcardDirectories(watchedWildcardDirectories || (watchedWildcardDirectories = ts.createMap()), ts.createMapFromTemplate(configFileSpecs.wildcardDirectories), watchWildcardDirectory);
105878             }
105879             else if (watchedWildcardDirectories) {
105880                 ts.clearMap(watchedWildcardDirectories, ts.closeFileWatcherOf);
105881             }
105882         }
105883         function watchWildcardDirectory(directory, flags) {
105884             return watchDirectory(host, directory, function (fileOrDirectory) {
105885                 ts.Debug.assert(!!configFileName);
105886                 var fileOrDirectoryPath = toPath(fileOrDirectory);
105887                 // Since the file existence changed, update the sourceFiles cache
105888                 if (cachedDirectoryStructureHost) {
105889                     cachedDirectoryStructureHost.addOrDeleteFileOrDirectory(fileOrDirectory, fileOrDirectoryPath);
105890                 }
105891                 nextSourceFileVersion(fileOrDirectoryPath);
105892                 fileOrDirectoryPath = ts.removeIgnoredPath(fileOrDirectoryPath);
105893                 if (!fileOrDirectoryPath)
105894                     return;
105895                 // If the the added or created file or directory is not supported file name, ignore the file
105896                 // But when watched directory is added/removed, we need to reload the file list
105897                 if (fileOrDirectoryPath !== directory && ts.hasExtension(fileOrDirectoryPath) && !ts.isSupportedSourceFileName(fileOrDirectory, compilerOptions)) {
105898                     writeLog("Project: " + configFileName + " Detected file add/remove of non supported extension: " + fileOrDirectory);
105899                     return;
105900                 }
105901                 // Reload is pending, do the reload
105902                 if (reloadLevel !== ts.ConfigFileProgramReloadLevel.Full) {
105903                     reloadLevel = ts.ConfigFileProgramReloadLevel.Partial;
105904                     // Schedule Update the program
105905                     scheduleProgramUpdate();
105906                 }
105907             }, flags, watchOptions, ts.WatchType.WildcardDirectory);
105908         }
105909     }
105910     ts.createWatchProgram = createWatchProgram;
105911 })(ts || (ts = {}));
105912 /*@internal*/
105913 var ts;
105914 (function (ts) {
105915     var UpToDateStatusType;
105916     (function (UpToDateStatusType) {
105917         UpToDateStatusType[UpToDateStatusType["Unbuildable"] = 0] = "Unbuildable";
105918         UpToDateStatusType[UpToDateStatusType["UpToDate"] = 1] = "UpToDate";
105919         /**
105920          * The project appears out of date because its upstream inputs are newer than its outputs,
105921          * but all of its outputs are actually newer than the previous identical outputs of its (.d.ts) inputs.
105922          * This means we can Pseudo-build (just touch timestamps), as if we had actually built this project.
105923          */
105924         UpToDateStatusType[UpToDateStatusType["UpToDateWithUpstreamTypes"] = 2] = "UpToDateWithUpstreamTypes";
105925         /**
105926          * The project appears out of date because its upstream inputs are newer than its outputs,
105927          * but all of its outputs are actually newer than the previous identical outputs of its (.d.ts) inputs.
105928          * This means we can Pseudo-build (just manipulate outputs), as if we had actually built this project.
105929          */
105930         UpToDateStatusType[UpToDateStatusType["OutOfDateWithPrepend"] = 3] = "OutOfDateWithPrepend";
105931         UpToDateStatusType[UpToDateStatusType["OutputMissing"] = 4] = "OutputMissing";
105932         UpToDateStatusType[UpToDateStatusType["OutOfDateWithSelf"] = 5] = "OutOfDateWithSelf";
105933         UpToDateStatusType[UpToDateStatusType["OutOfDateWithUpstream"] = 6] = "OutOfDateWithUpstream";
105934         UpToDateStatusType[UpToDateStatusType["UpstreamOutOfDate"] = 7] = "UpstreamOutOfDate";
105935         UpToDateStatusType[UpToDateStatusType["UpstreamBlocked"] = 8] = "UpstreamBlocked";
105936         UpToDateStatusType[UpToDateStatusType["ComputingUpstream"] = 9] = "ComputingUpstream";
105937         UpToDateStatusType[UpToDateStatusType["TsVersionOutputOfDate"] = 10] = "TsVersionOutputOfDate";
105938         /**
105939          * Projects with no outputs (i.e. "solution" files)
105940          */
105941         UpToDateStatusType[UpToDateStatusType["ContainerOnly"] = 11] = "ContainerOnly";
105942     })(UpToDateStatusType = ts.UpToDateStatusType || (ts.UpToDateStatusType = {}));
105943     function resolveConfigFileProjectName(project) {
105944         if (ts.fileExtensionIs(project, ".json" /* Json */)) {
105945             return project;
105946         }
105947         return ts.combinePaths(project, "tsconfig.json");
105948     }
105949     ts.resolveConfigFileProjectName = resolveConfigFileProjectName;
105950 })(ts || (ts = {}));
105951 var ts;
105952 (function (ts) {
105953     var minimumDate = new Date(-8640000000000000);
105954     var maximumDate = new Date(8640000000000000);
105955     var BuildResultFlags;
105956     (function (BuildResultFlags) {
105957         BuildResultFlags[BuildResultFlags["None"] = 0] = "None";
105958         /**
105959          * No errors of any kind occurred during build
105960          */
105961         BuildResultFlags[BuildResultFlags["Success"] = 1] = "Success";
105962         /**
105963          * None of the .d.ts files emitted by this build were
105964          * different from the existing files on disk
105965          */
105966         BuildResultFlags[BuildResultFlags["DeclarationOutputUnchanged"] = 2] = "DeclarationOutputUnchanged";
105967         BuildResultFlags[BuildResultFlags["ConfigFileErrors"] = 4] = "ConfigFileErrors";
105968         BuildResultFlags[BuildResultFlags["SyntaxErrors"] = 8] = "SyntaxErrors";
105969         BuildResultFlags[BuildResultFlags["TypeErrors"] = 16] = "TypeErrors";
105970         BuildResultFlags[BuildResultFlags["DeclarationEmitErrors"] = 32] = "DeclarationEmitErrors";
105971         BuildResultFlags[BuildResultFlags["EmitErrors"] = 64] = "EmitErrors";
105972         BuildResultFlags[BuildResultFlags["AnyErrors"] = 124] = "AnyErrors";
105973     })(BuildResultFlags || (BuildResultFlags = {}));
105974     function createConfigFileMap() {
105975         return ts.createMap();
105976     }
105977     function getOrCreateValueFromConfigFileMap(configFileMap, resolved, createT) {
105978         var existingValue = configFileMap.get(resolved);
105979         var newValue;
105980         if (!existingValue) {
105981             newValue = createT();
105982             configFileMap.set(resolved, newValue);
105983         }
105984         return existingValue || newValue;
105985     }
105986     function getOrCreateValueMapFromConfigFileMap(configFileMap, resolved) {
105987         return getOrCreateValueFromConfigFileMap(configFileMap, resolved, ts.createMap);
105988     }
105989     function newer(date1, date2) {
105990         return date2 > date1 ? date2 : date1;
105991     }
105992     function isDeclarationFile(fileName) {
105993         return ts.fileExtensionIs(fileName, ".d.ts" /* Dts */);
105994     }
105995     /*@internal*/
105996     function isCircularBuildOrder(buildOrder) {
105997         return !!buildOrder && !!buildOrder.buildOrder;
105998     }
105999     ts.isCircularBuildOrder = isCircularBuildOrder;
106000     /*@internal*/
106001     function getBuildOrderFromAnyBuildOrder(anyBuildOrder) {
106002         return isCircularBuildOrder(anyBuildOrder) ? anyBuildOrder.buildOrder : anyBuildOrder;
106003     }
106004     ts.getBuildOrderFromAnyBuildOrder = getBuildOrderFromAnyBuildOrder;
106005     /**
106006      * Create a function that reports watch status by writing to the system and handles the formating of the diagnostic
106007      */
106008     function createBuilderStatusReporter(system, pretty) {
106009         return function (diagnostic) {
106010             var output = pretty ? "[" + ts.formatColorAndReset(ts.getLocaleTimeString(system), ts.ForegroundColorEscapeSequences.Grey) + "] " : ts.getLocaleTimeString(system) + " - ";
106011             output += "" + ts.flattenDiagnosticMessageText(diagnostic.messageText, system.newLine) + (system.newLine + system.newLine);
106012             system.write(output);
106013         };
106014     }
106015     ts.createBuilderStatusReporter = createBuilderStatusReporter;
106016     function createSolutionBuilderHostBase(system, createProgram, reportDiagnostic, reportSolutionBuilderStatus) {
106017         var host = ts.createProgramHost(system, createProgram);
106018         host.getModifiedTime = system.getModifiedTime ? function (path) { return system.getModifiedTime(path); } : ts.returnUndefined;
106019         host.setModifiedTime = system.setModifiedTime ? function (path, date) { return system.setModifiedTime(path, date); } : ts.noop;
106020         host.deleteFile = system.deleteFile ? function (path) { return system.deleteFile(path); } : ts.noop;
106021         host.reportDiagnostic = reportDiagnostic || ts.createDiagnosticReporter(system);
106022         host.reportSolutionBuilderStatus = reportSolutionBuilderStatus || createBuilderStatusReporter(system);
106023         host.now = ts.maybeBind(system, system.now); // For testing
106024         return host;
106025     }
106026     function createSolutionBuilderHost(system, createProgram, reportDiagnostic, reportSolutionBuilderStatus, reportErrorSummary) {
106027         if (system === void 0) { system = ts.sys; }
106028         var host = createSolutionBuilderHostBase(system, createProgram, reportDiagnostic, reportSolutionBuilderStatus);
106029         host.reportErrorSummary = reportErrorSummary;
106030         return host;
106031     }
106032     ts.createSolutionBuilderHost = createSolutionBuilderHost;
106033     function createSolutionBuilderWithWatchHost(system, createProgram, reportDiagnostic, reportSolutionBuilderStatus, reportWatchStatus) {
106034         if (system === void 0) { system = ts.sys; }
106035         var host = createSolutionBuilderHostBase(system, createProgram, reportDiagnostic, reportSolutionBuilderStatus);
106036         var watchHost = ts.createWatchHost(system, reportWatchStatus);
106037         ts.copyProperties(host, watchHost);
106038         return host;
106039     }
106040     ts.createSolutionBuilderWithWatchHost = createSolutionBuilderWithWatchHost;
106041     function getCompilerOptionsOfBuildOptions(buildOptions) {
106042         var result = {};
106043         ts.commonOptionsWithBuild.forEach(function (option) {
106044             if (ts.hasProperty(buildOptions, option.name))
106045                 result[option.name] = buildOptions[option.name];
106046         });
106047         return result;
106048     }
106049     function createSolutionBuilder(host, rootNames, defaultOptions) {
106050         return createSolutionBuilderWorker(/*watch*/ false, host, rootNames, defaultOptions);
106051     }
106052     ts.createSolutionBuilder = createSolutionBuilder;
106053     function createSolutionBuilderWithWatch(host, rootNames, defaultOptions, baseWatchOptions) {
106054         return createSolutionBuilderWorker(/*watch*/ true, host, rootNames, defaultOptions, baseWatchOptions);
106055     }
106056     ts.createSolutionBuilderWithWatch = createSolutionBuilderWithWatch;
106057     function createSolutionBuilderState(watch, hostOrHostWithWatch, rootNames, options, baseWatchOptions) {
106058         var host = hostOrHostWithWatch;
106059         var hostWithWatch = hostOrHostWithWatch;
106060         var currentDirectory = host.getCurrentDirectory();
106061         var getCanonicalFileName = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames());
106062         // State of the solution
106063         var baseCompilerOptions = getCompilerOptionsOfBuildOptions(options);
106064         var compilerHost = ts.createCompilerHostFromProgramHost(host, function () { return state.projectCompilerOptions; });
106065         ts.setGetSourceFileAsHashVersioned(compilerHost, host);
106066         compilerHost.getParsedCommandLine = function (fileName) { return parseConfigFile(state, fileName, toResolvedConfigFilePath(state, fileName)); };
106067         compilerHost.resolveModuleNames = ts.maybeBind(host, host.resolveModuleNames);
106068         compilerHost.resolveTypeReferenceDirectives = ts.maybeBind(host, host.resolveTypeReferenceDirectives);
106069         var moduleResolutionCache = !compilerHost.resolveModuleNames ? ts.createModuleResolutionCache(currentDirectory, getCanonicalFileName) : undefined;
106070         if (!compilerHost.resolveModuleNames) {
106071             var loader_3 = function (moduleName, containingFile, redirectedReference) { return ts.resolveModuleName(moduleName, containingFile, state.projectCompilerOptions, compilerHost, moduleResolutionCache, redirectedReference).resolvedModule; };
106072             compilerHost.resolveModuleNames = function (moduleNames, containingFile, _reusedNames, redirectedReference) {
106073                 return ts.loadWithLocalCache(ts.Debug.checkEachDefined(moduleNames), containingFile, redirectedReference, loader_3);
106074             };
106075         }
106076         var _a = ts.createWatchFactory(hostWithWatch, options), watchFile = _a.watchFile, watchFilePath = _a.watchFilePath, watchDirectory = _a.watchDirectory, writeLog = _a.writeLog;
106077         var state = {
106078             host: host,
106079             hostWithWatch: hostWithWatch,
106080             currentDirectory: currentDirectory,
106081             getCanonicalFileName: getCanonicalFileName,
106082             parseConfigFileHost: ts.parseConfigHostFromCompilerHostLike(host),
106083             writeFileName: host.trace ? function (s) { return host.trace(s); } : undefined,
106084             // State of solution
106085             options: options,
106086             baseCompilerOptions: baseCompilerOptions,
106087             rootNames: rootNames,
106088             baseWatchOptions: baseWatchOptions,
106089             resolvedConfigFilePaths: ts.createMap(),
106090             configFileCache: createConfigFileMap(),
106091             projectStatus: createConfigFileMap(),
106092             buildInfoChecked: createConfigFileMap(),
106093             extendedConfigCache: ts.createMap(),
106094             builderPrograms: createConfigFileMap(),
106095             diagnostics: createConfigFileMap(),
106096             projectPendingBuild: createConfigFileMap(),
106097             projectErrorsReported: createConfigFileMap(),
106098             compilerHost: compilerHost,
106099             moduleResolutionCache: moduleResolutionCache,
106100             // Mutable state
106101             buildOrder: undefined,
106102             readFileWithCache: function (f) { return host.readFile(f); },
106103             projectCompilerOptions: baseCompilerOptions,
106104             cache: undefined,
106105             allProjectBuildPending: true,
106106             needsSummary: true,
106107             watchAllProjectsPending: watch,
106108             currentInvalidatedProject: undefined,
106109             // Watch state
106110             watch: watch,
106111             allWatchedWildcardDirectories: createConfigFileMap(),
106112             allWatchedInputFiles: createConfigFileMap(),
106113             allWatchedConfigFiles: createConfigFileMap(),
106114             timerToBuildInvalidatedProject: undefined,
106115             reportFileChangeDetected: false,
106116             watchFile: watchFile,
106117             watchFilePath: watchFilePath,
106118             watchDirectory: watchDirectory,
106119             writeLog: writeLog,
106120         };
106121         return state;
106122     }
106123     function toPath(state, fileName) {
106124         return ts.toPath(fileName, state.currentDirectory, state.getCanonicalFileName);
106125     }
106126     function toResolvedConfigFilePath(state, fileName) {
106127         var resolvedConfigFilePaths = state.resolvedConfigFilePaths;
106128         var path = resolvedConfigFilePaths.get(fileName);
106129         if (path !== undefined)
106130             return path;
106131         var resolvedPath = toPath(state, fileName);
106132         resolvedConfigFilePaths.set(fileName, resolvedPath);
106133         return resolvedPath;
106134     }
106135     function isParsedCommandLine(entry) {
106136         return !!entry.options;
106137     }
106138     function parseConfigFile(state, configFileName, configFilePath) {
106139         var configFileCache = state.configFileCache;
106140         var value = configFileCache.get(configFilePath);
106141         if (value) {
106142             return isParsedCommandLine(value) ? value : undefined;
106143         }
106144         var diagnostic;
106145         var parseConfigFileHost = state.parseConfigFileHost, baseCompilerOptions = state.baseCompilerOptions, baseWatchOptions = state.baseWatchOptions, extendedConfigCache = state.extendedConfigCache, host = state.host;
106146         var parsed;
106147         if (host.getParsedCommandLine) {
106148             parsed = host.getParsedCommandLine(configFileName);
106149             if (!parsed)
106150                 diagnostic = ts.createCompilerDiagnostic(ts.Diagnostics.File_0_not_found, configFileName);
106151         }
106152         else {
106153             parseConfigFileHost.onUnRecoverableConfigFileDiagnostic = function (d) { return diagnostic = d; };
106154             parsed = ts.getParsedCommandLineOfConfigFile(configFileName, baseCompilerOptions, parseConfigFileHost, extendedConfigCache, baseWatchOptions);
106155             parseConfigFileHost.onUnRecoverableConfigFileDiagnostic = ts.noop;
106156         }
106157         configFileCache.set(configFilePath, parsed || diagnostic);
106158         return parsed;
106159     }
106160     function resolveProjectName(state, name) {
106161         return ts.resolveConfigFileProjectName(ts.resolvePath(state.currentDirectory, name));
106162     }
106163     function createBuildOrder(state, roots) {
106164         var temporaryMarks = ts.createMap();
106165         var permanentMarks = ts.createMap();
106166         var circularityReportStack = [];
106167         var buildOrder;
106168         var circularDiagnostics;
106169         for (var _i = 0, roots_1 = roots; _i < roots_1.length; _i++) {
106170             var root = roots_1[_i];
106171             visit(root);
106172         }
106173         return circularDiagnostics ?
106174             { buildOrder: buildOrder || ts.emptyArray, circularDiagnostics: circularDiagnostics } :
106175             buildOrder || ts.emptyArray;
106176         function visit(configFileName, inCircularContext) {
106177             var projPath = toResolvedConfigFilePath(state, configFileName);
106178             // Already visited
106179             if (permanentMarks.has(projPath))
106180                 return;
106181             // Circular
106182             if (temporaryMarks.has(projPath)) {
106183                 if (!inCircularContext) {
106184                     (circularDiagnostics || (circularDiagnostics = [])).push(ts.createCompilerDiagnostic(ts.Diagnostics.Project_references_may_not_form_a_circular_graph_Cycle_detected_Colon_0, circularityReportStack.join("\r\n")));
106185                 }
106186                 return;
106187             }
106188             temporaryMarks.set(projPath, true);
106189             circularityReportStack.push(configFileName);
106190             var parsed = parseConfigFile(state, configFileName, projPath);
106191             if (parsed && parsed.projectReferences) {
106192                 for (var _i = 0, _a = parsed.projectReferences; _i < _a.length; _i++) {
106193                     var ref = _a[_i];
106194                     var resolvedRefPath = resolveProjectName(state, ref.path);
106195                     visit(resolvedRefPath, inCircularContext || ref.circular);
106196                 }
106197             }
106198             circularityReportStack.pop();
106199             permanentMarks.set(projPath, true);
106200             (buildOrder || (buildOrder = [])).push(configFileName);
106201         }
106202     }
106203     function getBuildOrder(state) {
106204         return state.buildOrder || createStateBuildOrder(state);
106205     }
106206     function createStateBuildOrder(state) {
106207         var buildOrder = createBuildOrder(state, state.rootNames.map(function (f) { return resolveProjectName(state, f); }));
106208         // Clear all to ResolvedConfigFilePaths cache to start fresh
106209         state.resolvedConfigFilePaths.clear();
106210         var currentProjects = ts.arrayToSet(getBuildOrderFromAnyBuildOrder(buildOrder), function (resolved) { return toResolvedConfigFilePath(state, resolved); });
106211         var noopOnDelete = { onDeleteValue: ts.noop };
106212         // Config file cache
106213         ts.mutateMapSkippingNewValues(state.configFileCache, currentProjects, noopOnDelete);
106214         ts.mutateMapSkippingNewValues(state.projectStatus, currentProjects, noopOnDelete);
106215         ts.mutateMapSkippingNewValues(state.buildInfoChecked, currentProjects, noopOnDelete);
106216         ts.mutateMapSkippingNewValues(state.builderPrograms, currentProjects, noopOnDelete);
106217         ts.mutateMapSkippingNewValues(state.diagnostics, currentProjects, noopOnDelete);
106218         ts.mutateMapSkippingNewValues(state.projectPendingBuild, currentProjects, noopOnDelete);
106219         ts.mutateMapSkippingNewValues(state.projectErrorsReported, currentProjects, noopOnDelete);
106220         // Remove watches for the program no longer in the solution
106221         if (state.watch) {
106222             ts.mutateMapSkippingNewValues(state.allWatchedConfigFiles, currentProjects, { onDeleteValue: ts.closeFileWatcher });
106223             ts.mutateMapSkippingNewValues(state.allWatchedWildcardDirectories, currentProjects, { onDeleteValue: function (existingMap) { return existingMap.forEach(ts.closeFileWatcherOf); } });
106224             ts.mutateMapSkippingNewValues(state.allWatchedInputFiles, currentProjects, { onDeleteValue: function (existingMap) { return existingMap.forEach(ts.closeFileWatcher); } });
106225         }
106226         return state.buildOrder = buildOrder;
106227     }
106228     function getBuildOrderFor(state, project, onlyReferences) {
106229         var resolvedProject = project && resolveProjectName(state, project);
106230         var buildOrderFromState = getBuildOrder(state);
106231         if (isCircularBuildOrder(buildOrderFromState))
106232             return buildOrderFromState;
106233         if (resolvedProject) {
106234             var projectPath_1 = toResolvedConfigFilePath(state, resolvedProject);
106235             var projectIndex = ts.findIndex(buildOrderFromState, function (configFileName) { return toResolvedConfigFilePath(state, configFileName) === projectPath_1; });
106236             if (projectIndex === -1)
106237                 return undefined;
106238         }
106239         var buildOrder = resolvedProject ? createBuildOrder(state, [resolvedProject]) : buildOrderFromState;
106240         ts.Debug.assert(!isCircularBuildOrder(buildOrder));
106241         ts.Debug.assert(!onlyReferences || resolvedProject !== undefined);
106242         ts.Debug.assert(!onlyReferences || buildOrder[buildOrder.length - 1] === resolvedProject);
106243         return onlyReferences ? buildOrder.slice(0, buildOrder.length - 1) : buildOrder;
106244     }
106245     function enableCache(state) {
106246         if (state.cache) {
106247             disableCache(state);
106248         }
106249         var compilerHost = state.compilerHost, host = state.host;
106250         var originalReadFileWithCache = state.readFileWithCache;
106251         var originalGetSourceFile = compilerHost.getSourceFile;
106252         var _a = ts.changeCompilerHostLikeToUseCache(host, function (fileName) { return toPath(state, fileName); }, function () {
106253             var args = [];
106254             for (var _i = 0; _i < arguments.length; _i++) {
106255                 args[_i] = arguments[_i];
106256             }
106257             return originalGetSourceFile.call.apply(originalGetSourceFile, __spreadArrays([compilerHost], args));
106258         }), originalReadFile = _a.originalReadFile, originalFileExists = _a.originalFileExists, originalDirectoryExists = _a.originalDirectoryExists, originalCreateDirectory = _a.originalCreateDirectory, originalWriteFile = _a.originalWriteFile, getSourceFileWithCache = _a.getSourceFileWithCache, readFileWithCache = _a.readFileWithCache;
106259         state.readFileWithCache = readFileWithCache;
106260         compilerHost.getSourceFile = getSourceFileWithCache;
106261         state.cache = {
106262             originalReadFile: originalReadFile,
106263             originalFileExists: originalFileExists,
106264             originalDirectoryExists: originalDirectoryExists,
106265             originalCreateDirectory: originalCreateDirectory,
106266             originalWriteFile: originalWriteFile,
106267             originalReadFileWithCache: originalReadFileWithCache,
106268             originalGetSourceFile: originalGetSourceFile,
106269         };
106270     }
106271     function disableCache(state) {
106272         if (!state.cache)
106273             return;
106274         var cache = state.cache, host = state.host, compilerHost = state.compilerHost, extendedConfigCache = state.extendedConfigCache, moduleResolutionCache = state.moduleResolutionCache;
106275         host.readFile = cache.originalReadFile;
106276         host.fileExists = cache.originalFileExists;
106277         host.directoryExists = cache.originalDirectoryExists;
106278         host.createDirectory = cache.originalCreateDirectory;
106279         host.writeFile = cache.originalWriteFile;
106280         compilerHost.getSourceFile = cache.originalGetSourceFile;
106281         state.readFileWithCache = cache.originalReadFileWithCache;
106282         extendedConfigCache.clear();
106283         if (moduleResolutionCache) {
106284             moduleResolutionCache.directoryToModuleNameMap.clear();
106285             moduleResolutionCache.moduleNameToDirectoryMap.clear();
106286         }
106287         state.cache = undefined;
106288     }
106289     function clearProjectStatus(state, resolved) {
106290         state.projectStatus.delete(resolved);
106291         state.diagnostics.delete(resolved);
106292     }
106293     function addProjToQueue(_a, proj, reloadLevel) {
106294         var projectPendingBuild = _a.projectPendingBuild;
106295         var value = projectPendingBuild.get(proj);
106296         if (value === undefined) {
106297             projectPendingBuild.set(proj, reloadLevel);
106298         }
106299         else if (value < reloadLevel) {
106300             projectPendingBuild.set(proj, reloadLevel);
106301         }
106302     }
106303     function setupInitialBuild(state, cancellationToken) {
106304         // Set initial build if not already built
106305         if (!state.allProjectBuildPending)
106306             return;
106307         state.allProjectBuildPending = false;
106308         if (state.options.watch) {
106309             reportWatchStatus(state, ts.Diagnostics.Starting_compilation_in_watch_mode);
106310         }
106311         enableCache(state);
106312         var buildOrder = getBuildOrderFromAnyBuildOrder(getBuildOrder(state));
106313         buildOrder.forEach(function (configFileName) {
106314             return state.projectPendingBuild.set(toResolvedConfigFilePath(state, configFileName), ts.ConfigFileProgramReloadLevel.None);
106315         });
106316         if (cancellationToken) {
106317             cancellationToken.throwIfCancellationRequested();
106318         }
106319     }
106320     var InvalidatedProjectKind;
106321     (function (InvalidatedProjectKind) {
106322         InvalidatedProjectKind[InvalidatedProjectKind["Build"] = 0] = "Build";
106323         InvalidatedProjectKind[InvalidatedProjectKind["UpdateBundle"] = 1] = "UpdateBundle";
106324         InvalidatedProjectKind[InvalidatedProjectKind["UpdateOutputFileStamps"] = 2] = "UpdateOutputFileStamps";
106325     })(InvalidatedProjectKind = ts.InvalidatedProjectKind || (ts.InvalidatedProjectKind = {}));
106326     function doneInvalidatedProject(state, projectPath) {
106327         state.projectPendingBuild.delete(projectPath);
106328         state.currentInvalidatedProject = undefined;
106329         return state.diagnostics.has(projectPath) ?
106330             ts.ExitStatus.DiagnosticsPresent_OutputsSkipped :
106331             ts.ExitStatus.Success;
106332     }
106333     function createUpdateOutputFileStampsProject(state, project, projectPath, config, buildOrder) {
106334         var updateOutputFileStampsPending = true;
106335         return {
106336             kind: InvalidatedProjectKind.UpdateOutputFileStamps,
106337             project: project,
106338             projectPath: projectPath,
106339             buildOrder: buildOrder,
106340             getCompilerOptions: function () { return config.options; },
106341             getCurrentDirectory: function () { return state.currentDirectory; },
106342             updateOutputFileStatmps: function () {
106343                 updateOutputTimestamps(state, config, projectPath);
106344                 updateOutputFileStampsPending = false;
106345             },
106346             done: function () {
106347                 if (updateOutputFileStampsPending) {
106348                     updateOutputTimestamps(state, config, projectPath);
106349                 }
106350                 return doneInvalidatedProject(state, projectPath);
106351             }
106352         };
106353     }
106354     function createBuildOrUpdateInvalidedProject(kind, state, project, projectPath, projectIndex, config, buildOrder) {
106355         var Step;
106356         (function (Step) {
106357             Step[Step["CreateProgram"] = 0] = "CreateProgram";
106358             Step[Step["SyntaxDiagnostics"] = 1] = "SyntaxDiagnostics";
106359             Step[Step["SemanticDiagnostics"] = 2] = "SemanticDiagnostics";
106360             Step[Step["Emit"] = 3] = "Emit";
106361             Step[Step["EmitBundle"] = 4] = "EmitBundle";
106362             Step[Step["BuildInvalidatedProjectOfBundle"] = 5] = "BuildInvalidatedProjectOfBundle";
106363             Step[Step["QueueReferencingProjects"] = 6] = "QueueReferencingProjects";
106364             Step[Step["Done"] = 7] = "Done";
106365         })(Step || (Step = {}));
106366         var step = kind === InvalidatedProjectKind.Build ? Step.CreateProgram : Step.EmitBundle;
106367         var program;
106368         var buildResult;
106369         var invalidatedProjectOfBundle;
106370         return kind === InvalidatedProjectKind.Build ?
106371             {
106372                 kind: kind,
106373                 project: project,
106374                 projectPath: projectPath,
106375                 buildOrder: buildOrder,
106376                 getCompilerOptions: function () { return config.options; },
106377                 getCurrentDirectory: function () { return state.currentDirectory; },
106378                 getBuilderProgram: function () { return withProgramOrUndefined(ts.identity); },
106379                 getProgram: function () {
106380                     return withProgramOrUndefined(function (program) { return program.getProgramOrUndefined(); });
106381                 },
106382                 getSourceFile: function (fileName) {
106383                     return withProgramOrUndefined(function (program) { return program.getSourceFile(fileName); });
106384                 },
106385                 getSourceFiles: function () {
106386                     return withProgramOrEmptyArray(function (program) { return program.getSourceFiles(); });
106387                 },
106388                 getOptionsDiagnostics: function (cancellationToken) {
106389                     return withProgramOrEmptyArray(function (program) { return program.getOptionsDiagnostics(cancellationToken); });
106390                 },
106391                 getGlobalDiagnostics: function (cancellationToken) {
106392                     return withProgramOrEmptyArray(function (program) { return program.getGlobalDiagnostics(cancellationToken); });
106393                 },
106394                 getConfigFileParsingDiagnostics: function () {
106395                     return withProgramOrEmptyArray(function (program) { return program.getConfigFileParsingDiagnostics(); });
106396                 },
106397                 getSyntacticDiagnostics: function (sourceFile, cancellationToken) {
106398                     return withProgramOrEmptyArray(function (program) { return program.getSyntacticDiagnostics(sourceFile, cancellationToken); });
106399                 },
106400                 getAllDependencies: function (sourceFile) {
106401                     return withProgramOrEmptyArray(function (program) { return program.getAllDependencies(sourceFile); });
106402                 },
106403                 getSemanticDiagnostics: function (sourceFile, cancellationToken) {
106404                     return withProgramOrEmptyArray(function (program) { return program.getSemanticDiagnostics(sourceFile, cancellationToken); });
106405                 },
106406                 getSemanticDiagnosticsOfNextAffectedFile: function (cancellationToken, ignoreSourceFile) {
106407                     return withProgramOrUndefined(function (program) {
106408                         return (program.getSemanticDiagnosticsOfNextAffectedFile) &&
106409                             program.getSemanticDiagnosticsOfNextAffectedFile(cancellationToken, ignoreSourceFile);
106410                     });
106411                 },
106412                 emit: function (targetSourceFile, writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers) {
106413                     if (targetSourceFile || emitOnlyDtsFiles) {
106414                         return withProgramOrUndefined(function (program) { return program.emit(targetSourceFile, writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers); });
106415                     }
106416                     executeSteps(Step.SemanticDiagnostics, cancellationToken);
106417                     if (step !== Step.Emit)
106418                         return undefined;
106419                     return emit(writeFile, cancellationToken, customTransformers);
106420                 },
106421                 done: done
106422             } :
106423             {
106424                 kind: kind,
106425                 project: project,
106426                 projectPath: projectPath,
106427                 buildOrder: buildOrder,
106428                 getCompilerOptions: function () { return config.options; },
106429                 getCurrentDirectory: function () { return state.currentDirectory; },
106430                 emit: function (writeFile, customTransformers) {
106431                     if (step !== Step.EmitBundle)
106432                         return invalidatedProjectOfBundle;
106433                     return emitBundle(writeFile, customTransformers);
106434                 },
106435                 done: done,
106436             };
106437         function done(cancellationToken, writeFile, customTransformers) {
106438             executeSteps(Step.Done, cancellationToken, writeFile, customTransformers);
106439             return doneInvalidatedProject(state, projectPath);
106440         }
106441         function withProgramOrUndefined(action) {
106442             executeSteps(Step.CreateProgram);
106443             return program && action(program);
106444         }
106445         function withProgramOrEmptyArray(action) {
106446             return withProgramOrUndefined(action) || ts.emptyArray;
106447         }
106448         function createProgram() {
106449             ts.Debug.assert(program === undefined);
106450             if (state.options.dry) {
106451                 reportStatus(state, ts.Diagnostics.A_non_dry_build_would_build_project_0, project);
106452                 buildResult = BuildResultFlags.Success;
106453                 step = Step.QueueReferencingProjects;
106454                 return;
106455             }
106456             if (state.options.verbose)
106457                 reportStatus(state, ts.Diagnostics.Building_project_0, project);
106458             if (config.fileNames.length === 0) {
106459                 reportAndStoreErrors(state, projectPath, ts.getConfigFileParsingDiagnostics(config));
106460                 // Nothing to build - must be a solution file, basically
106461                 buildResult = BuildResultFlags.None;
106462                 step = Step.QueueReferencingProjects;
106463                 return;
106464             }
106465             var host = state.host, compilerHost = state.compilerHost;
106466             state.projectCompilerOptions = config.options;
106467             // Update module resolution cache if needed
106468             updateModuleResolutionCache(state, project, config);
106469             // Create program
106470             program = host.createProgram(config.fileNames, config.options, compilerHost, getOldProgram(state, projectPath, config), ts.getConfigFileParsingDiagnostics(config), config.projectReferences);
106471             step++;
106472         }
106473         function handleDiagnostics(diagnostics, errorFlags, errorType) {
106474             if (diagnostics.length) {
106475                 buildResult = buildErrors(state, projectPath, program, config, diagnostics, errorFlags, errorType);
106476                 step = Step.QueueReferencingProjects;
106477             }
106478             else {
106479                 step++;
106480             }
106481         }
106482         function getSyntaxDiagnostics(cancellationToken) {
106483             ts.Debug.assertIsDefined(program);
106484             handleDiagnostics(__spreadArrays(program.getConfigFileParsingDiagnostics(), program.getOptionsDiagnostics(cancellationToken), program.getGlobalDiagnostics(cancellationToken), program.getSyntacticDiagnostics(/*sourceFile*/ undefined, cancellationToken)), BuildResultFlags.SyntaxErrors, "Syntactic");
106485         }
106486         function getSemanticDiagnostics(cancellationToken) {
106487             handleDiagnostics(ts.Debug.checkDefined(program).getSemanticDiagnostics(/*sourceFile*/ undefined, cancellationToken), BuildResultFlags.TypeErrors, "Semantic");
106488         }
106489         function emit(writeFileCallback, cancellationToken, customTransformers) {
106490             ts.Debug.assertIsDefined(program);
106491             ts.Debug.assert(step === Step.Emit);
106492             // Before emitting lets backup state, so we can revert it back if there are declaration errors to handle emit and declaration errors correctly
106493             program.backupState();
106494             var declDiagnostics;
106495             var reportDeclarationDiagnostics = function (d) { return (declDiagnostics || (declDiagnostics = [])).push(d); };
106496             var outputFiles = [];
106497             var emitResult = ts.emitFilesAndReportErrors(program, reportDeclarationDiagnostics, 
106498             /*writeFileName*/ undefined, 
106499             /*reportSummary*/ undefined, function (name, text, writeByteOrderMark) { return outputFiles.push({ name: name, text: text, writeByteOrderMark: writeByteOrderMark }); }, cancellationToken, 
106500             /*emitOnlyDts*/ false, customTransformers).emitResult;
106501             // Don't emit .d.ts if there are decl file errors
106502             if (declDiagnostics) {
106503                 program.restoreState();
106504                 buildResult = buildErrors(state, projectPath, program, config, declDiagnostics, BuildResultFlags.DeclarationEmitErrors, "Declaration file");
106505                 step = Step.QueueReferencingProjects;
106506                 return {
106507                     emitSkipped: true,
106508                     diagnostics: emitResult.diagnostics
106509                 };
106510             }
106511             // Actual Emit
106512             var host = state.host, compilerHost = state.compilerHost;
106513             var resultFlags = BuildResultFlags.DeclarationOutputUnchanged;
106514             var newestDeclarationFileContentChangedTime = minimumDate;
106515             var anyDtsChanged = false;
106516             var emitterDiagnostics = ts.createDiagnosticCollection();
106517             var emittedOutputs = ts.createMap();
106518             outputFiles.forEach(function (_a) {
106519                 var name = _a.name, text = _a.text, writeByteOrderMark = _a.writeByteOrderMark;
106520                 var priorChangeTime;
106521                 if (!anyDtsChanged && isDeclarationFile(name)) {
106522                     // Check for unchanged .d.ts files
106523                     if (host.fileExists(name) && state.readFileWithCache(name) === text) {
106524                         priorChangeTime = host.getModifiedTime(name);
106525                     }
106526                     else {
106527                         resultFlags &= ~BuildResultFlags.DeclarationOutputUnchanged;
106528                         anyDtsChanged = true;
106529                     }
106530                 }
106531                 emittedOutputs.set(toPath(state, name), name);
106532                 ts.writeFile(writeFileCallback ? { writeFile: writeFileCallback } : compilerHost, emitterDiagnostics, name, text, writeByteOrderMark);
106533                 if (priorChangeTime !== undefined) {
106534                     newestDeclarationFileContentChangedTime = newer(priorChangeTime, newestDeclarationFileContentChangedTime);
106535                 }
106536             });
106537             finishEmit(emitterDiagnostics, emittedOutputs, newestDeclarationFileContentChangedTime, 
106538             /*newestDeclarationFileContentChangedTimeIsMaximumDate*/ anyDtsChanged, outputFiles.length ? outputFiles[0].name : ts.getFirstProjectOutput(config, !host.useCaseSensitiveFileNames()), resultFlags);
106539             return emitResult;
106540         }
106541         function finishEmit(emitterDiagnostics, emittedOutputs, priorNewestUpdateTime, newestDeclarationFileContentChangedTimeIsMaximumDate, oldestOutputFileName, resultFlags) {
106542             var emitDiagnostics = emitterDiagnostics.getDiagnostics();
106543             if (emitDiagnostics.length) {
106544                 buildResult = buildErrors(state, projectPath, program, config, emitDiagnostics, BuildResultFlags.EmitErrors, "Emit");
106545                 step = Step.QueueReferencingProjects;
106546                 return emitDiagnostics;
106547             }
106548             if (state.writeFileName) {
106549                 emittedOutputs.forEach(function (name) { return listEmittedFile(state, config, name); });
106550                 if (program)
106551                     ts.listFiles(program, state.writeFileName);
106552             }
106553             // Update time stamps for rest of the outputs
106554             var newestDeclarationFileContentChangedTime = updateOutputTimestampsWorker(state, config, priorNewestUpdateTime, ts.Diagnostics.Updating_unchanged_output_timestamps_of_project_0, emittedOutputs);
106555             state.diagnostics.delete(projectPath);
106556             state.projectStatus.set(projectPath, {
106557                 type: ts.UpToDateStatusType.UpToDate,
106558                 newestDeclarationFileContentChangedTime: newestDeclarationFileContentChangedTimeIsMaximumDate ?
106559                     maximumDate :
106560                     newestDeclarationFileContentChangedTime,
106561                 oldestOutputFileName: oldestOutputFileName
106562             });
106563             afterProgramDone(state, projectPath, program, config);
106564             state.projectCompilerOptions = state.baseCompilerOptions;
106565             step = Step.QueueReferencingProjects;
106566             buildResult = resultFlags;
106567             return emitDiagnostics;
106568         }
106569         function emitBundle(writeFileCallback, customTransformers) {
106570             ts.Debug.assert(kind === InvalidatedProjectKind.UpdateBundle);
106571             if (state.options.dry) {
106572                 reportStatus(state, ts.Diagnostics.A_non_dry_build_would_update_output_of_project_0, project);
106573                 buildResult = BuildResultFlags.Success;
106574                 step = Step.QueueReferencingProjects;
106575                 return undefined;
106576             }
106577             if (state.options.verbose)
106578                 reportStatus(state, ts.Diagnostics.Updating_output_of_project_0, project);
106579             // Update js, and source map
106580             var compilerHost = state.compilerHost;
106581             state.projectCompilerOptions = config.options;
106582             var outputFiles = ts.emitUsingBuildInfo(config, compilerHost, function (ref) {
106583                 var refName = resolveProjectName(state, ref.path);
106584                 return parseConfigFile(state, refName, toResolvedConfigFilePath(state, refName));
106585             }, customTransformers);
106586             if (ts.isString(outputFiles)) {
106587                 reportStatus(state, ts.Diagnostics.Cannot_update_output_of_project_0_because_there_was_error_reading_file_1, project, relName(state, outputFiles));
106588                 step = Step.BuildInvalidatedProjectOfBundle;
106589                 return invalidatedProjectOfBundle = createBuildOrUpdateInvalidedProject(InvalidatedProjectKind.Build, state, project, projectPath, projectIndex, config, buildOrder);
106590             }
106591             // Actual Emit
106592             ts.Debug.assert(!!outputFiles.length);
106593             var emitterDiagnostics = ts.createDiagnosticCollection();
106594             var emittedOutputs = ts.createMap();
106595             outputFiles.forEach(function (_a) {
106596                 var name = _a.name, text = _a.text, writeByteOrderMark = _a.writeByteOrderMark;
106597                 emittedOutputs.set(toPath(state, name), name);
106598                 ts.writeFile(writeFileCallback ? { writeFile: writeFileCallback } : compilerHost, emitterDiagnostics, name, text, writeByteOrderMark);
106599             });
106600             var emitDiagnostics = finishEmit(emitterDiagnostics, emittedOutputs, minimumDate, 
106601             /*newestDeclarationFileContentChangedTimeIsMaximumDate*/ false, outputFiles[0].name, BuildResultFlags.DeclarationOutputUnchanged);
106602             return { emitSkipped: false, diagnostics: emitDiagnostics };
106603         }
106604         function executeSteps(till, cancellationToken, writeFile, customTransformers) {
106605             while (step <= till && step < Step.Done) {
106606                 var currentStep = step;
106607                 switch (step) {
106608                     case Step.CreateProgram:
106609                         createProgram();
106610                         break;
106611                     case Step.SyntaxDiagnostics:
106612                         getSyntaxDiagnostics(cancellationToken);
106613                         break;
106614                     case Step.SemanticDiagnostics:
106615                         getSemanticDiagnostics(cancellationToken);
106616                         break;
106617                     case Step.Emit:
106618                         emit(writeFile, cancellationToken, customTransformers);
106619                         break;
106620                     case Step.EmitBundle:
106621                         emitBundle(writeFile, customTransformers);
106622                         break;
106623                     case Step.BuildInvalidatedProjectOfBundle:
106624                         ts.Debug.checkDefined(invalidatedProjectOfBundle).done(cancellationToken);
106625                         step = Step.Done;
106626                         break;
106627                     case Step.QueueReferencingProjects:
106628                         queueReferencingProjects(state, project, projectPath, projectIndex, config, buildOrder, ts.Debug.checkDefined(buildResult));
106629                         step++;
106630                         break;
106631                     // Should never be done
106632                     case Step.Done:
106633                     default:
106634                         ts.assertType(step);
106635                 }
106636                 ts.Debug.assert(step > currentStep);
106637             }
106638         }
106639     }
106640     function needsBuild(_a, status, config) {
106641         var options = _a.options;
106642         if (status.type !== ts.UpToDateStatusType.OutOfDateWithPrepend || options.force)
106643             return true;
106644         return config.fileNames.length === 0 ||
106645             !!ts.getConfigFileParsingDiagnostics(config).length ||
106646             !ts.isIncrementalCompilation(config.options);
106647     }
106648     function getNextInvalidatedProject(state, buildOrder, reportQueue) {
106649         if (!state.projectPendingBuild.size)
106650             return undefined;
106651         if (isCircularBuildOrder(buildOrder))
106652             return undefined;
106653         if (state.currentInvalidatedProject) {
106654             // Only if same buildOrder the currentInvalidated project can be sent again
106655             return ts.arrayIsEqualTo(state.currentInvalidatedProject.buildOrder, buildOrder) ?
106656                 state.currentInvalidatedProject :
106657                 undefined;
106658         }
106659         var options = state.options, projectPendingBuild = state.projectPendingBuild;
106660         for (var projectIndex = 0; projectIndex < buildOrder.length; projectIndex++) {
106661             var project = buildOrder[projectIndex];
106662             var projectPath = toResolvedConfigFilePath(state, project);
106663             var reloadLevel = state.projectPendingBuild.get(projectPath);
106664             if (reloadLevel === undefined)
106665                 continue;
106666             if (reportQueue) {
106667                 reportQueue = false;
106668                 reportBuildQueue(state, buildOrder);
106669             }
106670             var config = parseConfigFile(state, project, projectPath);
106671             if (!config) {
106672                 reportParseConfigFileDiagnostic(state, projectPath);
106673                 projectPendingBuild.delete(projectPath);
106674                 continue;
106675             }
106676             if (reloadLevel === ts.ConfigFileProgramReloadLevel.Full) {
106677                 watchConfigFile(state, project, projectPath, config);
106678                 watchWildCardDirectories(state, project, projectPath, config);
106679                 watchInputFiles(state, project, projectPath, config);
106680             }
106681             else if (reloadLevel === ts.ConfigFileProgramReloadLevel.Partial) {
106682                 // Update file names
106683                 var result = ts.getFileNamesFromConfigSpecs(config.configFileSpecs, ts.getDirectoryPath(project), config.options, state.parseConfigFileHost);
106684                 ts.updateErrorForNoInputFiles(result, project, config.configFileSpecs, config.errors, ts.canJsonReportNoInutFiles(config.raw));
106685                 config.fileNames = result.fileNames;
106686                 watchInputFiles(state, project, projectPath, config);
106687             }
106688             var status = getUpToDateStatus(state, config, projectPath);
106689             verboseReportProjectStatus(state, project, status);
106690             if (!options.force) {
106691                 if (status.type === ts.UpToDateStatusType.UpToDate) {
106692                     reportAndStoreErrors(state, projectPath, ts.getConfigFileParsingDiagnostics(config));
106693                     projectPendingBuild.delete(projectPath);
106694                     // Up to date, skip
106695                     if (options.dry) {
106696                         // In a dry build, inform the user of this fact
106697                         reportStatus(state, ts.Diagnostics.Project_0_is_up_to_date, project);
106698                     }
106699                     continue;
106700                 }
106701                 if (status.type === ts.UpToDateStatusType.UpToDateWithUpstreamTypes) {
106702                     reportAndStoreErrors(state, projectPath, ts.getConfigFileParsingDiagnostics(config));
106703                     return createUpdateOutputFileStampsProject(state, project, projectPath, config, buildOrder);
106704                 }
106705             }
106706             if (status.type === ts.UpToDateStatusType.UpstreamBlocked) {
106707                 reportAndStoreErrors(state, projectPath, ts.getConfigFileParsingDiagnostics(config));
106708                 projectPendingBuild.delete(projectPath);
106709                 if (options.verbose) {
106710                     reportStatus(state, status.upstreamProjectBlocked ?
106711                         ts.Diagnostics.Skipping_build_of_project_0_because_its_dependency_1_was_not_built :
106712                         ts.Diagnostics.Skipping_build_of_project_0_because_its_dependency_1_has_errors, project, status.upstreamProjectName);
106713                 }
106714                 continue;
106715             }
106716             if (status.type === ts.UpToDateStatusType.ContainerOnly) {
106717                 reportAndStoreErrors(state, projectPath, ts.getConfigFileParsingDiagnostics(config));
106718                 projectPendingBuild.delete(projectPath);
106719                 // Do nothing
106720                 continue;
106721             }
106722             return createBuildOrUpdateInvalidedProject(needsBuild(state, status, config) ?
106723                 InvalidatedProjectKind.Build :
106724                 InvalidatedProjectKind.UpdateBundle, state, project, projectPath, projectIndex, config, buildOrder);
106725         }
106726         return undefined;
106727     }
106728     function listEmittedFile(_a, proj, file) {
106729         var writeFileName = _a.writeFileName;
106730         if (writeFileName && proj.options.listEmittedFiles) {
106731             writeFileName("TSFILE: " + file);
106732         }
106733     }
106734     function getOldProgram(_a, proj, parsed) {
106735         var options = _a.options, builderPrograms = _a.builderPrograms, compilerHost = _a.compilerHost;
106736         if (options.force)
106737             return undefined;
106738         var value = builderPrograms.get(proj);
106739         if (value)
106740             return value;
106741         return ts.readBuilderProgram(parsed.options, compilerHost);
106742     }
106743     function afterProgramDone(_a, proj, program, config) {
106744         var host = _a.host, watch = _a.watch, builderPrograms = _a.builderPrograms;
106745         if (program) {
106746             if (host.afterProgramEmitAndDiagnostics) {
106747                 host.afterProgramEmitAndDiagnostics(program);
106748             }
106749             if (watch) {
106750                 program.releaseProgram();
106751                 builderPrograms.set(proj, program);
106752             }
106753         }
106754         else if (host.afterEmitBundle) {
106755             host.afterEmitBundle(config);
106756         }
106757     }
106758     function buildErrors(state, resolvedPath, program, config, diagnostics, errorFlags, errorType) {
106759         reportAndStoreErrors(state, resolvedPath, diagnostics);
106760         // List files if any other build error using program (emit errors already report files)
106761         if (program && state.writeFileName)
106762             ts.listFiles(program, state.writeFileName);
106763         state.projectStatus.set(resolvedPath, { type: ts.UpToDateStatusType.Unbuildable, reason: errorType + " errors" });
106764         afterProgramDone(state, resolvedPath, program, config);
106765         state.projectCompilerOptions = state.baseCompilerOptions;
106766         return errorFlags;
106767     }
106768     function updateModuleResolutionCache(state, proj, config) {
106769         if (!state.moduleResolutionCache)
106770             return;
106771         // Update module resolution cache if needed
106772         var moduleResolutionCache = state.moduleResolutionCache;
106773         var projPath = toPath(state, proj);
106774         if (moduleResolutionCache.directoryToModuleNameMap.redirectsMap.size === 0) {
106775             // The own map will be for projectCompilerOptions
106776             ts.Debug.assert(moduleResolutionCache.moduleNameToDirectoryMap.redirectsMap.size === 0);
106777             moduleResolutionCache.directoryToModuleNameMap.redirectsMap.set(projPath, moduleResolutionCache.directoryToModuleNameMap.ownMap);
106778             moduleResolutionCache.moduleNameToDirectoryMap.redirectsMap.set(projPath, moduleResolutionCache.moduleNameToDirectoryMap.ownMap);
106779         }
106780         else {
106781             // Set correct own map
106782             ts.Debug.assert(moduleResolutionCache.moduleNameToDirectoryMap.redirectsMap.size > 0);
106783             var ref = {
106784                 sourceFile: config.options.configFile,
106785                 commandLine: config
106786             };
106787             moduleResolutionCache.directoryToModuleNameMap.setOwnMap(moduleResolutionCache.directoryToModuleNameMap.getOrCreateMapOfCacheRedirects(ref));
106788             moduleResolutionCache.moduleNameToDirectoryMap.setOwnMap(moduleResolutionCache.moduleNameToDirectoryMap.getOrCreateMapOfCacheRedirects(ref));
106789         }
106790         moduleResolutionCache.directoryToModuleNameMap.setOwnOptions(config.options);
106791         moduleResolutionCache.moduleNameToDirectoryMap.setOwnOptions(config.options);
106792     }
106793     function checkConfigFileUpToDateStatus(state, configFile, oldestOutputFileTime, oldestOutputFileName) {
106794         // Check tsconfig time
106795         var tsconfigTime = state.host.getModifiedTime(configFile) || ts.missingFileModifiedTime;
106796         if (oldestOutputFileTime < tsconfigTime) {
106797             return {
106798                 type: ts.UpToDateStatusType.OutOfDateWithSelf,
106799                 outOfDateOutputFileName: oldestOutputFileName,
106800                 newerInputFileName: configFile
106801             };
106802         }
106803     }
106804     function getUpToDateStatusWorker(state, project, resolvedPath) {
106805         var newestInputFileName = undefined;
106806         var newestInputFileTime = minimumDate;
106807         var host = state.host;
106808         // Get timestamps of input files
106809         for (var _i = 0, _a = project.fileNames; _i < _a.length; _i++) {
106810             var inputFile = _a[_i];
106811             if (!host.fileExists(inputFile)) {
106812                 return {
106813                     type: ts.UpToDateStatusType.Unbuildable,
106814                     reason: inputFile + " does not exist"
106815                 };
106816             }
106817             var inputTime = host.getModifiedTime(inputFile) || ts.missingFileModifiedTime;
106818             if (inputTime > newestInputFileTime) {
106819                 newestInputFileName = inputFile;
106820                 newestInputFileTime = inputTime;
106821             }
106822         }
106823         // Container if no files are specified in the project
106824         if (!project.fileNames.length && !ts.canJsonReportNoInutFiles(project.raw)) {
106825             return {
106826                 type: ts.UpToDateStatusType.ContainerOnly
106827             };
106828         }
106829         // Collect the expected outputs of this project
106830         var outputs = ts.getAllProjectOutputs(project, !host.useCaseSensitiveFileNames());
106831         // Now see if all outputs are newer than the newest input
106832         var oldestOutputFileName = "(none)";
106833         var oldestOutputFileTime = maximumDate;
106834         var newestOutputFileName = "(none)";
106835         var newestOutputFileTime = minimumDate;
106836         var missingOutputFileName;
106837         var newestDeclarationFileContentChangedTime = minimumDate;
106838         var isOutOfDateWithInputs = false;
106839         for (var _b = 0, outputs_1 = outputs; _b < outputs_1.length; _b++) {
106840             var output = outputs_1[_b];
106841             // Output is missing; can stop checking
106842             // Don't immediately return because we can still be upstream-blocked, which is a higher-priority status
106843             if (!host.fileExists(output)) {
106844                 missingOutputFileName = output;
106845                 break;
106846             }
106847             var outputTime = host.getModifiedTime(output) || ts.missingFileModifiedTime;
106848             if (outputTime < oldestOutputFileTime) {
106849                 oldestOutputFileTime = outputTime;
106850                 oldestOutputFileName = output;
106851             }
106852             // If an output is older than the newest input, we can stop checking
106853             // Don't immediately return because we can still be upstream-blocked, which is a higher-priority status
106854             if (outputTime < newestInputFileTime) {
106855                 isOutOfDateWithInputs = true;
106856                 break;
106857             }
106858             if (outputTime > newestOutputFileTime) {
106859                 newestOutputFileTime = outputTime;
106860                 newestOutputFileName = output;
106861             }
106862             // Keep track of when the most recent time a .d.ts file was changed.
106863             // In addition to file timestamps, we also keep track of when a .d.ts file
106864             // had its file touched but not had its contents changed - this allows us
106865             // to skip a downstream typecheck
106866             if (isDeclarationFile(output)) {
106867                 var outputModifiedTime = host.getModifiedTime(output) || ts.missingFileModifiedTime;
106868                 newestDeclarationFileContentChangedTime = newer(newestDeclarationFileContentChangedTime, outputModifiedTime);
106869             }
106870         }
106871         var pseudoUpToDate = false;
106872         var usesPrepend = false;
106873         var upstreamChangedProject;
106874         if (project.projectReferences) {
106875             state.projectStatus.set(resolvedPath, { type: ts.UpToDateStatusType.ComputingUpstream });
106876             for (var _c = 0, _d = project.projectReferences; _c < _d.length; _c++) {
106877                 var ref = _d[_c];
106878                 usesPrepend = usesPrepend || !!(ref.prepend);
106879                 var resolvedRef = ts.resolveProjectReferencePath(ref);
106880                 var resolvedRefPath = toResolvedConfigFilePath(state, resolvedRef);
106881                 var refStatus = getUpToDateStatus(state, parseConfigFile(state, resolvedRef, resolvedRefPath), resolvedRefPath);
106882                 // Its a circular reference ignore the status of this project
106883                 if (refStatus.type === ts.UpToDateStatusType.ComputingUpstream ||
106884                     refStatus.type === ts.UpToDateStatusType.ContainerOnly) { // Container only ignore this project
106885                     continue;
106886                 }
106887                 // An upstream project is blocked
106888                 if (refStatus.type === ts.UpToDateStatusType.Unbuildable ||
106889                     refStatus.type === ts.UpToDateStatusType.UpstreamBlocked) {
106890                     return {
106891                         type: ts.UpToDateStatusType.UpstreamBlocked,
106892                         upstreamProjectName: ref.path,
106893                         upstreamProjectBlocked: refStatus.type === ts.UpToDateStatusType.UpstreamBlocked
106894                     };
106895                 }
106896                 // If the upstream project is out of date, then so are we (someone shouldn't have asked, though?)
106897                 if (refStatus.type !== ts.UpToDateStatusType.UpToDate) {
106898                     return {
106899                         type: ts.UpToDateStatusType.UpstreamOutOfDate,
106900                         upstreamProjectName: ref.path
106901                     };
106902                 }
106903                 // Check oldest output file name only if there is no missing output file name
106904                 if (!missingOutputFileName) {
106905                     // If the upstream project's newest file is older than our oldest output, we
106906                     // can't be out of date because of it
106907                     if (refStatus.newestInputFileTime && refStatus.newestInputFileTime <= oldestOutputFileTime) {
106908                         continue;
106909                     }
106910                     // If the upstream project has only change .d.ts files, and we've built
106911                     // *after* those files, then we're "psuedo up to date" and eligible for a fast rebuild
106912                     if (refStatus.newestDeclarationFileContentChangedTime && refStatus.newestDeclarationFileContentChangedTime <= oldestOutputFileTime) {
106913                         pseudoUpToDate = true;
106914                         upstreamChangedProject = ref.path;
106915                         continue;
106916                     }
106917                     // We have an output older than an upstream output - we are out of date
106918                     ts.Debug.assert(oldestOutputFileName !== undefined, "Should have an oldest output filename here");
106919                     return {
106920                         type: ts.UpToDateStatusType.OutOfDateWithUpstream,
106921                         outOfDateOutputFileName: oldestOutputFileName,
106922                         newerProjectName: ref.path
106923                     };
106924                 }
106925             }
106926         }
106927         if (missingOutputFileName !== undefined) {
106928             return {
106929                 type: ts.UpToDateStatusType.OutputMissing,
106930                 missingOutputFileName: missingOutputFileName
106931             };
106932         }
106933         if (isOutOfDateWithInputs) {
106934             return {
106935                 type: ts.UpToDateStatusType.OutOfDateWithSelf,
106936                 outOfDateOutputFileName: oldestOutputFileName,
106937                 newerInputFileName: newestInputFileName
106938             };
106939         }
106940         else {
106941             // Check tsconfig time
106942             var configStatus = checkConfigFileUpToDateStatus(state, project.options.configFilePath, oldestOutputFileTime, oldestOutputFileName);
106943             if (configStatus)
106944                 return configStatus;
106945             // Check extended config time
106946             var extendedConfigStatus = ts.forEach(project.options.configFile.extendedSourceFiles || ts.emptyArray, function (configFile) { return checkConfigFileUpToDateStatus(state, configFile, oldestOutputFileTime, oldestOutputFileName); });
106947             if (extendedConfigStatus)
106948                 return extendedConfigStatus;
106949         }
106950         if (!state.buildInfoChecked.has(resolvedPath)) {
106951             state.buildInfoChecked.set(resolvedPath, true);
106952             var buildInfoPath = ts.getTsBuildInfoEmitOutputFilePath(project.options);
106953             if (buildInfoPath) {
106954                 var value = state.readFileWithCache(buildInfoPath);
106955                 var buildInfo = value && ts.getBuildInfo(value);
106956                 if (buildInfo && (buildInfo.bundle || buildInfo.program) && buildInfo.version !== ts.version) {
106957                     return {
106958                         type: ts.UpToDateStatusType.TsVersionOutputOfDate,
106959                         version: buildInfo.version
106960                     };
106961                 }
106962             }
106963         }
106964         if (usesPrepend && pseudoUpToDate) {
106965             return {
106966                 type: ts.UpToDateStatusType.OutOfDateWithPrepend,
106967                 outOfDateOutputFileName: oldestOutputFileName,
106968                 newerProjectName: upstreamChangedProject
106969             };
106970         }
106971         // Up to date
106972         return {
106973             type: pseudoUpToDate ? ts.UpToDateStatusType.UpToDateWithUpstreamTypes : ts.UpToDateStatusType.UpToDate,
106974             newestDeclarationFileContentChangedTime: newestDeclarationFileContentChangedTime,
106975             newestInputFileTime: newestInputFileTime,
106976             newestOutputFileTime: newestOutputFileTime,
106977             newestInputFileName: newestInputFileName,
106978             newestOutputFileName: newestOutputFileName,
106979             oldestOutputFileName: oldestOutputFileName
106980         };
106981     }
106982     function getUpToDateStatus(state, project, resolvedPath) {
106983         if (project === undefined) {
106984             return { type: ts.UpToDateStatusType.Unbuildable, reason: "File deleted mid-build" };
106985         }
106986         var prior = state.projectStatus.get(resolvedPath);
106987         if (prior !== undefined) {
106988             return prior;
106989         }
106990         var actual = getUpToDateStatusWorker(state, project, resolvedPath);
106991         state.projectStatus.set(resolvedPath, actual);
106992         return actual;
106993     }
106994     function updateOutputTimestampsWorker(state, proj, priorNewestUpdateTime, verboseMessage, skipOutputs) {
106995         var host = state.host;
106996         var outputs = ts.getAllProjectOutputs(proj, !host.useCaseSensitiveFileNames());
106997         if (!skipOutputs || outputs.length !== skipOutputs.size) {
106998             var reportVerbose = !!state.options.verbose;
106999             var now = host.now ? host.now() : new Date();
107000             for (var _i = 0, outputs_2 = outputs; _i < outputs_2.length; _i++) {
107001                 var file = outputs_2[_i];
107002                 if (skipOutputs && skipOutputs.has(toPath(state, file))) {
107003                     continue;
107004                 }
107005                 if (reportVerbose) {
107006                     reportVerbose = false;
107007                     reportStatus(state, verboseMessage, proj.options.configFilePath);
107008                 }
107009                 if (isDeclarationFile(file)) {
107010                     priorNewestUpdateTime = newer(priorNewestUpdateTime, host.getModifiedTime(file) || ts.missingFileModifiedTime);
107011                 }
107012                 host.setModifiedTime(file, now);
107013             }
107014         }
107015         return priorNewestUpdateTime;
107016     }
107017     function updateOutputTimestamps(state, proj, resolvedPath) {
107018         if (state.options.dry) {
107019             return reportStatus(state, ts.Diagnostics.A_non_dry_build_would_update_timestamps_for_output_of_project_0, proj.options.configFilePath);
107020         }
107021         var priorNewestUpdateTime = updateOutputTimestampsWorker(state, proj, minimumDate, ts.Diagnostics.Updating_output_timestamps_of_project_0);
107022         state.projectStatus.set(resolvedPath, {
107023             type: ts.UpToDateStatusType.UpToDate,
107024             newestDeclarationFileContentChangedTime: priorNewestUpdateTime,
107025             oldestOutputFileName: ts.getFirstProjectOutput(proj, !state.host.useCaseSensitiveFileNames())
107026         });
107027     }
107028     function queueReferencingProjects(state, project, projectPath, projectIndex, config, buildOrder, buildResult) {
107029         // Queue only if there are no errors
107030         if (buildResult & BuildResultFlags.AnyErrors)
107031             return;
107032         // Only composite projects can be referenced by other projects
107033         if (!config.options.composite)
107034             return;
107035         // Always use build order to queue projects
107036         for (var index = projectIndex + 1; index < buildOrder.length; index++) {
107037             var nextProject = buildOrder[index];
107038             var nextProjectPath = toResolvedConfigFilePath(state, nextProject);
107039             if (state.projectPendingBuild.has(nextProjectPath))
107040                 continue;
107041             var nextProjectConfig = parseConfigFile(state, nextProject, nextProjectPath);
107042             if (!nextProjectConfig || !nextProjectConfig.projectReferences)
107043                 continue;
107044             for (var _i = 0, _a = nextProjectConfig.projectReferences; _i < _a.length; _i++) {
107045                 var ref = _a[_i];
107046                 var resolvedRefPath = resolveProjectName(state, ref.path);
107047                 if (toResolvedConfigFilePath(state, resolvedRefPath) !== projectPath)
107048                     continue;
107049                 // If the project is referenced with prepend, always build downstream projects,
107050                 // If declaration output is changed, build the project
107051                 // otherwise mark the project UpToDateWithUpstreamTypes so it updates output time stamps
107052                 var status = state.projectStatus.get(nextProjectPath);
107053                 if (status) {
107054                     switch (status.type) {
107055                         case ts.UpToDateStatusType.UpToDate:
107056                             if (buildResult & BuildResultFlags.DeclarationOutputUnchanged) {
107057                                 if (ref.prepend) {
107058                                     state.projectStatus.set(nextProjectPath, {
107059                                         type: ts.UpToDateStatusType.OutOfDateWithPrepend,
107060                                         outOfDateOutputFileName: status.oldestOutputFileName,
107061                                         newerProjectName: project
107062                                     });
107063                                 }
107064                                 else {
107065                                     status.type = ts.UpToDateStatusType.UpToDateWithUpstreamTypes;
107066                                 }
107067                                 break;
107068                             }
107069                         // falls through
107070                         case ts.UpToDateStatusType.UpToDateWithUpstreamTypes:
107071                         case ts.UpToDateStatusType.OutOfDateWithPrepend:
107072                             if (!(buildResult & BuildResultFlags.DeclarationOutputUnchanged)) {
107073                                 state.projectStatus.set(nextProjectPath, {
107074                                     type: ts.UpToDateStatusType.OutOfDateWithUpstream,
107075                                     outOfDateOutputFileName: status.type === ts.UpToDateStatusType.OutOfDateWithPrepend ? status.outOfDateOutputFileName : status.oldestOutputFileName,
107076                                     newerProjectName: project
107077                                 });
107078                             }
107079                             break;
107080                         case ts.UpToDateStatusType.UpstreamBlocked:
107081                             if (toResolvedConfigFilePath(state, resolveProjectName(state, status.upstreamProjectName)) === projectPath) {
107082                                 clearProjectStatus(state, nextProjectPath);
107083                             }
107084                             break;
107085                     }
107086                 }
107087                 addProjToQueue(state, nextProjectPath, ts.ConfigFileProgramReloadLevel.None);
107088                 break;
107089             }
107090         }
107091     }
107092     function build(state, project, cancellationToken, onlyReferences) {
107093         var buildOrder = getBuildOrderFor(state, project, onlyReferences);
107094         if (!buildOrder)
107095             return ts.ExitStatus.InvalidProject_OutputsSkipped;
107096         setupInitialBuild(state, cancellationToken);
107097         var reportQueue = true;
107098         var successfulProjects = 0;
107099         while (true) {
107100             var invalidatedProject = getNextInvalidatedProject(state, buildOrder, reportQueue);
107101             if (!invalidatedProject)
107102                 break;
107103             reportQueue = false;
107104             invalidatedProject.done(cancellationToken);
107105             if (!state.diagnostics.has(invalidatedProject.projectPath))
107106                 successfulProjects++;
107107         }
107108         disableCache(state);
107109         reportErrorSummary(state, buildOrder);
107110         startWatching(state, buildOrder);
107111         return isCircularBuildOrder(buildOrder)
107112             ? ts.ExitStatus.ProjectReferenceCycle_OutputsSkipped
107113             : !buildOrder.some(function (p) { return state.diagnostics.has(toResolvedConfigFilePath(state, p)); })
107114                 ? ts.ExitStatus.Success
107115                 : successfulProjects
107116                     ? ts.ExitStatus.DiagnosticsPresent_OutputsGenerated
107117                     : ts.ExitStatus.DiagnosticsPresent_OutputsSkipped;
107118     }
107119     function clean(state, project, onlyReferences) {
107120         var buildOrder = getBuildOrderFor(state, project, onlyReferences);
107121         if (!buildOrder)
107122             return ts.ExitStatus.InvalidProject_OutputsSkipped;
107123         if (isCircularBuildOrder(buildOrder)) {
107124             reportErrors(state, buildOrder.circularDiagnostics);
107125             return ts.ExitStatus.ProjectReferenceCycle_OutputsSkipped;
107126         }
107127         var options = state.options, host = state.host;
107128         var filesToDelete = options.dry ? [] : undefined;
107129         for (var _i = 0, buildOrder_1 = buildOrder; _i < buildOrder_1.length; _i++) {
107130             var proj = buildOrder_1[_i];
107131             var resolvedPath = toResolvedConfigFilePath(state, proj);
107132             var parsed = parseConfigFile(state, proj, resolvedPath);
107133             if (parsed === undefined) {
107134                 // File has gone missing; fine to ignore here
107135                 reportParseConfigFileDiagnostic(state, resolvedPath);
107136                 continue;
107137             }
107138             var outputs = ts.getAllProjectOutputs(parsed, !host.useCaseSensitiveFileNames());
107139             for (var _a = 0, outputs_3 = outputs; _a < outputs_3.length; _a++) {
107140                 var output = outputs_3[_a];
107141                 if (host.fileExists(output)) {
107142                     if (filesToDelete) {
107143                         filesToDelete.push(output);
107144                     }
107145                     else {
107146                         host.deleteFile(output);
107147                         invalidateProject(state, resolvedPath, ts.ConfigFileProgramReloadLevel.None);
107148                     }
107149                 }
107150             }
107151         }
107152         if (filesToDelete) {
107153             reportStatus(state, ts.Diagnostics.A_non_dry_build_would_delete_the_following_files_Colon_0, filesToDelete.map(function (f) { return "\r\n * " + f; }).join(""));
107154         }
107155         return ts.ExitStatus.Success;
107156     }
107157     function invalidateProject(state, resolved, reloadLevel) {
107158         // If host implements getParsedCommandLine, we cant get list of files from parseConfigFileHost
107159         if (state.host.getParsedCommandLine && reloadLevel === ts.ConfigFileProgramReloadLevel.Partial) {
107160             reloadLevel = ts.ConfigFileProgramReloadLevel.Full;
107161         }
107162         if (reloadLevel === ts.ConfigFileProgramReloadLevel.Full) {
107163             state.configFileCache.delete(resolved);
107164             state.buildOrder = undefined;
107165         }
107166         state.needsSummary = true;
107167         clearProjectStatus(state, resolved);
107168         addProjToQueue(state, resolved, reloadLevel);
107169         enableCache(state);
107170     }
107171     function invalidateProjectAndScheduleBuilds(state, resolvedPath, reloadLevel) {
107172         state.reportFileChangeDetected = true;
107173         invalidateProject(state, resolvedPath, reloadLevel);
107174         scheduleBuildInvalidatedProject(state);
107175     }
107176     function scheduleBuildInvalidatedProject(state) {
107177         var hostWithWatch = state.hostWithWatch;
107178         if (!hostWithWatch.setTimeout || !hostWithWatch.clearTimeout) {
107179             return;
107180         }
107181         if (state.timerToBuildInvalidatedProject) {
107182             hostWithWatch.clearTimeout(state.timerToBuildInvalidatedProject);
107183         }
107184         state.timerToBuildInvalidatedProject = hostWithWatch.setTimeout(buildNextInvalidatedProject, 250, state);
107185     }
107186     function buildNextInvalidatedProject(state) {
107187         state.timerToBuildInvalidatedProject = undefined;
107188         if (state.reportFileChangeDetected) {
107189             state.reportFileChangeDetected = false;
107190             state.projectErrorsReported.clear();
107191             reportWatchStatus(state, ts.Diagnostics.File_change_detected_Starting_incremental_compilation);
107192         }
107193         var buildOrder = getBuildOrder(state);
107194         var invalidatedProject = getNextInvalidatedProject(state, buildOrder, /*reportQueue*/ false);
107195         if (invalidatedProject) {
107196             invalidatedProject.done();
107197             if (state.projectPendingBuild.size) {
107198                 // Schedule next project for build
107199                 if (state.watch && !state.timerToBuildInvalidatedProject) {
107200                     scheduleBuildInvalidatedProject(state);
107201                 }
107202                 return;
107203             }
107204         }
107205         disableCache(state);
107206         reportErrorSummary(state, buildOrder);
107207     }
107208     function watchConfigFile(state, resolved, resolvedPath, parsed) {
107209         if (!state.watch || state.allWatchedConfigFiles.has(resolvedPath))
107210             return;
107211         state.allWatchedConfigFiles.set(resolvedPath, state.watchFile(state.hostWithWatch, resolved, function () {
107212             invalidateProjectAndScheduleBuilds(state, resolvedPath, ts.ConfigFileProgramReloadLevel.Full);
107213         }, ts.PollingInterval.High, parsed === null || parsed === void 0 ? void 0 : parsed.watchOptions, ts.WatchType.ConfigFile, resolved));
107214     }
107215     function isSameFile(state, file1, file2) {
107216         return ts.comparePaths(file1, file2, state.currentDirectory, !state.host.useCaseSensitiveFileNames()) === 0 /* EqualTo */;
107217     }
107218     function isOutputFile(state, fileName, configFile) {
107219         if (configFile.options.noEmit)
107220             return false;
107221         // ts or tsx files are not output
107222         if (!ts.fileExtensionIs(fileName, ".d.ts" /* Dts */) &&
107223             (ts.fileExtensionIs(fileName, ".ts" /* Ts */) || ts.fileExtensionIs(fileName, ".tsx" /* Tsx */))) {
107224             return false;
107225         }
107226         // If options have --outFile or --out, check if its that
107227         var out = configFile.options.outFile || configFile.options.out;
107228         if (out && (isSameFile(state, fileName, out) || isSameFile(state, fileName, ts.removeFileExtension(out) + ".d.ts" /* Dts */))) {
107229             return true;
107230         }
107231         // If declarationDir is specified, return if its a file in that directory
107232         if (configFile.options.declarationDir && ts.containsPath(configFile.options.declarationDir, fileName, state.currentDirectory, !state.host.useCaseSensitiveFileNames())) {
107233             return true;
107234         }
107235         // If --outDir, check if file is in that directory
107236         if (configFile.options.outDir && ts.containsPath(configFile.options.outDir, fileName, state.currentDirectory, !state.host.useCaseSensitiveFileNames())) {
107237             return true;
107238         }
107239         return !ts.forEach(configFile.fileNames, function (inputFile) { return isSameFile(state, fileName, inputFile); });
107240     }
107241     function watchWildCardDirectories(state, resolved, resolvedPath, parsed) {
107242         if (!state.watch)
107243             return;
107244         ts.updateWatchingWildcardDirectories(getOrCreateValueMapFromConfigFileMap(state.allWatchedWildcardDirectories, resolvedPath), ts.createMapFromTemplate(parsed.configFileSpecs.wildcardDirectories), function (dir, flags) { return state.watchDirectory(state.hostWithWatch, dir, function (fileOrDirectory) {
107245             var fileOrDirectoryPath = toPath(state, fileOrDirectory);
107246             if (fileOrDirectoryPath !== toPath(state, dir) && ts.hasExtension(fileOrDirectoryPath) && !ts.isSupportedSourceFileName(fileOrDirectory, parsed.options)) {
107247                 state.writeLog("Project: " + resolved + " Detected file add/remove of non supported extension: " + fileOrDirectory);
107248                 return;
107249             }
107250             if (isOutputFile(state, fileOrDirectory, parsed)) {
107251                 state.writeLog(fileOrDirectory + " is output file");
107252                 return;
107253             }
107254             invalidateProjectAndScheduleBuilds(state, resolvedPath, ts.ConfigFileProgramReloadLevel.Partial);
107255         }, flags, parsed === null || parsed === void 0 ? void 0 : parsed.watchOptions, ts.WatchType.WildcardDirectory, resolved); });
107256     }
107257     function watchInputFiles(state, resolved, resolvedPath, parsed) {
107258         if (!state.watch)
107259             return;
107260         ts.mutateMap(getOrCreateValueMapFromConfigFileMap(state.allWatchedInputFiles, resolvedPath), ts.arrayToMap(parsed.fileNames, function (fileName) { return toPath(state, fileName); }), {
107261             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); },
107262             onDeleteValue: ts.closeFileWatcher,
107263         });
107264     }
107265     function startWatching(state, buildOrder) {
107266         if (!state.watchAllProjectsPending)
107267             return;
107268         state.watchAllProjectsPending = false;
107269         for (var _i = 0, _a = getBuildOrderFromAnyBuildOrder(buildOrder); _i < _a.length; _i++) {
107270             var resolved = _a[_i];
107271             var resolvedPath = toResolvedConfigFilePath(state, resolved);
107272             var cfg = parseConfigFile(state, resolved, resolvedPath);
107273             // Watch this file
107274             watchConfigFile(state, resolved, resolvedPath, cfg);
107275             if (cfg) {
107276                 // Update watchers for wildcard directories
107277                 watchWildCardDirectories(state, resolved, resolvedPath, cfg);
107278                 // Watch input files
107279                 watchInputFiles(state, resolved, resolvedPath, cfg);
107280             }
107281         }
107282     }
107283     function stopWatching(state) {
107284         ts.clearMap(state.allWatchedConfigFiles, ts.closeFileWatcher);
107285         ts.clearMap(state.allWatchedWildcardDirectories, function (watchedWildcardDirectories) { return ts.clearMap(watchedWildcardDirectories, ts.closeFileWatcherOf); });
107286         ts.clearMap(state.allWatchedInputFiles, function (watchedWildcardDirectories) { return ts.clearMap(watchedWildcardDirectories, ts.closeFileWatcher); });
107287     }
107288     function createSolutionBuilderWorker(watch, hostOrHostWithWatch, rootNames, options, baseWatchOptions) {
107289         var state = createSolutionBuilderState(watch, hostOrHostWithWatch, rootNames, options, baseWatchOptions);
107290         return {
107291             build: function (project, cancellationToken) { return build(state, project, cancellationToken); },
107292             clean: function (project) { return clean(state, project); },
107293             buildReferences: function (project, cancellationToken) { return build(state, project, cancellationToken, /*onlyReferences*/ true); },
107294             cleanReferences: function (project) { return clean(state, project, /*onlyReferences*/ true); },
107295             getNextInvalidatedProject: function (cancellationToken) {
107296                 setupInitialBuild(state, cancellationToken);
107297                 return getNextInvalidatedProject(state, getBuildOrder(state), /*reportQueue*/ false);
107298             },
107299             getBuildOrder: function () { return getBuildOrder(state); },
107300             getUpToDateStatusOfProject: function (project) {
107301                 var configFileName = resolveProjectName(state, project);
107302                 var configFilePath = toResolvedConfigFilePath(state, configFileName);
107303                 return getUpToDateStatus(state, parseConfigFile(state, configFileName, configFilePath), configFilePath);
107304             },
107305             invalidateProject: function (configFilePath, reloadLevel) { return invalidateProject(state, configFilePath, reloadLevel || ts.ConfigFileProgramReloadLevel.None); },
107306             buildNextInvalidatedProject: function () { return buildNextInvalidatedProject(state); },
107307             getAllParsedConfigs: function () { return ts.arrayFrom(ts.mapDefinedIterator(state.configFileCache.values(), function (config) { return isParsedCommandLine(config) ? config : undefined; })); },
107308             close: function () { return stopWatching(state); },
107309         };
107310     }
107311     function relName(state, path) {
107312         return ts.convertToRelativePath(path, state.currentDirectory, function (f) { return state.getCanonicalFileName(f); });
107313     }
107314     function reportStatus(state, message) {
107315         var args = [];
107316         for (var _i = 2; _i < arguments.length; _i++) {
107317             args[_i - 2] = arguments[_i];
107318         }
107319         state.host.reportSolutionBuilderStatus(ts.createCompilerDiagnostic.apply(void 0, __spreadArrays([message], args)));
107320     }
107321     function reportWatchStatus(state, message) {
107322         var args = [];
107323         for (var _i = 2; _i < arguments.length; _i++) {
107324             args[_i - 2] = arguments[_i];
107325         }
107326         if (state.hostWithWatch.onWatchStatusChange) {
107327             state.hostWithWatch.onWatchStatusChange(ts.createCompilerDiagnostic.apply(void 0, __spreadArrays([message], args)), state.host.getNewLine(), state.baseCompilerOptions);
107328         }
107329     }
107330     function reportErrors(_a, errors) {
107331         var host = _a.host;
107332         errors.forEach(function (err) { return host.reportDiagnostic(err); });
107333     }
107334     function reportAndStoreErrors(state, proj, errors) {
107335         reportErrors(state, errors);
107336         state.projectErrorsReported.set(proj, true);
107337         if (errors.length) {
107338             state.diagnostics.set(proj, errors);
107339         }
107340     }
107341     function reportParseConfigFileDiagnostic(state, proj) {
107342         reportAndStoreErrors(state, proj, [state.configFileCache.get(proj)]);
107343     }
107344     function reportErrorSummary(state, buildOrder) {
107345         if (!state.needsSummary)
107346             return;
107347         state.needsSummary = false;
107348         var canReportSummary = state.watch || !!state.host.reportErrorSummary;
107349         var diagnostics = state.diagnostics;
107350         var totalErrors = 0;
107351         if (isCircularBuildOrder(buildOrder)) {
107352             reportBuildQueue(state, buildOrder.buildOrder);
107353             reportErrors(state, buildOrder.circularDiagnostics);
107354             if (canReportSummary)
107355                 totalErrors += ts.getErrorCountForSummary(buildOrder.circularDiagnostics);
107356         }
107357         else {
107358             // Report errors from the other projects
107359             buildOrder.forEach(function (project) {
107360                 var projectPath = toResolvedConfigFilePath(state, project);
107361                 if (!state.projectErrorsReported.has(projectPath)) {
107362                     reportErrors(state, diagnostics.get(projectPath) || ts.emptyArray);
107363                 }
107364             });
107365             if (canReportSummary)
107366                 diagnostics.forEach(function (singleProjectErrors) { return totalErrors += ts.getErrorCountForSummary(singleProjectErrors); });
107367         }
107368         if (state.watch) {
107369             reportWatchStatus(state, ts.getWatchErrorSummaryDiagnosticMessage(totalErrors), totalErrors);
107370         }
107371         else if (state.host.reportErrorSummary) {
107372             state.host.reportErrorSummary(totalErrors);
107373         }
107374     }
107375     /**
107376      * Report the build ordering inferred from the current project graph if we're in verbose mode
107377      */
107378     function reportBuildQueue(state, buildQueue) {
107379         if (state.options.verbose) {
107380             reportStatus(state, ts.Diagnostics.Projects_in_this_build_Colon_0, buildQueue.map(function (s) { return "\r\n    * " + relName(state, s); }).join(""));
107381         }
107382     }
107383     function reportUpToDateStatus(state, configFileName, status) {
107384         switch (status.type) {
107385             case ts.UpToDateStatusType.OutOfDateWithSelf:
107386                 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));
107387             case ts.UpToDateStatusType.OutOfDateWithUpstream:
107388                 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));
107389             case ts.UpToDateStatusType.OutputMissing:
107390                 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));
107391             case ts.UpToDateStatusType.UpToDate:
107392                 if (status.newestInputFileTime !== undefined) {
107393                     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 || ""));
107394                 }
107395                 // Don't report anything for "up to date because it was already built" -- too verbose
107396                 break;
107397             case ts.UpToDateStatusType.OutOfDateWithPrepend:
107398                 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));
107399             case ts.UpToDateStatusType.UpToDateWithUpstreamTypes:
107400                 return reportStatus(state, ts.Diagnostics.Project_0_is_up_to_date_with_d_ts_files_from_its_dependencies, relName(state, configFileName));
107401             case ts.UpToDateStatusType.UpstreamOutOfDate:
107402                 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));
107403             case ts.UpToDateStatusType.UpstreamBlocked:
107404                 return reportStatus(state, status.upstreamProjectBlocked ?
107405                     ts.Diagnostics.Project_0_can_t_be_built_because_its_dependency_1_was_not_built :
107406                     ts.Diagnostics.Project_0_can_t_be_built_because_its_dependency_1_has_errors, relName(state, configFileName), relName(state, status.upstreamProjectName));
107407             case ts.UpToDateStatusType.Unbuildable:
107408                 return reportStatus(state, ts.Diagnostics.Failed_to_parse_file_0_Colon_1, relName(state, configFileName), status.reason);
107409             case ts.UpToDateStatusType.TsVersionOutputOfDate:
107410                 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);
107411             case ts.UpToDateStatusType.ContainerOnly:
107412             // Don't report status on "solution" projects
107413             // falls through
107414             case ts.UpToDateStatusType.ComputingUpstream:
107415                 // Should never leak from getUptoDateStatusWorker
107416                 break;
107417             default:
107418                 ts.assertType(status);
107419         }
107420     }
107421     /**
107422      * Report the up-to-date status of a project if we're in verbose mode
107423      */
107424     function verboseReportProjectStatus(state, configFileName, status) {
107425         if (state.options.verbose) {
107426             reportUpToDateStatus(state, configFileName, status);
107427         }
107428     }
107429 })(ts || (ts = {}));
107430 var ts;
107431 (function (ts) {
107432     var server;
107433     (function (server) {
107434         /* @internal */
107435         server.ActionSet = "action::set";
107436         /* @internal */
107437         server.ActionInvalidate = "action::invalidate";
107438         /* @internal */
107439         server.ActionPackageInstalled = "action::packageInstalled";
107440         /* @internal */
107441         server.EventTypesRegistry = "event::typesRegistry";
107442         /* @internal */
107443         server.EventBeginInstallTypes = "event::beginInstallTypes";
107444         /* @internal */
107445         server.EventEndInstallTypes = "event::endInstallTypes";
107446         /* @internal */
107447         server.EventInitializationFailed = "event::initializationFailed";
107448         /* @internal */
107449         var Arguments;
107450         (function (Arguments) {
107451             Arguments.GlobalCacheLocation = "--globalTypingsCacheLocation";
107452             Arguments.LogFile = "--logFile";
107453             Arguments.EnableTelemetry = "--enableTelemetry";
107454             Arguments.TypingSafeListLocation = "--typingSafeListLocation";
107455             Arguments.TypesMapLocation = "--typesMapLocation";
107456             /**
107457              * This argument specifies the location of the NPM executable.
107458              * typingsInstaller will run the command with `${npmLocation} install ...`.
107459              */
107460             Arguments.NpmLocation = "--npmLocation";
107461             /**
107462              * Flag indicating that the typings installer should try to validate the default npm location.
107463              * If the default npm is not found when this flag is enabled, fallback to `npm install`
107464              */
107465             Arguments.ValidateDefaultNpmLocation = "--validateDefaultNpmLocation";
107466         })(Arguments = server.Arguments || (server.Arguments = {}));
107467         /* @internal */
107468         function hasArgument(argumentName) {
107469             return ts.sys.args.indexOf(argumentName) >= 0;
107470         }
107471         server.hasArgument = hasArgument;
107472         /* @internal */
107473         function findArgument(argumentName) {
107474             var index = ts.sys.args.indexOf(argumentName);
107475             return index >= 0 && index < ts.sys.args.length - 1
107476                 ? ts.sys.args[index + 1]
107477                 : undefined;
107478         }
107479         server.findArgument = findArgument;
107480         /* @internal */
107481         function nowString() {
107482             // E.g. "12:34:56.789"
107483             var d = new Date();
107484             return d.getHours() + ":" + d.getMinutes() + ":" + d.getSeconds() + "." + d.getMilliseconds();
107485         }
107486         server.nowString = nowString;
107487     })(server = ts.server || (ts.server = {}));
107488 })(ts || (ts = {}));
107489 /* @internal */
107490 var ts;
107491 (function (ts) {
107492     var JsTyping;
107493     (function (JsTyping) {
107494         function isTypingUpToDate(cachedTyping, availableTypingVersions) {
107495             var availableVersion = new ts.Version(ts.getProperty(availableTypingVersions, "ts" + ts.versionMajorMinor) || ts.getProperty(availableTypingVersions, "latest"));
107496             return availableVersion.compareTo(cachedTyping.version) <= 0;
107497         }
107498         JsTyping.isTypingUpToDate = isTypingUpToDate;
107499         JsTyping.nodeCoreModuleList = [
107500             "assert",
107501             "async_hooks",
107502             "buffer",
107503             "child_process",
107504             "cluster",
107505             "console",
107506             "constants",
107507             "crypto",
107508             "dgram",
107509             "dns",
107510             "domain",
107511             "events",
107512             "fs",
107513             "http",
107514             "https",
107515             "http2",
107516             "inspector",
107517             "net",
107518             "os",
107519             "path",
107520             "perf_hooks",
107521             "process",
107522             "punycode",
107523             "querystring",
107524             "readline",
107525             "repl",
107526             "stream",
107527             "string_decoder",
107528             "timers",
107529             "tls",
107530             "tty",
107531             "url",
107532             "util",
107533             "v8",
107534             "vm",
107535             "zlib"
107536         ];
107537         JsTyping.nodeCoreModules = ts.arrayToSet(JsTyping.nodeCoreModuleList);
107538         function nonRelativeModuleNameForTypingCache(moduleName) {
107539             return JsTyping.nodeCoreModules.has(moduleName) ? "node" : moduleName;
107540         }
107541         JsTyping.nonRelativeModuleNameForTypingCache = nonRelativeModuleNameForTypingCache;
107542         function loadSafeList(host, safeListPath) {
107543             var result = ts.readConfigFile(safeListPath, function (path) { return host.readFile(path); });
107544             return ts.createMapFromTemplate(result.config);
107545         }
107546         JsTyping.loadSafeList = loadSafeList;
107547         function loadTypesMap(host, typesMapPath) {
107548             var result = ts.readConfigFile(typesMapPath, function (path) { return host.readFile(path); });
107549             if (result.config) {
107550                 return ts.createMapFromTemplate(result.config.simpleMap);
107551             }
107552             return undefined;
107553         }
107554         JsTyping.loadTypesMap = loadTypesMap;
107555         /**
107556          * @param host is the object providing I/O related operations.
107557          * @param fileNames are the file names that belong to the same project
107558          * @param projectRootPath is the path to the project root directory
107559          * @param safeListPath is the path used to retrieve the safe list
107560          * @param packageNameToTypingLocation is the map of package names to their cached typing locations and installed versions
107561          * @param typeAcquisition is used to customize the typing acquisition process
107562          * @param compilerOptions are used as a source for typing inference
107563          */
107564         function discoverTypings(host, log, fileNames, projectRootPath, safeList, packageNameToTypingLocation, typeAcquisition, unresolvedImports, typesRegistry) {
107565             if (!typeAcquisition || !typeAcquisition.enable) {
107566                 return { cachedTypingPaths: [], newTypingNames: [], filesToWatch: [] };
107567             }
107568             // A typing name to typing file path mapping
107569             var inferredTypings = ts.createMap();
107570             // Only infer typings for .js and .jsx files
107571             fileNames = ts.mapDefined(fileNames, function (fileName) {
107572                 var path = ts.normalizePath(fileName);
107573                 if (ts.hasJSFileExtension(path)) {
107574                     return path;
107575                 }
107576             });
107577             var filesToWatch = [];
107578             if (typeAcquisition.include)
107579                 addInferredTypings(typeAcquisition.include, "Explicitly included types");
107580             var exclude = typeAcquisition.exclude || [];
107581             // Directories to search for package.json, bower.json and other typing information
107582             var possibleSearchDirs = ts.arrayToSet(fileNames, ts.getDirectoryPath);
107583             possibleSearchDirs.set(projectRootPath, true);
107584             possibleSearchDirs.forEach(function (_true, searchDir) {
107585                 var packageJsonPath = ts.combinePaths(searchDir, "package.json");
107586                 getTypingNamesFromJson(packageJsonPath, filesToWatch);
107587                 var bowerJsonPath = ts.combinePaths(searchDir, "bower.json");
107588                 getTypingNamesFromJson(bowerJsonPath, filesToWatch);
107589                 var bowerComponentsPath = ts.combinePaths(searchDir, "bower_components");
107590                 getTypingNamesFromPackagesFolder(bowerComponentsPath, filesToWatch);
107591                 var nodeModulesPath = ts.combinePaths(searchDir, "node_modules");
107592                 getTypingNamesFromPackagesFolder(nodeModulesPath, filesToWatch);
107593             });
107594             getTypingNamesFromSourceFileNames(fileNames);
107595             // add typings for unresolved imports
107596             if (unresolvedImports) {
107597                 var module_1 = ts.deduplicate(unresolvedImports.map(nonRelativeModuleNameForTypingCache), ts.equateStringsCaseSensitive, ts.compareStringsCaseSensitive);
107598                 addInferredTypings(module_1, "Inferred typings from unresolved imports");
107599             }
107600             // Add the cached typing locations for inferred typings that are already installed
107601             packageNameToTypingLocation.forEach(function (typing, name) {
107602                 var registryEntry = typesRegistry.get(name);
107603                 if (inferredTypings.has(name) && inferredTypings.get(name) === undefined && registryEntry !== undefined && isTypingUpToDate(typing, registryEntry)) {
107604                     inferredTypings.set(name, typing.typingLocation);
107605                 }
107606             });
107607             // Remove typings that the user has added to the exclude list
107608             for (var _i = 0, exclude_1 = exclude; _i < exclude_1.length; _i++) {
107609                 var excludeTypingName = exclude_1[_i];
107610                 var didDelete = inferredTypings.delete(excludeTypingName);
107611                 if (didDelete && log)
107612                     log("Typing for " + excludeTypingName + " is in exclude list, will be ignored.");
107613             }
107614             var newTypingNames = [];
107615             var cachedTypingPaths = [];
107616             inferredTypings.forEach(function (inferred, typing) {
107617                 if (inferred !== undefined) {
107618                     cachedTypingPaths.push(inferred);
107619                 }
107620                 else {
107621                     newTypingNames.push(typing);
107622                 }
107623             });
107624             var result = { cachedTypingPaths: cachedTypingPaths, newTypingNames: newTypingNames, filesToWatch: filesToWatch };
107625             if (log)
107626                 log("Result: " + JSON.stringify(result));
107627             return result;
107628             function addInferredTyping(typingName) {
107629                 if (!inferredTypings.has(typingName)) {
107630                     inferredTypings.set(typingName, undefined); // TODO: GH#18217
107631                 }
107632             }
107633             function addInferredTypings(typingNames, message) {
107634                 if (log)
107635                     log(message + ": " + JSON.stringify(typingNames));
107636                 ts.forEach(typingNames, addInferredTyping);
107637             }
107638             /**
107639              * Get the typing info from common package manager json files like package.json or bower.json
107640              */
107641             function getTypingNamesFromJson(jsonPath, filesToWatch) {
107642                 if (!host.fileExists(jsonPath)) {
107643                     return;
107644                 }
107645                 filesToWatch.push(jsonPath);
107646                 var jsonConfig = ts.readConfigFile(jsonPath, function (path) { return host.readFile(path); }).config;
107647                 var jsonTypingNames = ts.flatMap([jsonConfig.dependencies, jsonConfig.devDependencies, jsonConfig.optionalDependencies, jsonConfig.peerDependencies], ts.getOwnKeys);
107648                 addInferredTypings(jsonTypingNames, "Typing names in '" + jsonPath + "' dependencies");
107649             }
107650             /**
107651              * Infer typing names from given file names. For example, the file name "jquery-min.2.3.4.js"
107652              * should be inferred to the 'jquery' typing name; and "angular-route.1.2.3.js" should be inferred
107653              * to the 'angular-route' typing name.
107654              * @param fileNames are the names for source files in the project
107655              */
107656             function getTypingNamesFromSourceFileNames(fileNames) {
107657                 var fromFileNames = ts.mapDefined(fileNames, function (j) {
107658                     if (!ts.hasJSFileExtension(j))
107659                         return undefined;
107660                     var inferredTypingName = ts.removeFileExtension(ts.getBaseFileName(j.toLowerCase()));
107661                     var cleanedTypingName = ts.removeMinAndVersionNumbers(inferredTypingName);
107662                     return safeList.get(cleanedTypingName);
107663                 });
107664                 if (fromFileNames.length) {
107665                     addInferredTypings(fromFileNames, "Inferred typings from file names");
107666                 }
107667                 var hasJsxFile = ts.some(fileNames, function (f) { return ts.fileExtensionIs(f, ".jsx" /* Jsx */); });
107668                 if (hasJsxFile) {
107669                     if (log)
107670                         log("Inferred 'react' typings due to presence of '.jsx' extension");
107671                     addInferredTyping("react");
107672                 }
107673             }
107674             /**
107675              * Infer typing names from packages folder (ex: node_module, bower_components)
107676              * @param packagesFolderPath is the path to the packages folder
107677              */
107678             function getTypingNamesFromPackagesFolder(packagesFolderPath, filesToWatch) {
107679                 filesToWatch.push(packagesFolderPath);
107680                 // Todo: add support for ModuleResolutionHost too
107681                 if (!host.directoryExists(packagesFolderPath)) {
107682                     return;
107683                 }
107684                 // depth of 2, so we access `node_modules/foo` but not `node_modules/foo/bar`
107685                 var fileNames = host.readDirectory(packagesFolderPath, [".json" /* Json */], /*excludes*/ undefined, /*includes*/ undefined, /*depth*/ 2);
107686                 if (log)
107687                     log("Searching for typing names in " + packagesFolderPath + "; all files: " + JSON.stringify(fileNames));
107688                 var packageNames = [];
107689                 for (var _i = 0, fileNames_1 = fileNames; _i < fileNames_1.length; _i++) {
107690                     var fileName = fileNames_1[_i];
107691                     var normalizedFileName = ts.normalizePath(fileName);
107692                     var baseFileName = ts.getBaseFileName(normalizedFileName);
107693                     if (baseFileName !== "package.json" && baseFileName !== "bower.json") {
107694                         continue;
107695                     }
107696                     var result_1 = ts.readConfigFile(normalizedFileName, function (path) { return host.readFile(path); });
107697                     var packageJson = result_1.config;
107698                     // npm 3's package.json contains a "_requiredBy" field
107699                     // we should include all the top level module names for npm 2, and only module names whose
107700                     // "_requiredBy" field starts with "#" or equals "/" for npm 3.
107701                     if (baseFileName === "package.json" && packageJson._requiredBy &&
107702                         ts.filter(packageJson._requiredBy, function (r) { return r[0] === "#" || r === "/"; }).length === 0) {
107703                         continue;
107704                     }
107705                     // If the package has its own d.ts typings, those will take precedence. Otherwise the package name will be used
107706                     // to download d.ts files from DefinitelyTyped
107707                     if (!packageJson.name) {
107708                         continue;
107709                     }
107710                     var ownTypes = packageJson.types || packageJson.typings;
107711                     if (ownTypes) {
107712                         var absolutePath = ts.getNormalizedAbsolutePath(ownTypes, ts.getDirectoryPath(normalizedFileName));
107713                         if (log)
107714                             log("    Package '" + packageJson.name + "' provides its own types.");
107715                         inferredTypings.set(packageJson.name, absolutePath);
107716                     }
107717                     else {
107718                         packageNames.push(packageJson.name);
107719                     }
107720                 }
107721                 addInferredTypings(packageNames, "    Found package names");
107722             }
107723         }
107724         JsTyping.discoverTypings = discoverTypings;
107725         var NameValidationResult;
107726         (function (NameValidationResult) {
107727             NameValidationResult[NameValidationResult["Ok"] = 0] = "Ok";
107728             NameValidationResult[NameValidationResult["EmptyName"] = 1] = "EmptyName";
107729             NameValidationResult[NameValidationResult["NameTooLong"] = 2] = "NameTooLong";
107730             NameValidationResult[NameValidationResult["NameStartsWithDot"] = 3] = "NameStartsWithDot";
107731             NameValidationResult[NameValidationResult["NameStartsWithUnderscore"] = 4] = "NameStartsWithUnderscore";
107732             NameValidationResult[NameValidationResult["NameContainsNonURISafeCharacters"] = 5] = "NameContainsNonURISafeCharacters";
107733         })(NameValidationResult = JsTyping.NameValidationResult || (JsTyping.NameValidationResult = {}));
107734         var maxPackageNameLength = 214;
107735         /**
107736          * Validates package name using rules defined at https://docs.npmjs.com/files/package.json
107737          */
107738         function validatePackageName(packageName) {
107739             return validatePackageNameWorker(packageName, /*supportScopedPackage*/ true);
107740         }
107741         JsTyping.validatePackageName = validatePackageName;
107742         function validatePackageNameWorker(packageName, supportScopedPackage) {
107743             if (!packageName) {
107744                 return 1 /* EmptyName */;
107745             }
107746             if (packageName.length > maxPackageNameLength) {
107747                 return 2 /* NameTooLong */;
107748             }
107749             if (packageName.charCodeAt(0) === 46 /* dot */) {
107750                 return 3 /* NameStartsWithDot */;
107751             }
107752             if (packageName.charCodeAt(0) === 95 /* _ */) {
107753                 return 4 /* NameStartsWithUnderscore */;
107754             }
107755             // check if name is scope package like: starts with @ and has one '/' in the middle
107756             // scoped packages are not currently supported
107757             if (supportScopedPackage) {
107758                 var matches = /^@([^/]+)\/([^/]+)$/.exec(packageName);
107759                 if (matches) {
107760                     var scopeResult = validatePackageNameWorker(matches[1], /*supportScopedPackage*/ false);
107761                     if (scopeResult !== 0 /* Ok */) {
107762                         return { name: matches[1], isScopeName: true, result: scopeResult };
107763                     }
107764                     var packageResult = validatePackageNameWorker(matches[2], /*supportScopedPackage*/ false);
107765                     if (packageResult !== 0 /* Ok */) {
107766                         return { name: matches[2], isScopeName: false, result: packageResult };
107767                     }
107768                     return 0 /* Ok */;
107769                 }
107770             }
107771             if (encodeURIComponent(packageName) !== packageName) {
107772                 return 5 /* NameContainsNonURISafeCharacters */;
107773             }
107774             return 0 /* Ok */;
107775         }
107776         function renderPackageNameValidationFailure(result, typing) {
107777             return typeof result === "object" ?
107778                 renderPackageNameValidationFailureWorker(typing, result.result, result.name, result.isScopeName) :
107779                 renderPackageNameValidationFailureWorker(typing, result, typing, /*isScopeName*/ false);
107780         }
107781         JsTyping.renderPackageNameValidationFailure = renderPackageNameValidationFailure;
107782         function renderPackageNameValidationFailureWorker(typing, result, name, isScopeName) {
107783             var kind = isScopeName ? "Scope" : "Package";
107784             switch (result) {
107785                 case 1 /* EmptyName */:
107786                     return "'" + typing + "':: " + kind + " name '" + name + "' cannot be empty";
107787                 case 2 /* NameTooLong */:
107788                     return "'" + typing + "':: " + kind + " name '" + name + "' should be less than " + maxPackageNameLength + " characters";
107789                 case 3 /* NameStartsWithDot */:
107790                     return "'" + typing + "':: " + kind + " name '" + name + "' cannot start with '.'";
107791                 case 4 /* NameStartsWithUnderscore */:
107792                     return "'" + typing + "':: " + kind + " name '" + name + "' cannot start with '_'";
107793                 case 5 /* NameContainsNonURISafeCharacters */:
107794                     return "'" + typing + "':: " + kind + " name '" + name + "' contains non URI safe characters";
107795                 case 0 /* Ok */:
107796                     return ts.Debug.fail(); // Shouldn't have called this.
107797                 default:
107798                     throw ts.Debug.assertNever(result);
107799             }
107800         }
107801     })(JsTyping = ts.JsTyping || (ts.JsTyping = {}));
107802 })(ts || (ts = {}));
107803 var ts;
107804 (function (ts) {
107805     var server;
107806     (function (server) {
107807         var typingsInstaller;
107808         (function (typingsInstaller) {
107809             var nullLog = {
107810                 isEnabled: function () { return false; },
107811                 writeLine: ts.noop
107812             };
107813             function typingToFileName(cachePath, packageName, installTypingHost, log) {
107814                 try {
107815                     var result = ts.resolveModuleName(packageName, ts.combinePaths(cachePath, "index.d.ts"), { moduleResolution: ts.ModuleResolutionKind.NodeJs }, installTypingHost);
107816                     return result.resolvedModule && result.resolvedModule.resolvedFileName;
107817                 }
107818                 catch (e) {
107819                     if (log.isEnabled()) {
107820                         log.writeLine("Failed to resolve " + packageName + " in folder '" + cachePath + "': " + e.message);
107821                     }
107822                     return undefined;
107823                 }
107824             }
107825             /*@internal*/
107826             function installNpmPackages(npmPath, tsVersion, packageNames, install) {
107827                 var hasError = false;
107828                 for (var remaining = packageNames.length; remaining > 0;) {
107829                     var result = getNpmCommandForInstallation(npmPath, tsVersion, packageNames, remaining);
107830                     remaining = result.remaining;
107831                     hasError = install(result.command) || hasError;
107832                 }
107833                 return hasError;
107834             }
107835             typingsInstaller.installNpmPackages = installNpmPackages;
107836             /*@internal*/
107837             function getNpmCommandForInstallation(npmPath, tsVersion, packageNames, remaining) {
107838                 var sliceStart = packageNames.length - remaining;
107839                 var command, toSlice = remaining;
107840                 while (true) {
107841                     command = npmPath + " install --ignore-scripts " + (toSlice === packageNames.length ? packageNames : packageNames.slice(sliceStart, sliceStart + toSlice)).join(" ") + " --save-dev --user-agent=\"typesInstaller/" + tsVersion + "\"";
107842                     if (command.length < 8000) {
107843                         break;
107844                     }
107845                     toSlice = toSlice - Math.floor(toSlice / 2);
107846                 }
107847                 return { command: command, remaining: remaining - toSlice };
107848             }
107849             typingsInstaller.getNpmCommandForInstallation = getNpmCommandForInstallation;
107850             function endsWith(str, suffix, caseSensitive) {
107851                 var expectedPos = str.length - suffix.length;
107852                 return expectedPos >= 0 &&
107853                     (str.indexOf(suffix, expectedPos) === expectedPos ||
107854                         (!caseSensitive && ts.compareStringsCaseInsensitive(str.substr(expectedPos), suffix) === 0 /* EqualTo */));
107855             }
107856             function isPackageOrBowerJson(fileName, caseSensitive) {
107857                 return endsWith(fileName, "/package.json", caseSensitive) || endsWith(fileName, "/bower.json", caseSensitive);
107858             }
107859             function sameFiles(a, b, caseSensitive) {
107860                 return a === b || (!caseSensitive && ts.compareStringsCaseInsensitive(a, b) === 0 /* EqualTo */);
107861             }
107862             var ProjectWatcherType;
107863             (function (ProjectWatcherType) {
107864                 ProjectWatcherType["FileWatcher"] = "FileWatcher";
107865                 ProjectWatcherType["DirectoryWatcher"] = "DirectoryWatcher";
107866             })(ProjectWatcherType || (ProjectWatcherType = {}));
107867             var TypingsInstaller = /** @class */ (function () {
107868                 function TypingsInstaller(installTypingHost, globalCachePath, safeListPath, typesMapLocation, throttleLimit, log) {
107869                     if (log === void 0) { log = nullLog; }
107870                     this.installTypingHost = installTypingHost;
107871                     this.globalCachePath = globalCachePath;
107872                     this.safeListPath = safeListPath;
107873                     this.typesMapLocation = typesMapLocation;
107874                     this.throttleLimit = throttleLimit;
107875                     this.log = log;
107876                     this.packageNameToTypingLocation = ts.createMap();
107877                     this.missingTypingsSet = ts.createMap();
107878                     this.knownCachesSet = ts.createMap();
107879                     this.projectWatchers = ts.createMap();
107880                     this.pendingRunRequests = [];
107881                     this.installRunCount = 1;
107882                     this.inFlightRequestCount = 0;
107883                     this.latestDistTag = "latest";
107884                     this.toCanonicalFileName = ts.createGetCanonicalFileName(installTypingHost.useCaseSensitiveFileNames);
107885                     this.globalCachePackageJsonPath = ts.combinePaths(globalCachePath, "package.json");
107886                     if (this.log.isEnabled()) {
107887                         this.log.writeLine("Global cache location '" + globalCachePath + "', safe file path '" + safeListPath + "', types map path " + typesMapLocation);
107888                     }
107889                     this.processCacheLocation(this.globalCachePath);
107890                 }
107891                 TypingsInstaller.prototype.closeProject = function (req) {
107892                     this.closeWatchers(req.projectName);
107893                 };
107894                 TypingsInstaller.prototype.closeWatchers = function (projectName) {
107895                     if (this.log.isEnabled()) {
107896                         this.log.writeLine("Closing file watchers for project '" + projectName + "'");
107897                     }
107898                     var watchers = this.projectWatchers.get(projectName);
107899                     if (!watchers) {
107900                         if (this.log.isEnabled()) {
107901                             this.log.writeLine("No watchers are registered for project '" + projectName + "'");
107902                         }
107903                         return;
107904                     }
107905                     ts.clearMap(watchers, ts.closeFileWatcher);
107906                     this.projectWatchers.delete(projectName);
107907                     if (this.log.isEnabled()) {
107908                         this.log.writeLine("Closing file watchers for project '" + projectName + "' - done.");
107909                     }
107910                 };
107911                 TypingsInstaller.prototype.install = function (req) {
107912                     var _this = this;
107913                     if (this.log.isEnabled()) {
107914                         this.log.writeLine("Got install request " + JSON.stringify(req));
107915                     }
107916                     // load existing typing information from the cache
107917                     if (req.cachePath) {
107918                         if (this.log.isEnabled()) {
107919                             this.log.writeLine("Request specifies cache path '" + req.cachePath + "', loading cached information...");
107920                         }
107921                         this.processCacheLocation(req.cachePath);
107922                     }
107923                     if (this.safeList === undefined) {
107924                         this.initializeSafeList();
107925                     }
107926                     var discoverTypingsResult = ts.JsTyping.discoverTypings(this.installTypingHost, this.log.isEnabled() ? (function (s) { return _this.log.writeLine(s); }) : undefined, req.fileNames, req.projectRootPath, this.safeList, this.packageNameToTypingLocation, req.typeAcquisition, req.unresolvedImports, this.typesRegistry);
107927                     if (this.log.isEnabled()) {
107928                         this.log.writeLine("Finished typings discovery: " + JSON.stringify(discoverTypingsResult));
107929                     }
107930                     // start watching files
107931                     this.watchFiles(req.projectName, discoverTypingsResult.filesToWatch, req.projectRootPath, req.watchOptions);
107932                     // install typings
107933                     if (discoverTypingsResult.newTypingNames.length) {
107934                         this.installTypings(req, req.cachePath || this.globalCachePath, discoverTypingsResult.cachedTypingPaths, discoverTypingsResult.newTypingNames);
107935                     }
107936                     else {
107937                         this.sendResponse(this.createSetTypings(req, discoverTypingsResult.cachedTypingPaths));
107938                         if (this.log.isEnabled()) {
107939                             this.log.writeLine("No new typings were requested as a result of typings discovery");
107940                         }
107941                     }
107942                 };
107943                 TypingsInstaller.prototype.initializeSafeList = function () {
107944                     // Prefer the safe list from the types map if it exists
107945                     if (this.typesMapLocation) {
107946                         var safeListFromMap = ts.JsTyping.loadTypesMap(this.installTypingHost, this.typesMapLocation);
107947                         if (safeListFromMap) {
107948                             this.log.writeLine("Loaded safelist from types map file '" + this.typesMapLocation + "'");
107949                             this.safeList = safeListFromMap;
107950                             return;
107951                         }
107952                         this.log.writeLine("Failed to load safelist from types map file '" + this.typesMapLocation + "'");
107953                     }
107954                     this.safeList = ts.JsTyping.loadSafeList(this.installTypingHost, this.safeListPath);
107955                 };
107956                 TypingsInstaller.prototype.processCacheLocation = function (cacheLocation) {
107957                     if (this.log.isEnabled()) {
107958                         this.log.writeLine("Processing cache location '" + cacheLocation + "'");
107959                     }
107960                     if (this.knownCachesSet.has(cacheLocation)) {
107961                         if (this.log.isEnabled()) {
107962                             this.log.writeLine("Cache location was already processed...");
107963                         }
107964                         return;
107965                     }
107966                     var packageJson = ts.combinePaths(cacheLocation, "package.json");
107967                     var packageLockJson = ts.combinePaths(cacheLocation, "package-lock.json");
107968                     if (this.log.isEnabled()) {
107969                         this.log.writeLine("Trying to find '" + packageJson + "'...");
107970                     }
107971                     if (this.installTypingHost.fileExists(packageJson) && this.installTypingHost.fileExists(packageLockJson)) {
107972                         var npmConfig = JSON.parse(this.installTypingHost.readFile(packageJson)); // TODO: GH#18217
107973                         var npmLock = JSON.parse(this.installTypingHost.readFile(packageLockJson)); // TODO: GH#18217
107974                         if (this.log.isEnabled()) {
107975                             this.log.writeLine("Loaded content of '" + packageJson + "': " + JSON.stringify(npmConfig));
107976                             this.log.writeLine("Loaded content of '" + packageLockJson + "'");
107977                         }
107978                         if (npmConfig.devDependencies && npmLock.dependencies) {
107979                             for (var key in npmConfig.devDependencies) {
107980                                 if (!ts.hasProperty(npmLock.dependencies, key)) {
107981                                     // if package in package.json but not package-lock.json, skip adding to cache so it is reinstalled on next use
107982                                     continue;
107983                                 }
107984                                 // key is @types/<package name>
107985                                 var packageName = ts.getBaseFileName(key);
107986                                 if (!packageName) {
107987                                     continue;
107988                                 }
107989                                 var typingFile = typingToFileName(cacheLocation, packageName, this.installTypingHost, this.log);
107990                                 if (!typingFile) {
107991                                     this.missingTypingsSet.set(packageName, true);
107992                                     continue;
107993                                 }
107994                                 var existingTypingFile = this.packageNameToTypingLocation.get(packageName);
107995                                 if (existingTypingFile) {
107996                                     if (existingTypingFile.typingLocation === typingFile) {
107997                                         continue;
107998                                     }
107999                                     if (this.log.isEnabled()) {
108000                                         this.log.writeLine("New typing for package " + packageName + " from '" + typingFile + "' conflicts with existing typing file '" + existingTypingFile + "'");
108001                                     }
108002                                 }
108003                                 if (this.log.isEnabled()) {
108004                                     this.log.writeLine("Adding entry into typings cache: '" + packageName + "' => '" + typingFile + "'");
108005                                 }
108006                                 var info = ts.getProperty(npmLock.dependencies, key);
108007                                 var version_1 = info && info.version;
108008                                 if (!version_1) {
108009                                     continue;
108010                                 }
108011                                 var newTyping = { typingLocation: typingFile, version: new ts.Version(version_1) };
108012                                 this.packageNameToTypingLocation.set(packageName, newTyping);
108013                             }
108014                         }
108015                     }
108016                     if (this.log.isEnabled()) {
108017                         this.log.writeLine("Finished processing cache location '" + cacheLocation + "'");
108018                     }
108019                     this.knownCachesSet.set(cacheLocation, true);
108020                 };
108021                 TypingsInstaller.prototype.filterTypings = function (typingsToInstall) {
108022                     var _this = this;
108023                     return ts.mapDefined(typingsToInstall, function (typing) {
108024                         var typingKey = ts.mangleScopedPackageName(typing);
108025                         if (_this.missingTypingsSet.get(typingKey)) {
108026                             if (_this.log.isEnabled())
108027                                 _this.log.writeLine("'" + typing + "':: '" + typingKey + "' is in missingTypingsSet - skipping...");
108028                             return undefined;
108029                         }
108030                         var validationResult = ts.JsTyping.validatePackageName(typing);
108031                         if (validationResult !== 0 /* Ok */) {
108032                             // add typing name to missing set so we won't process it again
108033                             _this.missingTypingsSet.set(typingKey, true);
108034                             if (_this.log.isEnabled())
108035                                 _this.log.writeLine(ts.JsTyping.renderPackageNameValidationFailure(validationResult, typing));
108036                             return undefined;
108037                         }
108038                         if (!_this.typesRegistry.has(typingKey)) {
108039                             if (_this.log.isEnabled())
108040                                 _this.log.writeLine("'" + typing + "':: Entry for package '" + typingKey + "' does not exist in local types registry - skipping...");
108041                             return undefined;
108042                         }
108043                         if (_this.packageNameToTypingLocation.get(typingKey) && ts.JsTyping.isTypingUpToDate(_this.packageNameToTypingLocation.get(typingKey), _this.typesRegistry.get(typingKey))) {
108044                             if (_this.log.isEnabled())
108045                                 _this.log.writeLine("'" + typing + "':: '" + typingKey + "' already has an up-to-date typing - skipping...");
108046                             return undefined;
108047                         }
108048                         return typingKey;
108049                     });
108050                 };
108051                 TypingsInstaller.prototype.ensurePackageDirectoryExists = function (directory) {
108052                     var npmConfigPath = ts.combinePaths(directory, "package.json");
108053                     if (this.log.isEnabled()) {
108054                         this.log.writeLine("Npm config file: " + npmConfigPath);
108055                     }
108056                     if (!this.installTypingHost.fileExists(npmConfigPath)) {
108057                         if (this.log.isEnabled()) {
108058                             this.log.writeLine("Npm config file: '" + npmConfigPath + "' is missing, creating new one...");
108059                         }
108060                         this.ensureDirectoryExists(directory, this.installTypingHost);
108061                         this.installTypingHost.writeFile(npmConfigPath, '{ "private": true }');
108062                     }
108063                 };
108064                 TypingsInstaller.prototype.installTypings = function (req, cachePath, currentlyCachedTypings, typingsToInstall) {
108065                     var _this = this;
108066                     if (this.log.isEnabled()) {
108067                         this.log.writeLine("Installing typings " + JSON.stringify(typingsToInstall));
108068                     }
108069                     var filteredTypings = this.filterTypings(typingsToInstall);
108070                     if (filteredTypings.length === 0) {
108071                         if (this.log.isEnabled()) {
108072                             this.log.writeLine("All typings are known to be missing or invalid - no need to install more typings");
108073                         }
108074                         this.sendResponse(this.createSetTypings(req, currentlyCachedTypings));
108075                         return;
108076                     }
108077                     this.ensurePackageDirectoryExists(cachePath);
108078                     var requestId = this.installRunCount;
108079                     this.installRunCount++;
108080                     // send progress event
108081                     this.sendResponse({
108082                         kind: server.EventBeginInstallTypes,
108083                         eventId: requestId,
108084                         // qualified explicitly to prevent occasional shadowing
108085                         // eslint-disable-next-line @typescript-eslint/no-unnecessary-qualifier
108086                         typingsInstallerVersion: ts.version,
108087                         projectName: req.projectName
108088                     });
108089                     var scopedTypings = filteredTypings.map(typingsName);
108090                     this.installTypingsAsync(requestId, scopedTypings, cachePath, function (ok) {
108091                         try {
108092                             if (!ok) {
108093                                 if (_this.log.isEnabled()) {
108094                                     _this.log.writeLine("install request failed, marking packages as missing to prevent repeated requests: " + JSON.stringify(filteredTypings));
108095                                 }
108096                                 for (var _i = 0, filteredTypings_1 = filteredTypings; _i < filteredTypings_1.length; _i++) {
108097                                     var typing = filteredTypings_1[_i];
108098                                     _this.missingTypingsSet.set(typing, true);
108099                                 }
108100                                 return;
108101                             }
108102                             // TODO: watch project directory
108103                             if (_this.log.isEnabled()) {
108104                                 _this.log.writeLine("Installed typings " + JSON.stringify(scopedTypings));
108105                             }
108106                             var installedTypingFiles = [];
108107                             for (var _a = 0, filteredTypings_2 = filteredTypings; _a < filteredTypings_2.length; _a++) {
108108                                 var packageName = filteredTypings_2[_a];
108109                                 var typingFile = typingToFileName(cachePath, packageName, _this.installTypingHost, _this.log);
108110                                 if (!typingFile) {
108111                                     _this.missingTypingsSet.set(packageName, true);
108112                                     continue;
108113                                 }
108114                                 // packageName is guaranteed to exist in typesRegistry by filterTypings
108115                                 var distTags = _this.typesRegistry.get(packageName);
108116                                 var newVersion = new ts.Version(distTags["ts" + ts.versionMajorMinor] || distTags[_this.latestDistTag]);
108117                                 var newTyping = { typingLocation: typingFile, version: newVersion };
108118                                 _this.packageNameToTypingLocation.set(packageName, newTyping);
108119                                 installedTypingFiles.push(typingFile);
108120                             }
108121                             if (_this.log.isEnabled()) {
108122                                 _this.log.writeLine("Installed typing files " + JSON.stringify(installedTypingFiles));
108123                             }
108124                             _this.sendResponse(_this.createSetTypings(req, currentlyCachedTypings.concat(installedTypingFiles)));
108125                         }
108126                         finally {
108127                             var response = {
108128                                 kind: server.EventEndInstallTypes,
108129                                 eventId: requestId,
108130                                 projectName: req.projectName,
108131                                 packagesToInstall: scopedTypings,
108132                                 installSuccess: ok,
108133                                 // qualified explicitly to prevent occasional shadowing
108134                                 // eslint-disable-next-line @typescript-eslint/no-unnecessary-qualifier
108135                                 typingsInstallerVersion: ts.version
108136                             };
108137                             _this.sendResponse(response);
108138                         }
108139                     });
108140                 };
108141                 TypingsInstaller.prototype.ensureDirectoryExists = function (directory, host) {
108142                     var directoryName = ts.getDirectoryPath(directory);
108143                     if (!host.directoryExists(directoryName)) {
108144                         this.ensureDirectoryExists(directoryName, host);
108145                     }
108146                     if (!host.directoryExists(directory)) {
108147                         host.createDirectory(directory);
108148                     }
108149                 };
108150                 TypingsInstaller.prototype.watchFiles = function (projectName, files, projectRootPath, options) {
108151                     var _this = this;
108152                     if (!files.length) {
108153                         // shut down existing watchers
108154                         this.closeWatchers(projectName);
108155                         return;
108156                     }
108157                     var watchers = this.projectWatchers.get(projectName);
108158                     var toRemove = ts.createMap();
108159                     if (!watchers) {
108160                         watchers = ts.createMap();
108161                         this.projectWatchers.set(projectName, watchers);
108162                     }
108163                     else {
108164                         ts.copyEntries(watchers, toRemove);
108165                     }
108166                     // handler should be invoked once for the entire set of files since it will trigger full rediscovery of typings
108167                     watchers.isInvoked = false;
108168                     var isLoggingEnabled = this.log.isEnabled();
108169                     var createProjectWatcher = function (path, projectWatcherType) {
108170                         var canonicalPath = _this.toCanonicalFileName(path);
108171                         toRemove.delete(canonicalPath);
108172                         if (watchers.has(canonicalPath)) {
108173                             return;
108174                         }
108175                         if (isLoggingEnabled) {
108176                             _this.log.writeLine(projectWatcherType + ":: Added:: WatchInfo: " + path);
108177                         }
108178                         var watcher = projectWatcherType === "FileWatcher" /* FileWatcher */ ?
108179                             _this.installTypingHost.watchFile(path, function (f, eventKind) {
108180                                 if (isLoggingEnabled) {
108181                                     _this.log.writeLine("FileWatcher:: Triggered with " + f + " eventKind: " + ts.FileWatcherEventKind[eventKind] + ":: WatchInfo: " + path + ":: handler is already invoked '" + watchers.isInvoked + "'");
108182                                 }
108183                                 if (!watchers.isInvoked) {
108184                                     watchers.isInvoked = true;
108185                                     _this.sendResponse({ projectName: projectName, kind: server.ActionInvalidate });
108186                                 }
108187                             }, /*pollingInterval*/ 2000, options) :
108188                             _this.installTypingHost.watchDirectory(path, function (f) {
108189                                 if (isLoggingEnabled) {
108190                                     _this.log.writeLine("DirectoryWatcher:: Triggered with " + f + " :: WatchInfo: " + path + " recursive :: handler is already invoked '" + watchers.isInvoked + "'");
108191                                 }
108192                                 if (watchers.isInvoked || !ts.fileExtensionIs(f, ".json" /* Json */)) {
108193                                     return;
108194                                 }
108195                                 if (isPackageOrBowerJson(f, _this.installTypingHost.useCaseSensitiveFileNames) &&
108196                                     !sameFiles(f, _this.globalCachePackageJsonPath, _this.installTypingHost.useCaseSensitiveFileNames)) {
108197                                     watchers.isInvoked = true;
108198                                     _this.sendResponse({ projectName: projectName, kind: server.ActionInvalidate });
108199                                 }
108200                             }, /*recursive*/ true, options);
108201                         watchers.set(canonicalPath, isLoggingEnabled ? {
108202                             close: function () {
108203                                 _this.log.writeLine(projectWatcherType + ":: Closed:: WatchInfo: " + path);
108204                                 watcher.close();
108205                             }
108206                         } : watcher);
108207                     };
108208                     // Create watches from list of files
108209                     for (var _i = 0, files_1 = files; _i < files_1.length; _i++) {
108210                         var file = files_1[_i];
108211                         if (file.endsWith("/package.json") || file.endsWith("/bower.json")) {
108212                             // package.json or bower.json exists, watch the file to detect changes and update typings
108213                             createProjectWatcher(file, "FileWatcher" /* FileWatcher */);
108214                             continue;
108215                         }
108216                         // path in projectRoot, watch project root
108217                         if (ts.containsPath(projectRootPath, file, projectRootPath, !this.installTypingHost.useCaseSensitiveFileNames)) {
108218                             var subDirectory = file.indexOf(ts.directorySeparator, projectRootPath.length + 1);
108219                             if (subDirectory !== -1) {
108220                                 // Watch subDirectory
108221                                 createProjectWatcher(file.substr(0, subDirectory), "DirectoryWatcher" /* DirectoryWatcher */);
108222                             }
108223                             else {
108224                                 // Watch the directory itself
108225                                 createProjectWatcher(file, "DirectoryWatcher" /* DirectoryWatcher */);
108226                             }
108227                             continue;
108228                         }
108229                         // path in global cache, watch global cache
108230                         if (ts.containsPath(this.globalCachePath, file, projectRootPath, !this.installTypingHost.useCaseSensitiveFileNames)) {
108231                             createProjectWatcher(this.globalCachePath, "DirectoryWatcher" /* DirectoryWatcher */);
108232                             continue;
108233                         }
108234                         // watch node_modules or bower_components
108235                         createProjectWatcher(file, "DirectoryWatcher" /* DirectoryWatcher */);
108236                     }
108237                     // Remove unused watches
108238                     toRemove.forEach(function (watch, path) {
108239                         watch.close();
108240                         watchers.delete(path);
108241                     });
108242                 };
108243                 TypingsInstaller.prototype.createSetTypings = function (request, typings) {
108244                     return {
108245                         projectName: request.projectName,
108246                         typeAcquisition: request.typeAcquisition,
108247                         compilerOptions: request.compilerOptions,
108248                         typings: typings,
108249                         unresolvedImports: request.unresolvedImports,
108250                         kind: server.ActionSet
108251                     };
108252                 };
108253                 TypingsInstaller.prototype.installTypingsAsync = function (requestId, packageNames, cwd, onRequestCompleted) {
108254                     this.pendingRunRequests.unshift({ requestId: requestId, packageNames: packageNames, cwd: cwd, onRequestCompleted: onRequestCompleted });
108255                     this.executeWithThrottling();
108256                 };
108257                 TypingsInstaller.prototype.executeWithThrottling = function () {
108258                     var _this = this;
108259                     var _loop_1 = function () {
108260                         this_1.inFlightRequestCount++;
108261                         var request = this_1.pendingRunRequests.pop();
108262                         this_1.installWorker(request.requestId, request.packageNames, request.cwd, function (ok) {
108263                             _this.inFlightRequestCount--;
108264                             request.onRequestCompleted(ok);
108265                             _this.executeWithThrottling();
108266                         });
108267                     };
108268                     var this_1 = this;
108269                     while (this.inFlightRequestCount < this.throttleLimit && this.pendingRunRequests.length) {
108270                         _loop_1();
108271                     }
108272                 };
108273                 return TypingsInstaller;
108274             }());
108275             typingsInstaller.TypingsInstaller = TypingsInstaller;
108276             /* @internal */
108277             function typingsName(packageName) {
108278                 return "@types/" + packageName + "@ts" + ts.versionMajorMinor;
108279             }
108280             typingsInstaller.typingsName = typingsName;
108281         })(typingsInstaller = server.typingsInstaller || (server.typingsInstaller = {}));
108282     })(server = ts.server || (ts.server = {}));
108283 })(ts || (ts = {}));
108284 var ts;
108285 (function (ts) {
108286     var server;
108287     (function (server) {
108288         var typingsInstaller;
108289         (function (typingsInstaller) {
108290             var fs = require("fs");
108291             var path = require("path");
108292             var FileLog = (function () {
108293                 function FileLog(logFile) {
108294                     var _this = this;
108295                     this.logFile = logFile;
108296                     this.isEnabled = function () {
108297                         return typeof _this.logFile === "string";
108298                     };
108299                     this.writeLine = function (text) {
108300                         if (typeof _this.logFile !== "string")
108301                             return;
108302                         try {
108303                             fs.appendFileSync(_this.logFile, "[" + server.nowString() + "] " + text + ts.sys.newLine);
108304                         }
108305                         catch (e) {
108306                             _this.logFile = undefined;
108307                         }
108308                     };
108309                 }
108310                 return FileLog;
108311             }());
108312             function getDefaultNPMLocation(processName, validateDefaultNpmLocation, host) {
108313                 if (path.basename(processName).indexOf("node") === 0) {
108314                     var npmPath = path.join(path.dirname(process.argv[0]), "npm");
108315                     if (!validateDefaultNpmLocation) {
108316                         return npmPath;
108317                     }
108318                     if (host.fileExists(npmPath)) {
108319                         return "\"" + npmPath + "\"";
108320                     }
108321                 }
108322                 return "npm";
108323             }
108324             function loadTypesRegistryFile(typesRegistryFilePath, host, log) {
108325                 if (!host.fileExists(typesRegistryFilePath)) {
108326                     if (log.isEnabled()) {
108327                         log.writeLine("Types registry file '" + typesRegistryFilePath + "' does not exist");
108328                     }
108329                     return ts.createMap();
108330                 }
108331                 try {
108332                     var content = JSON.parse(host.readFile(typesRegistryFilePath));
108333                     return ts.createMapFromTemplate(content.entries);
108334                 }
108335                 catch (e) {
108336                     if (log.isEnabled()) {
108337                         log.writeLine("Error when loading types registry file '" + typesRegistryFilePath + "': " + e.message + ", " + e.stack);
108338                     }
108339                     return ts.createMap();
108340                 }
108341             }
108342             var typesRegistryPackageName = "types-registry";
108343             function getTypesRegistryFileLocation(globalTypingsCacheLocation) {
108344                 return ts.combinePaths(ts.normalizeSlashes(globalTypingsCacheLocation), "node_modules/" + typesRegistryPackageName + "/index.json");
108345             }
108346             var NodeTypingsInstaller = (function (_super) {
108347                 __extends(NodeTypingsInstaller, _super);
108348                 function NodeTypingsInstaller(globalTypingsCacheLocation, typingSafeListLocation, typesMapLocation, npmLocation, validateDefaultNpmLocation, throttleLimit, log) {
108349                     var _this = _super.call(this, ts.sys, globalTypingsCacheLocation, typingSafeListLocation ? ts.toPath(typingSafeListLocation, "", ts.createGetCanonicalFileName(ts.sys.useCaseSensitiveFileNames)) : ts.toPath("typingSafeList.json", __dirname, ts.createGetCanonicalFileName(ts.sys.useCaseSensitiveFileNames)), typesMapLocation ? ts.toPath(typesMapLocation, "", ts.createGetCanonicalFileName(ts.sys.useCaseSensitiveFileNames)) : ts.toPath("typesMap.json", __dirname, ts.createGetCanonicalFileName(ts.sys.useCaseSensitiveFileNames)), throttleLimit, log) || this;
108350                     _this.npmPath = npmLocation !== undefined ? npmLocation : getDefaultNPMLocation(process.argv[0], validateDefaultNpmLocation, _this.installTypingHost);
108351                     if (ts.stringContains(_this.npmPath, " ") && _this.npmPath[0] !== "\"") {
108352                         _this.npmPath = "\"" + _this.npmPath + "\"";
108353                     }
108354                     if (_this.log.isEnabled()) {
108355                         _this.log.writeLine("Process id: " + process.pid);
108356                         _this.log.writeLine("NPM location: " + _this.npmPath + " (explicit '" + server.Arguments.NpmLocation + "' " + (npmLocation === undefined ? "not " : "") + " provided)");
108357                         _this.log.writeLine("validateDefaultNpmLocation: " + validateDefaultNpmLocation);
108358                     }
108359                     (_this.nodeExecSync = require("child_process").execSync);
108360                     _this.ensurePackageDirectoryExists(globalTypingsCacheLocation);
108361                     try {
108362                         if (_this.log.isEnabled()) {
108363                             _this.log.writeLine("Updating " + typesRegistryPackageName + " npm package...");
108364                         }
108365                         _this.execSyncAndLog(_this.npmPath + " install --ignore-scripts " + typesRegistryPackageName + "@" + _this.latestDistTag, { cwd: globalTypingsCacheLocation });
108366                         if (_this.log.isEnabled()) {
108367                             _this.log.writeLine("Updated " + typesRegistryPackageName + " npm package");
108368                         }
108369                     }
108370                     catch (e) {
108371                         if (_this.log.isEnabled()) {
108372                             _this.log.writeLine("Error updating " + typesRegistryPackageName + " package: " + e.message);
108373                         }
108374                         _this.delayedInitializationError = {
108375                             kind: "event::initializationFailed",
108376                             message: e.message
108377                         };
108378                     }
108379                     _this.typesRegistry = loadTypesRegistryFile(getTypesRegistryFileLocation(globalTypingsCacheLocation), _this.installTypingHost, _this.log);
108380                     return _this;
108381                 }
108382                 NodeTypingsInstaller.prototype.listen = function () {
108383                     var _this = this;
108384                     process.on("message", function (req) {
108385                         if (_this.delayedInitializationError) {
108386                             _this.sendResponse(_this.delayedInitializationError);
108387                             _this.delayedInitializationError = undefined;
108388                         }
108389                         switch (req.kind) {
108390                             case "discover":
108391                                 _this.install(req);
108392                                 break;
108393                             case "closeProject":
108394                                 _this.closeProject(req);
108395                                 break;
108396                             case "typesRegistry": {
108397                                 var typesRegistry_1 = {};
108398                                 _this.typesRegistry.forEach(function (value, key) {
108399                                     typesRegistry_1[key] = value;
108400                                 });
108401                                 var response = { kind: server.EventTypesRegistry, typesRegistry: typesRegistry_1 };
108402                                 _this.sendResponse(response);
108403                                 break;
108404                             }
108405                             case "installPackage": {
108406                                 var fileName = req.fileName, packageName_1 = req.packageName, projectName_1 = req.projectName, projectRootPath = req.projectRootPath;
108407                                 var cwd = getDirectoryOfPackageJson(fileName, _this.installTypingHost) || projectRootPath;
108408                                 if (cwd) {
108409                                     _this.installWorker(-1, [packageName_1], cwd, function (success) {
108410                                         var message = success ? "Package " + packageName_1 + " installed." : "There was an error installing " + packageName_1 + ".";
108411                                         var response = { kind: server.ActionPackageInstalled, projectName: projectName_1, success: success, message: message };
108412                                         _this.sendResponse(response);
108413                                     });
108414                                 }
108415                                 else {
108416                                     var response = { kind: server.ActionPackageInstalled, projectName: projectName_1, success: false, message: "Could not determine a project root path." };
108417                                     _this.sendResponse(response);
108418                                 }
108419                                 break;
108420                             }
108421                             default:
108422                                 ts.Debug.assertNever(req);
108423                         }
108424                     });
108425                 };
108426                 NodeTypingsInstaller.prototype.sendResponse = function (response) {
108427                     if (this.log.isEnabled()) {
108428                         this.log.writeLine("Sending response:\n    " + JSON.stringify(response));
108429                     }
108430                     process.send(response);
108431                     if (this.log.isEnabled()) {
108432                         this.log.writeLine("Response has been sent.");
108433                     }
108434                 };
108435                 NodeTypingsInstaller.prototype.installWorker = function (requestId, packageNames, cwd, onRequestCompleted) {
108436                     var _this = this;
108437                     if (this.log.isEnabled()) {
108438                         this.log.writeLine("#" + requestId + " with arguments'" + JSON.stringify(packageNames) + "'.");
108439                     }
108440                     var start = Date.now();
108441                     var hasError = typingsInstaller.installNpmPackages(this.npmPath, ts.version, packageNames, function (command) { return _this.execSyncAndLog(command, { cwd: cwd }); });
108442                     if (this.log.isEnabled()) {
108443                         this.log.writeLine("npm install #" + requestId + " took: " + (Date.now() - start) + " ms");
108444                     }
108445                     onRequestCompleted(!hasError);
108446                 };
108447                 NodeTypingsInstaller.prototype.execSyncAndLog = function (command, options) {
108448                     if (this.log.isEnabled()) {
108449                         this.log.writeLine("Exec: " + command);
108450                     }
108451                     try {
108452                         var stdout = this.nodeExecSync(command, __assign(__assign({}, options), { encoding: "utf-8" }));
108453                         if (this.log.isEnabled()) {
108454                             this.log.writeLine("    Succeeded. stdout:" + indent(ts.sys.newLine, stdout));
108455                         }
108456                         return false;
108457                     }
108458                     catch (error) {
108459                         var stdout = error.stdout, stderr = error.stderr;
108460                         this.log.writeLine("    Failed. stdout:" + indent(ts.sys.newLine, stdout) + ts.sys.newLine + "    stderr:" + indent(ts.sys.newLine, stderr));
108461                         return true;
108462                     }
108463                 };
108464                 return NodeTypingsInstaller;
108465             }(typingsInstaller.TypingsInstaller));
108466             typingsInstaller.NodeTypingsInstaller = NodeTypingsInstaller;
108467             function getDirectoryOfPackageJson(fileName, host) {
108468                 return ts.forEachAncestorDirectory(ts.getDirectoryPath(fileName), function (directory) {
108469                     if (host.fileExists(ts.combinePaths(directory, "package.json"))) {
108470                         return directory;
108471                     }
108472                 });
108473             }
108474             var logFilePath = server.findArgument(server.Arguments.LogFile);
108475             var globalTypingsCacheLocation = server.findArgument(server.Arguments.GlobalCacheLocation);
108476             var typingSafeListLocation = server.findArgument(server.Arguments.TypingSafeListLocation);
108477             var typesMapLocation = server.findArgument(server.Arguments.TypesMapLocation);
108478             var npmLocation = server.findArgument(server.Arguments.NpmLocation);
108479             var validateDefaultNpmLocation = server.hasArgument(server.Arguments.ValidateDefaultNpmLocation);
108480             var log = new FileLog(logFilePath);
108481             if (log.isEnabled()) {
108482                 process.on("uncaughtException", function (e) {
108483                     log.writeLine("Unhandled exception: " + e + " at " + e.stack);
108484                 });
108485             }
108486             process.on("disconnect", function () {
108487                 if (log.isEnabled()) {
108488                     log.writeLine("Parent process has exited, shutting down...");
108489                 }
108490                 process.exit(0);
108491             });
108492             var installer = new NodeTypingsInstaller(globalTypingsCacheLocation, typingSafeListLocation, typesMapLocation, npmLocation, validateDefaultNpmLocation, 5, log);
108493             installer.listen();
108494             function indent(newline, str) {
108495                 return newline + "    " + str.replace(/\r?\n/, newline + "    ");
108496             }
108497         })(typingsInstaller = server.typingsInstaller || (server.typingsInstaller = {}));
108498     })(server = ts.server || (ts.server = {}));
108499 })(ts || (ts = {}));
108500 //# sourceMappingURL=typingsInstaller.js.map